text,length,is_long_context,metric_val,label_metric "/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2019 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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.*/ #include ""stdafx.h"" #include ""FERigidSolver.h"" #include ""FESolidSolver2.h"" #include ""FERigidMaterial.h"" #include #include #include #include #include #include #include #include #include FERigidSolver::FERigidSolver(FEModel* fem) : m_fem(fem) { m_dofX = m_dofY = m_dofZ = -1; m_bAllowMixedBCs = false; } int FERigidSolver::InitEquations(int neq) { // Next, we assign equation numbers to the rigid body degrees of freedom FERigidSystem& rigid = *m_fem->GetRigidSystem(); int nrb = rigid.Objects(); for (int i = 0; iGetDOFIndex(""x""); m_dofY = m_fem->GetDOFIndex(""y""); m_dofZ = m_fem->GetDOFIndex(""z""); m_dofVX = m_fem->GetDOFIndex(""vx""); m_dofVY = m_fem->GetDOFIndex(""vy""); m_dofVZ = m_fem->GetDOFIndex(""vz""); m_dofU = m_fem->GetDOFIndex(""u""); m_dofV = m_fem->GetDOFIndex(""v""); m_dofW = m_fem->GetDOFIndex(""w""); m_dofSX = m_fem->GetDOFIndex(""sx""); m_dofSY = m_fem->GetDOFIndex(""sy""); m_dofSZ = m_fem->GetDOFIndex(""sz""); m_dofSVX = m_fem->GetDOFIndex(""svx""); m_dofSVY = m_fem->GetDOFIndex(""svy""); m_dofSVZ = m_fem->GetDOFIndex(""svz""); int dofRU = m_fem->GetDOFIndex(""Ru""); int dofRV = m_fem->GetDOFIndex(""Rv""); int dofRW = m_fem->GetDOFIndex(""Rw""); // we assign the rigid body equation number to // Also make sure that the nodes are NOT constrained! FEMesh& mesh = m_fem->GetMesh(); for (int i = 0; i= 0) { FERigidBody& RB = *rigid.Object(node.m_rid); node.m_ID[m_dofX] = (RB.m_LM[0] >= 0 ? -RB.m_LM[0] - 2 : RB.m_LM[0]); node.m_ID[m_dofY] = (RB.m_LM[1] >= 0 ? -RB.m_LM[1] - 2 : RB.m_LM[1]); node.m_ID[m_dofZ] = (RB.m_LM[2] >= 0 ? -RB.m_LM[2] - 2 : RB.m_LM[2]); node.m_ID[dofRU] = (RB.m_LM[3] >= 0 ? -RB.m_LM[3] - 2 : RB.m_LM[3]); node.m_ID[dofRV] = (RB.m_LM[4] >= 0 ? -RB.m_LM[4] - 2 : RB.m_LM[4]); node.m_ID[dofRW] = (RB.m_LM[5] >= 0 ? -RB.m_LM[5] - 2 : RB.m_LM[5]); if (node.HasFlags(FENode::SHELL) && node.HasFlags(FENode::RIGID_CLAMP)) { node.m_ID[m_dofU] = (RB.m_LM[0] >= 0 ? -RB.m_LM[0] - 2 : RB.m_LM[0]); node.m_ID[m_dofV] = (RB.m_LM[1] >= 0 ? -RB.m_LM[1] - 2 : RB.m_LM[1]); node.m_ID[m_dofW] = (RB.m_LM[2] >= 0 ? -RB.m_LM[2] - 2 : RB.m_LM[2]); node.m_ID[m_dofSX] = (RB.m_LM[0] >= 0 ? -RB.m_LM[0] - 2 : RB.m_LM[0]); node.m_ID[m_dofSY] = (RB.m_LM[1] >= 0 ? -RB.m_LM[1] - 2 : RB.m_LM[1]); node.m_ID[m_dofSZ] = (RB.m_LM[2] >= 0 ? -RB.m_LM[2] - 2 : RB.m_LM[2]); } } } return neq; } //----------------------------------------------------------------------------- //! Serialization void FERigidSolver::Serialize(DumpStream& ar) { if (ar.IsShallow()) return; if (ar.IsSaving()) { ar << m_dofX << m_dofY << m_dofZ; ar << m_dofVX << m_dofVY << m_dofVZ; ar << m_dofU << m_dofV << m_dofW; ar << m_dofSX << m_dofSY << m_dofSZ; ar << m_dofSVX << m_dofSVY << m_dofSVZ; ar << m_bAllowMixedBCs; } else { ar >> m_dofX >> m_dofY >> m_dofZ; ar >> m_dofVX >> m_dofVY >> m_dofVZ; ar >> m_dofU >> m_dofV >> m_dofW; ar >> m_dofSX >> m_dofSY >> m_dofSZ; ar >> m_dofSVX >> m_dofSVY >> m_dofSVZ; ar >> m_bAllowMixedBCs; } } //----------------------------------------------------------------------------- // \\todo: eliminate need for ui parameter void FERigidSolver::PrepStep(const FETimeInfo& timeInfo, vector& ui) { FERigidSystem& rigid = *m_fem->GetRigidSystem(); int NO = rigid.Objects(); for (int i = 0; iInit(); // calculate local rigid displacements for (int i = 0; i= 0) { RB.m_dul[I] = DC.Value() - RB.m_Ut[DC.bc]; } } } // calculate global rigid displacements for (int i = 0; im_rt; dul = pprb->m_dul; quatd Q1 = pprb->GetRotation(); dr = r0 + dr - r1; // grab the parent's local displacements vec3d dR = vec3d(dul[0], dul[1], dul[2]); v = vec3d(dul[3], dul[4], dul[5]); w = sqrt(v.x*v.x + v.y*v.y + v.z*v.z); quatd dQ = quatd(w, v); dQ = Q1*dQ*Q1.Inverse(); // update global displacements quatd Qi = Q1.Inverse(); dr = dR + r1 + dQ*dr - r0; dq = dQ*dq; // move up in the chain pprb = pprb->m_prb; Q0 = Q1; } // set global displacements double* du = RB.m_du; du[0] = dr.x; du[1] = dr.y; du[2] = dr.z; v = dq.GetVector(); w = dq.GetAngle(); du[3] = w*v.x; du[4] = w*v.y; du[5] = w*v.z; } } } // store rigid displacements in Ui vector for (int i = 0; i= 0) ui[I] = RB.m_du[j]; } } FEAnalysis* pstep = m_fem->GetCurrentStep(); if (pstep->m_nanalysis == FE_DYNAMIC) { FEMesh& mesh = m_fem->GetMesh(); // set the initial velocities of all rigid nodes for (int i = 0; i= 0) { FERigidBody& rb = *rigid.Object(n.m_rid); vec3d V = rb.m_vt; vec3d W = rb.m_wt; vec3d r = n.m_rt - rb.m_rt; vec3d v = V + (W ^ r); n.m_vp = v; n.set_vec3d(m_dofVX, m_dofVY, m_dofVZ, v); vec3d a = (W ^ V)*2.0 + (W ^ (W ^ r)); n.m_ap = n.m_at = a; } } } // store the current rigid body reaction forces for (int i = 0; i& ui, vector& F, vector& en, vector& elm, matrix& ke, double alpha) { int n = (int)en.size(); FEMesh& mesh = m_fem->GetMesh(); bool bclamped_shell = false; for (int j = 0; j& ui, vector& F, vector& en, vector& elm, matrix& ke, double alpha) { FERigidSystem& rigid = *m_fem->GetRigidSystem(); if (rigid.Objects() == 0) return; int i, j, k, l, n = (int)en.size(); // get nodal DOFS DOFS& fedofs = m_fem->GetDOFS(); int MAX_NDOFS = fedofs.GetTotalDOFS(); int ndof = ke.columns() / n; matrix kij(ndof, ndof); matrix KF(ndof, 6); double KR[6][6]; int *lmi, *lmj; int I, J; vec3d zi, zj; mat3d Zi, Zj; FEMesh& mesh = m_fem->GetMesh(); // loop over columns for (j = 0; j= 0) { // this is a rigid interface node // get the rigid body this node is attached to FERigidBody& RBj = *rigid.Object(nodej.m_rid); // get the rigid body equation nrs. lmj = RBj.m_LM; // get the relative distance to the center of mass zj = nodej.m_rt - RBj.m_rt; Zj.skew(zj); // loop over rows for (i = 0; i= 0) { // node i is also a rigid body node // get the rigid body this node is attached to FERigidBody& RBi = *rigid.Object(nodei.m_rid); lmi = RBi.m_LM; // get the relative distance (use alpha rule) zi = (nodei.m_rt - RBi.m_rt)*alpha + (nodei.m_rp - RBi.m_rp)*(1 - alpha); Zi.skew(zi); mat3d M; // Kuu transformation to Krr M = Kuu*alpha; KR[0][0] = M[0][0]; KR[0][1] = M[0][1]; KR[0][2] = M[0][2]; KR[1][0] = M[1][0]; KR[1][1] = M[1][1]; KR[1][2] = M[1][2]; KR[2][0] = M[2][0]; KR[2][1] = M[2][1]; KR[2][2] = M[2][2]; // Kuu transformation to Krq M = Kuu*Zj*(-alpha); KR[0][3] = M[0][0]; KR[0][4] = M[0][1]; KR[0][5] = M[0][2]; KR[1][3] = M[1][0]; KR[1][4] = M[1][1]; KR[1][5] = M[1][2]; KR[2][3] = M[2][0]; KR[2][4] = M[2][1]; KR[2][5] = M[2][2]; // Kuu transformation to Kqr M = Zi*Kuu*alpha; KR[3][0] = M[0][0]; KR[3][1] = M[0][1]; KR[3][2] = M[0][2]; KR[4][0] = M[1][0]; KR[4][1] = M[1][1]; KR[4][2] = M[1][2]; KR[5][0] = M[2][0]; KR[5][1] = M[2][1]; KR[5][2] = M[2][2]; // Kuu transformation to Kqq M = Zi*Kuu*Zj*(-alpha); KR[3][3] = M[0][0]; KR[3][4] = M[0][1]; KR[3][5] = M[0][2]; KR[4][3] = M[1][0]; KR[4][4] = M[1][1]; KR[4][5] = M[1][2]; KR[5][3] = M[2][0]; KR[5][4] = M[2][1]; KR[5][5] = M[2][2]; // add the stiffness components to the Krr matrix for (k = 0; k<6; ++k) for (l = 0; l<6; ++l) { J = lmj[k]; I = lmi[l]; if (I >= 0) { // multiply KR by alpha for alpha rule if (J < -1) F[I] -= KR[l][k]*ui[-J - 2]; else if (J >= 0) K.add(I, J, KR[l][k]); } } // we still need to couple the non-rigid degrees of node i to the // rigid dofs of node j for (k = 3; k= 0) { // multiply KF by alpha for alpha rule if (J < -1) F[I] -= KF[l][k] * ui[-J - 2]; else if (J >= 0) K.add(I, J, KF[l][k]); } } // now the transpose location for (l = 3; l= 0) { if (J < -1) F[I] -= KF[l][k] * ui[-J - 2]; else if (J >= 0) K.add(I, J, KF[l][k]); } } } else { // node i is not a rigid body node // add the stiffness components to the Kfr matrix // Kij for (k = 0; k= 0) { // multiply KF by alpha for alpha rule if (J < -1) F[I] -= KF[l][k] * ui[-J - 2]; else if (J >= 0) K.add(I, J, KF[l][k]); } } } } } else { // loop over rows for (i = 0; i= 0) { // node i is a rigid body // get the rigid body this node is attached to FERigidBody& RBi = *rigid.Object(nodei.m_rid); // get the rigid body equation nrs. lmi = RBi.m_LM; // get the relative distance (use alpha rule) zi = (nodei.m_rt - RBi.m_rt)*alpha + (nodei.m_rp - RBi.m_rp)*(1 - alpha); Zi.skew(zi); // get the element sub-matrix for (k = 0; k= 0) { if (J < -1) F[I] -= KF[l][k] * ui[-J - 2]; else if (J >= 0) K.add(I, J, KF[l][k]); } } } } } } } //----------------------------------------------------------------------------- //! This function calculates the rigid stiffness matrices //! correct stiffness matrix for rigid bodies accounting for rigid-body-deformable-shell interfaces void FERigidSolver::RigidStiffnessShell(SparseMatrix& K, vector& ui, vector& F, vector& en, vector& elm, matrix& ke, double alpha) { FERigidSystem& rigid = *m_fem->GetRigidSystem(); if (rigid.Objects() == 0) return; int i, j, k, l, n = (int)en.size(); // get nodal DOFS DOFS& fedofs = m_fem->GetDOFS(); int MAX_NDOFS = fedofs.GetTotalDOFS(); vector< vector > kij; kij.assign(MAX_NDOFS, vector(MAX_NDOFS)); vector< vector > KF; KF.assign(MAX_NDOFS, vector(6)); double KR[6][6]; int *lmi, *lmj; int I, J; vec3d ai, aj, bi, bj; mat3d Ai, Aj, Bi, Bj; int ndof = ke.columns() / n; FEMesh& mesh = m_fem->GetMesh(); // loop over columns for (j = 0; j= 0) { // this is a rigid interface node // get the rigid body this node is attached to FERigidBody& RBj = *rigid.Object(nodej.m_rid); // get the rigid body equation nrs. lmj = RBj.m_LM; // get the relative distance to the center of mass aj = nodej.m_rt - RBj.m_rt; Aj.skew(aj); // get the shell director bj = aj - (nodej.m_d0 + nodej.get_vec3d(m_dofX, m_dofY, m_dofZ) - nodej.get_vec3d(m_dofSX, m_dofSY, m_dofSZ)); Bj.skew(bj); // loop over rows for (i = 0; i= 0) { // node i is also a rigid body node // get the rigid body this node is attached to FERigidBody& RBi = *rigid.Object(nodei.m_rid); lmi = RBi.m_LM; // get the relative distance (use alpha rule) ai = (nodei.m_rt - RBi.m_rt)*alpha + (nodei.m_rp - RBi.m_rp)*(1 - alpha); Ai.skew(ai); // get the shell director bi = ai - (nodei.m_d0 + nodei.get_vec3d(m_dofX, m_dofY, m_dofZ) - nodei.get_vec3d(m_dofSX, m_dofSY, m_dofSZ)); Bi.skew(bi); mat3d M; // Kuu transformation M = (Kuu + Kwu + Kuw + Kww)*alpha; KR[0][0] = M[0][0]; KR[0][1] = M[0][1]; KR[0][2] = M[0][2]; KR[1][0] = M[1][0]; KR[1][1] = M[1][1]; KR[1][2] = M[1][2]; KR[2][0] = M[2][0]; KR[2][1] = M[2][1]; KR[2][2] = M[2][2]; // Kuw transformation M = ((Kuu + Kwu)*Aj + (Kuw + Kww)*Bj)*(-alpha); KR[0][3] = M[0][0]; KR[0][4] = M[0][1]; KR[0][5] = M[0][2]; KR[1][3] = M[1][0]; KR[1][4] = M[1][1]; KR[1][5] = M[1][2]; KR[2][3] = M[2][0]; KR[2][4] = M[2][1]; KR[2][5] = M[2][2]; // Kwu transformation M = (Ai*(Kuu + Kuw) + Bi*(Kwu + Kww))*alpha; KR[3][0] = M[0][0]; KR[3][1] = M[0][1]; KR[3][2] = M[0][2]; KR[4][0] = M[1][0]; KR[4][1] = M[1][1]; KR[4][2] = M[1][2]; KR[5][0] = M[2][0]; KR[5][1] = M[2][1]; KR[5][2] = M[2][2]; // Kww transformation M = ((Ai*Kuu + Bi*Kwu)*Aj + (Ai*Kuw + Bi*Kww)*Bj)*(-alpha); KR[3][3] = M[0][0]; KR[3][4] = M[0][1]; KR[3][5] = M[0][2]; KR[4][3] = M[1][0]; KR[4][4] = M[1][1]; KR[4][5] = M[1][2]; KR[5][3] = M[2][0]; KR[5][4] = M[2][1]; KR[5][5] = M[2][2]; // add the stiffness components to the Krr matrix for (k = 0; k<6; ++k) for (l = 0; l<6; ++l) { J = lmj[k]; I = lmi[l]; if (I >= 0) { // multiply KR by alpha for alpha rule if (J < -1) F[I] -= KR[l][k]*ui[-J - 2]; else if (J >= 0) K.add(I, J, KR[l][k]); } } // we still need to couple the non-rigid degrees of node i to the // rigid dofs of node j for (k = 6; k= 0) { // multiply KF by alpha for alpha rule if (J < -1) F[I] -= KF[l][k] * ui[-J - 2]; else if (J >= 0) K.add(I, J, KF[l][k]); } } // now the transpose location for (l = 6; l= 0) { if (J < -1) F[I] -= KF[l][k] * ui[-J - 2]; else if (J >= 0) K.add(I, J, KF[l][k]); } } } else { // node i is not a rigid body node // add the stiffness components to the Kfr matrix // Kij for (k = 0; k= 0) { // multiply KF by alpha for alpha rule if (J < -1) F[I] -= KF[l][k] * ui[-J - 2]; else if (J >= 0) K.add(I, J, KF[l][k]); } } } } } else { // loop over rows for (i = 0; i= 0) { // node i is a rigid body // get the rigid body this node is attached to FERigidBody& RBi = *rigid.Object(nodei.m_rid); // get the rigid body equation nrs. lmi = RBi.m_LM; // get the relative distance (use alpha rule) ai = (nodei.m_rt - RBi.m_rt)*alpha + (nodei.m_rp - RBi.m_rp)*(1 - alpha); Ai.skew(ai); // get the shell director bi = ai - (nodei.m_d0 + nodei.get_vec3d(m_dofX, m_dofY, m_dofZ) - nodei.get_vec3d(m_dofSX, m_dofSY, m_dofSZ)); Bi.skew(bi); // get the element sub-matrix for (k = 0; k= 0) { if (J < -1) F[I] -= KF[l][k] * ui[-J - 2]; else if (J >= 0) K.add(I, J, KF[l][k]); } } } } } } } //----------------------------------------------------------------------------- void FERigidSolver::AssembleResidual(int node_id, int dof, double f, vector& R) { FEMesh& mesh = m_fem->GetMesh(); FERigidSystem& rigid = *m_fem->GetRigidSystem(); // get the equation number FENode& node = mesh.Node(node_id); int n = node.m_ID[dof]; // assemble into global vector if (n >= 0) R[n] += f; else if (node.m_rid >= 0) { // this is a rigid body node FERigidBody& RB = *rigid.Object(node.m_rid); // get the relative position vec3d a = node.m_rt - RB.m_rt; int* lm = RB.m_LM; if (dof == m_dofX) { if (lm[0] >= 0) R[lm[0]] += f; if (lm[4] >= 0) R[lm[4]] += a.z*f; if (lm[5] >= 0) R[lm[5]] += -a.y*f; } else if (dof == m_dofY) { if (lm[1] >= 0) R[lm[1]] += f; if (lm[3] >= 0) R[lm[3]] += -a.z*f; if (lm[5] >= 0) R[lm[5]] += a.x*f; } else if (dof == m_dofZ) { if (lm[2] >= 0) R[lm[2]] += f; if (lm[3] >= 0) R[lm[3]] += a.y*f; if (lm[4] >= 0) R[lm[4]] += -a.x*f; } if (node.HasFlags(FENode::SHELL) && node.HasFlags(FENode::RIGID_CLAMP)) { // get the shell director vec3d d = node.m_d0 + node.get_vec3d(m_dofX, m_dofY, m_dofZ) - node.get_vec3d(m_dofSX, m_dofSY, m_dofSZ); vec3d b = a - d; if (dof == m_dofSX) { if (lm[0] >= 0) R[lm[0]] += f; if (lm[4] >= 0) R[lm[4]] += b.z*f; if (lm[5] >= 0) R[lm[5]] += -b.y*f; } else if (dof == m_dofSY) { if (lm[1] >= 0) R[lm[1]] += f; if (lm[3] >= 0) R[lm[3]] += -b.z*f; if (lm[5] >= 0) R[lm[5]] += b.x*f; } else if (dof == m_dofSZ) { if (lm[2] >= 0) R[lm[2]] += f; if (lm[3] >= 0) R[lm[3]] += b.y*f; if (lm[4] >= 0) R[lm[4]] += -b.x*f; } } } } //----------------------------------------------------------------------------- void FERigidSolver::Residual() { FERigidSystem& rigid = *m_fem->GetRigidSystem(); int NRB = rigid.Objects(); for (int i = 0; iGetRigidSystem(); // we still need to set the diagonal elements to 1 // for the prescribed rigid body dofs. int NRB = rigid.Objects(); for (int i = 0; iGetRigidSystem(); // element stiffness matrix vector lm; matrix ke; // 6 dofs per rigid body ke.resize(6, 6); // Newmark integration rule double dt = timeInfo.timeIncrement; double beta = timeInfo.beta; double gamma = timeInfo.gamma; double a = 1. / (beta*dt*dt); for (int i=0; iAssembleStiffness(lm, ke); } } //================================================================================================= // FERigidSolverOld //================================================================================================= //----------------------------------------------------------------------------- //! This function updates the rigid body linear and angular velocity by solving //! an overdetermined system of linear equations using the least-square method. void FERigidSolverOld::UpdateRigidKinematics() { // get the model and mesh FEModel& fem = *m_fem; FEMesh& mesh = fem.GetMesh(); FERigidSystem& rigid = *fem.GetRigidSystem(); // loop over all rigid bodies int NRB = rigid.Objects(); for (int j = 0; j r; r.assign(6, 0.0); matrix m(6, 6); m.zero(); // we need to loop over all domains that define this rigid body int ncnt = 0; int NDOM = mesh.Domains(); for (int n = 0; nIsRigid()) { FERigidMaterial* prm = static_cast(pm); if (prm->GetRigidBodyID() == j) { // now loop over all the nodes int NN = dom.Nodes(); for (int i = 0; i 2) { vector VR = r / m; rb.m_vt = vec3d(VR[0], VR[1], VR[2]); rb.m_wt = vec3d(VR[3], VR[4], VR[5]); } } } //----------------------------------------------------------------------------- //! Updates the rigid body data void FERigidSolverOld::UpdateRigidBodies(vector& Ui, vector& ui, bool bnewUpdate) { // get the number of rigid bodies FERigidSystem& rigid = *m_fem->GetRigidSystem(); const int NRB = rigid.Objects(); // first calculate the rigid body displacement increments for (int i = 0; i= 0 ? Ui[lm[j]] + ui[lm[j]] : 0); } } } // for prescribed displacements, the displacement increments are evaluated differently // TODO: Is this really necessary? Why can't the ui vector contain the correct values? const int NRD = rigid.PrescribedBCs(); for (int i = 0; iGetMesh(); int N = mesh.Nodes(); for (int i = 0; i= 0) { vec3d ut = node.m_rt - node.m_r0; node.set_vec3d(m_dofX, m_dofY, m_dofZ, ut); } } } //================================================================================================= // FERigidSolverNew //================================================================================================= //----------------------------------------------------------------------------- void FERigidSolverNew::UpdateIncrements(vector& Ui, vector& ui, bool emap) { FERigidSystem& rigid = *m_fem->GetRigidSystem(); int nrb = rigid.Objects(); for (int i = 0; i= 0) Ui[lm[j]] += ui[lm[j]]; // next, we do the rotations. We do this separately since // they need to be interpreted differently than displacements vec3d vUi(0, 0, 0); vec3d vui(0, 0, 0); if (lm[3] >= 0) { vUi.x = Ui[lm[3]]; vui.x = ui[lm[3]]; } if (lm[4] >= 0) { vUi.y = Ui[lm[4]]; vui.y = ui[lm[4]]; } if (lm[5] >= 0) { vUi.z = Ui[lm[5]]; vui.z = ui[lm[5]]; } if (emap) qUi = quatd(vUi); else qUi = quatd(2 * atan(vUi.norm() / 2), vUi); // Cayley transform quatd qui(2 * atan(vui.norm() / 2), vui); // Cayley transform quatd q = qui*qUi; q.MakeUnit(); if (emap) v = q.GetVector()*q.GetAngle(); else v = q.GetVector()*(2 * tan(q.GetAngle() / 2)); // Cayley transform if (lm[3] >= 0) Ui[lm[3]] = v.x; if (lm[4] >= 0) Ui[lm[4]] = v.y; if (lm[5] >= 0) Ui[lm[5]] = v.z; } } } //----------------------------------------------------------------------------- //! Updates the rigid body data void FERigidSolverNew::UpdateRigidBodies(vector& Ui, vector& ui) { // update rigid bodies FERigidSystem& rigid = *m_fem->GetRigidSystem(); int nrb = rigid.Objects(); for (int i = 0; ilc; // TODO: do I need to take the line search step into account here? du[j] = (lc < 0 ? 0 : pdc->Value() - RB.m_Up[j]); } else { du[j] = (lm[j] >= 0 ? Ui[lm[j]] + ui[lm[j]] : 0); } } } RB.m_rt.x = RB.m_rp.x + du[0]; RB.m_rt.y = RB.m_rp.y + du[1]; RB.m_rt.z = RB.m_rp.z + du[2]; // next, we do the rotations. We do this seperatly since // they need to be interpreted differently than displacements if (RB.m_prb == 0) { quatd qdu; // quaternion of net increment if (RB.m_bpofr) { // if all rotation components are known (prescribed or fixed) // evaluate net increment from load curve double Ut[3] = { 0 }; for (int j = 3; j<6; ++j) { if (RB.m_pDC[j]) { int lc = RB.m_pDC[j]->lc; Ut[j - 3] = RB.m_pDC[j]->Value(); } } quatd qUt(vec3d(Ut[0], Ut[1], Ut[2])); qdu = qUt*RB.m_qp.Inverse(); } else { // rotation components are either free or fixed vec3d vUi(0, 0, 0); // initialize total increment so far vec3d vui(0, 0, 0); // initialize current increment if (lm[3] >= 0) { vUi.x = Ui[lm[3]]; vui.x = ui[lm[3]]; } if (lm[4] >= 0) { vUi.y = Ui[lm[4]]; vui.y = ui[lm[4]]; } if (lm[5] >= 0) { vUi.z = Ui[lm[5]]; vui.z = ui[lm[5]]; } quatd qUi(2 * atan(vUi.norm() / 2), vUi); // Cayley transform quatd qui(2 * atan(vui.norm() / 2), vui); // Cayley transform qdu = qui*qUi; } qdu.MakeUnit(); // clean-up roundoff errors vec3d vdu = qdu.GetVector()*(2 * tan(qdu.GetAngle() / 2)); // Cayley transform du[3] = vdu.x; du[4] = vdu.y; du[5] = vdu.z; } vec3d vdu(du[3], du[4], du[5]); quatd qdu(2 * atan(vdu.norm() / 2), vdu); quatd Q = qdu*RB.m_qp; Q.MakeUnit(); // update at the current time step RB.SetRotation(Q); if (RB.m_prb) du = RB.m_dul; // update RB center of mass translations RB.m_Ut[0] = RB.m_Up[0] + du[0]; RB.m_Ut[1] = RB.m_Up[1] + du[1]; RB.m_Ut[2] = RB.m_Up[2] + du[2]; // update RB rotations vec3d vUt = RB.GetRotation().GetVector()*RB.GetRotation().GetAngle(); RB.m_Ut[3] = vUt.x; RB.m_Ut[4] = vUt.y; RB.m_Ut[5] = vUt.z; } // update the mesh' nodes rigid.UpdateMesh(); // Since the rigid nodes are repositioned we need to update the displacement DOFS FEMesh& mesh = m_fem->GetMesh(); int N = mesh.Nodes(); for (int i = 0; i= 0) { vec3d ut = node.m_rt - node.m_r0; node.set_vec3d(m_dofX, m_dofY, m_dofZ, ut); if (node.HasFlags(FENode::SHELL) && node.HasFlags(FENode::RIGID_CLAMP)) { // get the rigid body FERigidBody& RB = *rigid.Object(node.m_rid); // evaluate the director in the current configuration vec3d d = RB.GetRotation()*node.m_d0 - node.m_d0; // evaluate the back face displacement increments node.set_vec3d(m_dofSX, m_dofSY, m_dofSZ, ut - d); } } } } //----------------------------------------------------------------------------- //! evaluate body forces void FERigidSolverNew::BodyForces(FEGlobalVector& R, const FETimeInfo& timeInfo, FEBodyForce& pbf) { FERigidSystem& rigid = *m_fem->GetRigidSystem(); int nrb = rigid.Objects(); // calculate body forces on rigid bodies for (int i = 0; i fe(3); vector LM(3); // create a material point to evaluate the body force FEElasticMaterialPoint mp; mp.m_r0 = RB.m_r0; mp.m_rt = RB.m_rt; mp.m_F = RB.GetRotation().RotationMatrix(); // body force = mass*body force per mass (recall that body forces are negated in FEBio) vec3d F = pbf.force(mp)*(-RB.m_mass); fe[0] = F.x; fe[1] = F.y; fe[2] = F.z; // pack the equation numbers LM[0] = RB.m_LM[0]; LM[1] = RB.m_LM[1]; LM[2] = RB.m_LM[2]; R.Assemble(LM, fe); // add to rigid body force RB.m_Fr += F; } } //----------------------------------------------------------------------------- //! evaluate inertia forces void FERigidSolverNew::InertialForces(FEGlobalVector& R, const FETimeInfo& timeInfo) { // Newmark rule double beta = timeInfo.beta; double gamma = timeInfo.gamma; double dt = timeInfo.timeIncrement; double a = 1.0 / (beta*dt); double b = a / dt; double c = 1.0 - 0.5 / beta; FERigidSystem& rigid = *m_fem->GetRigidSystem(); int nrb = rigid.Objects(); for (int i = 0; i fe(6); vector LM(6); // rate of change of linear momentum = mass*acceleration vec3d F = RB.m_at*RB.m_mass; fe[0] = -F.x; fe[1] = -F.y; fe[2] = -F.z; // evaluate mass moment of inertia at t and tp mat3d Rt = RB.GetRotation().RotationMatrix(); mat3ds Jt = (Rt*RB.m_moi*Rt.transpose()).sym(); mat3d Rp = RB.m_qp.RotationMatrix(); mat3ds Jp = (Rp*RB.m_moi*Rp.transpose()).sym(); // evaluate rate of change of angular momentum vec3d M = (Jt*RB.m_wt - Jp*RB.m_wp) / dt; fe[3] = -M.x; fe[4] = -M.y; fe[5] = -M.z; // pack the equation numbers LM[0] = RB.m_LM[0]; LM[1] = RB.m_LM[1]; LM[2] = RB.m_LM[2]; LM[3] = RB.m_LM[3]; LM[4] = RB.m_LM[4]; LM[5] = RB.m_LM[5]; R.Assemble(LM, fe); } } ",16174,True,2998.531509485128,median "== Cluster Operator The Cluster Operator is in charge of deploying a Kafka cluster alongside a Zookeeper ensemble. As part of the Kafka cluster, it can also deploy the topic operator which provides operator-style topic management via ConfigMaps. The Cluster Operator is also able to deploy a Kafka Connect cluster which connects to an existing Kafka cluster. On {OpenShiftName} such a cluster can be deployed using the Source2Image feature, providing an easy way of including more connectors. .Example Architecture diagram of the Cluster Operator. image::cluster_operator.png[Cluster Operator] When the Cluster Operator is up, it starts to ""watch"" for certain {ProductPlatformName} resources containing the desired Kafka or Kafka Connect cluster configuration. A `Kafka` resource is used for Kafka cluster configuration, and a `KafkaConnect` resource is used for Kafka Connect cluster configuration. When a new desired resource (that is, a `Kafka` or `KafkaConnect` resource) is created in the {ProductPlatformName} cluster, the operator gets the cluster configuration from the desired resource and starts creating a new Kafka or Kafka Connect cluster by creating the necessary other {ProductPlatformName} resources, such as StatefulSets, Services, ConfigMaps, and so on. Every time the desired resource is updated by the user, the operator performs corresponding updates on the {ProductPlatformName} resources which make up the Kafka or Kafka Connect cluster. Resources are either patched or deleted and then re-created in order to make the Kafka or Kafka Connect cluster reflect the state of the desired cluster resource. This might cause a rolling update which might lead to service disruption. Finally, when the desired resource is deleted, the operator starts to un-deploy the cluster deleting all the related {ProductPlatformName} resources. === Reconciliation Although the operator reacts to all notifications about the desired cluster resources received from the {ProductPlatformName} cluster, if the operator is not running, or if a notification is not received for any reason, the desired resources will get out of sync with the state of the running {ProductPlatformName} cluster. In order to handle failovers properly, a periodic reconciliation process is executed by the Cluster Operator so that it can compare the state of the desired resources with the current cluster deployments in order to have a consistent state across all of them. [[kafka_assembly_details]] === Format of the `Kafka` resource The full API is described in <>. Whatever other labels are applied to the desired Kafka resource will also be applied to the {ProductPlatformName} resources making up the Kafka cluster. This provides a convenient mechanism for those resources to be labelled in whatever way the user requires. [[kafka_config_map_details]] ==== Kafka In order to configure a Kafka cluster deployment, it is possible to specify the following fields in Kafka resource (a dot is used to denote a nested YAML object): `spec.kafka.replicas`:: The number of Kafka broker nodes. Default is 3. `spec.kafka.image`:: The Docker image to use for the Kafka brokers. Default is determined by the value of the `<>` environment variable of the Cluster Operator. `spec.kafka.brokerRackInitImage`:: The Docker image to use for the init container which does some initial configuration work (that is, rack support). Default is determined by the value of the `<>` environment variable of the Cluster Operator. `spec.kafka.livenessProbe.initialDelaySeconds`:: The initial delay for the liveness probe for each Kafka broker node. Default is 15. `spec.kafka.livenessProbe.timeoutSeconds`:: The timeout on the liveness probe for each Kafka broker node. Default is 5. `spec.kafka.readinessProbe.initialDelaySeconds`:: The initial delay for the readiness probe for each Kafka broker node. Default is 15. `spec.kafka.readinessProbe.timeoutSeconds`:: The timeout on the readiness probe for each Kafka broker node. Default is 5. `spec.kafka.config`:: The Kafka broker configuration. See section <> for more details. `spec.kafka.storage`:: The storage configuration for the Kafka broker nodes. See section <> for more details. `spec.kafka.metrics`:: The JMX exporter configuration for exposing metrics from Kafka broker nodes. When this field is absent no metrics will be exposed. `spec.kafka.logging`:: An object that specifies inline logging levels or the name of external config map that specifies the logging levels. When this field is absent default values are used. List of loggers which can be set: [source] kafka.root.logger.level log4j.logger.org.I0Itec.zkclient.ZkClient log4j.logger.org.apache.zookeeper log4j.logger.kafka log4j.logger.org.apache.kafka log4j.logger.kafka.request.logger log4j.logger.kafka.network.Processor log4j.logger.kafka.server.KafkaApis log4j.logger.kafka.network.RequestChannel$ log4j.logger.kafka.controller log4j.logger.kafka.log.LogCleaner log4j.logger.state.change.logger log4j.logger.kafka.authorizer.logger `spec.kafka.resources`:: The resource limits and requests for Kafka broker containers. The accepted format is described in the <> section. `spec.kafka.jvmOptions`:: An object allowing the JVM running Kafka to be configured. The accepted format is described in the <> section. `spec.kafka.rack`:: An object allowing the Kafka rack feature to be configured and used in rack-aware partition assignment for fault tolerance. The accepted JSON format is described in the <> section. `spec.kafka.affinity`:: An object allowing control over how the Kafka pods are scheduled to nodes. The format of the corresponding key is the same as the content supported in the Pod `affinity` in {ProductPlatformName}. See section <> for more details. `spec.zookeeper.replicas`:: The number of Zookeeper nodes. `spec.zookeeper.image`:: The Docker image to use for the Zookeeper nodes. Default is determined by the value of the `<>` environment variable of the Cluster Operator. `spec.zookeeper.livenessProbe.initialDelaySeconds`:: The initial delay for the liveness probe for each Zookeeper node. Default is 15. `spec.zookeeper.livenessProbe.initialDelaySeconds`:: The timeout on the liveness probe for each Zookeeper node. Default is 5. `spec.zookeeper.readinessProbe.initialDelaySeconds`:: The initial delay for the readiness probe for each Zookeeper node. Default is 15. `spec.zookeeper.readinessProbe.initialDelaySeconds`:: The timeout on the readiness probe for each Zookeeper node. Default is 5. `spec.zookeeper.config`:: The Zookeeper configuration. See section <> for more details. `spec.zookeeper.storage`:: The storage configuration for the Zookeeper nodes. See section <> for more details. `spec.zookeeper.metrics`:: The JMX exporter configuration for exposing metrics from Zookeeper nodes. When this field is absent no metrics will be exposed. `spec.zookeeper.logging`:: An object that specifies inline logging levels or the name of external config map that specifies the logging levels. When this field is absent default values are used. List of loggers which can be set: [source] zookeeper.root.logger `spec.zookeeper.resources`:: An object configuring the resource limits and requests for Zookeeper broker containers. The accepted JSON format is described in the <> section. `spec.zookeeper.jvmOptions`:: An object allowing the JVM running Zookeeper to be configured. The accepted JSON format is described in the <> section. `spec.zookeeper.affinity`:: An object allowing control over how the Zookeeper pods are scheduled to nodes. The format of the corresponding key is the same as the content supported in the Pod `affinity` in {ProductPlatformName}. See section <> for more details. `spec.topicOperator`:: An object representing the topic operator configuration. See the <> documentation for further details. More info about the topic operator in the related <> documentation page. The following is an example of a Kafka resource. .Example `Kafka` resource [source,yaml,options=""nowrap"",subs=""attributes""] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: replicas: 3 image: ""{DockerKafka}"" kafka-healthcheck-delay: ""15"" kafka-healthcheck-timeout: ""5"" config: offsets.topic.replication.factor: 3 transaction.state.log.replication.factor: 3 transaction.state.log.min.isr: 2 storage: type: ephemeral metrics: { ""lowercaseOutputName"": true, ""rules"": [ { ""pattern"": ""kafka.server<type=(.+), name=(.+)PerSec\\\\w*><>Count"", ""name"": ""kafka_server_$1_$2_total"" }, { ""pattern"": ""kafka.server<type=(.+), name=(.+)PerSec\\\\w*, topic=(.+)><>Count"", ""name"": ""kafka_server_$1_$2_total"", ""labels"": { ""topic"": ""$3"" } } ] } logging: type: external name: customConfigMap zookeeper: replicas: 1 image: {DockerZookeeper} healthcheck-delay: ""15"" healthcheck-timeout: ""5"" config: timeTick: 2000, initLimit: 5, syncLimit: 2, autopurge.purgeInterval: 1 storage: type: ephemeral metrics: { ""lowercaseOutputName"": true } logging: type : inline loggers : zookeeper.root.logger: INFO ---- The resources created by the Cluster Operator in the {ProductPlatformName} cluster will be the following : `[cluster-name]-zookeeper`:: StatefulSet which is in charge of managing the Zookeeper node pods `[cluster-name]-kafka`:: StatefulSet which is in charge of managing the Kafka broker pods `[cluster-name]-zookeeper-headless`:: Service needed to have DNS resolve the Zookeeper pods IP addresses directly `[cluster-name]-kafka-headless`:: Service needed to have DNS resolve the Kafka broker pods IP addresses directly `[cluster-name]-zookeeper`:: Service used by Kafka brokers to connect to Zookeeper nodes as clients `[cluster-name]-kafka`:: Service can be used as bootstrap servers for Kafka clients `[cluster-name]-zookeeper-metrics-config`:: ConfigMap which contains the Zookeeper metrics configuration and mounted as a volume by the Zookeeper node pods `[cluster-name]-kafka-metrics-config`:: ConfigMap which contains the Kafka metrics configuration and mounted as a volume by the Kafka broker pods `[cluster-name]-zookeeper-config`:: ConfigMap which contains the Zookeeper ancillary configuration and is mounted as a volume by the Zookeeper node pods `[cluster-name]-kafka-config`:: ConfigMap which contains the Kafka ancillary configuration and is mounted as a volume by the Kafka broker pods [[kafka_configuration_json_config]] ===== Kafka Configuration The `spec.kafka.config` object allows detailed configuration of Apache Kafka. This field should contain a JSON object with Kafka configuration options as keys. The values could be in one of the following JSON types: * String * Number * Boolean The `spec.kafka.config` object supports all Kafka configuration options with the exception of options related to: * Security (Encryption, Authentication and Authorization) * Listener configuration * Broker ID configuration * Configuration of log data directories * Inter-broker communication * Zookeeper connectivity Specifically, all configuration options with keys starting with one of the following strings will be ignored: * `listeners` * `advertised.` * `broker.` * `listener.` * `host.name` * `port` * `inter.broker.listener.name` * `sasl.` * `ssl.` * `security.` * `password.` * `principal.builder.class` * `log.dir` * `zookeeper.connect` * `zookeeper.set.acl` * `authorizer.` * `super.user` All other options will be passed to Kafka. A list of all the available options can be found on the http://kafka.apache.org/11/documentation.html#brokerconfigs[Kafka website]. An example `spec.kafka.config` field is provided below. .Example fragment of a `Kafka` resource specifying Kafka configuration [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... config: num.partitions: 1, num.recovery.threads.per.data.dir: 1, default.replication.factor: 3, offsets.topic.replication.factor: 3, transaction.state.log.replication.factor: 3, transaction.state.log.min.isr: 1, log.retention.hours: 168, log.segment.bytes: 1073741824, log.retention.check.interval.ms: 300000, num.network.threads: 3, num.io.threads: 8, socket.send.buffer.bytes: 102400, socket.receive.buffer.bytes: 102400, socket.request.max.bytes: 104857600, group.initial.rebalance.delay.ms: 0 # ... ---- NOTE:: The Cluster Operator does not validate keys or values in the provided `config` object. When invalid configuration is provided, the Kafka cluster might not start or might become unstable. In such cases, the configuration in the `spec.kafka.config` object should be fixed and the cluster operator will roll out the new configuration to all Kafka brokers. [[zookeeper_configuration_json_config]] ===== Zookeeper Configuration The `spec.zookeeper.config` object allows detailed configuration of Apache Zookeeper. This field should contain a JSON object with Zookeeper configuration options as keys. The values could be in one of the following JSON types: * String * Number * Boolean The `spec.zookeeper.config` object supports all Zookeeper configuration options with the exception of options related to: * Security (Encryption, Authentication and Authorization) * Listener configuration * Configuration of data directories * Zookeeper cluster composition Specifically, all configuration options with keys starting with one of the following strings will be ignored: * `server.` * `dataDir` * `dataLogDir` * `clientPort` * `authProvider` * `quorum.auth` * `requireClientAuthScheme` All other options will be passed to Zookeeper. A list of all the available options can be found on the http://zookeeper.apache.org/doc/r3.4.12/zookeeperAdmin.html[Zookeeper website]. An example `spec.zookeeper.config` object is provided below. .Example fragment of a `Kafka` resource specifying Zookeeper configuration [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: zookeeper: # ... config: timeTick: 2000, initLimit: 5, syncLimit: 2, quorumListenOnAllIPs: true, maxClientCnxns: 0, autopurge.snapRetainCount: 3, autopurge.purgeInterval: 1 # ... ---- Selected options have default values: * `timeTick` with default value `2000` * `initLimit` with default value `5` * `syncLimit` with default value `2` * `autopurge.purgeInterval` with default value `1` These options will be automatically configured in case they are not present in the `spec.zookeeper.config` object. NOTE:: The Cluster Operator does not validate keys or values in the provided `config` object. When invalid configuration is provided, the Zookeeper cluster might not start or might become unstable. In such cases, the configuration in the `spec.zookeeper.config` object should be fixed and the cluster operator will roll out the new configuration to all Zookeeper nodes. [[storage_configuration_json_config]] ===== Storage Both Kafka and Zookeeper save data to files. {ProductName} allows to save such data in an ""ephemeral"" way (using `emptyDir`) or in a ""persistent-claim"" way using persistent volumes. It is possible to provide the storage configuration in the `spec.kafka.storage` and `spec.zookeeper.storage` objects. IMPORTANT: The `spec.kafka.storage` and `spec.zookeeper.storage` objects cannot be changed when the cluster is up. The storage object has a mandatory `type` field for specifying the type of storage to use which must be either ""ephemeral"" or ""persistent-claim"". The ""ephemeral"" storage is really simple to configure. .Example fragment of a `Kafka` resource using `ephemeral` storage for Kafka pods [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... storage: type: ephemeral # ... ---- WARNING: If the Zookeeper cluster is deployed using ""ephemeral"" storage, the Kafka brokers can have problems dealing with Zookeeper node restarts which could happen via updates in the Kafka resource. In case of ""persistent-claim"" type the following fields can be provided as well: `size` (required):: defines the size of the persistent volume claim, for example, ""1Gi"". `class` (optional):: the {ProductPlatformName} https://kubernetes.io/docs/concepts/storage/storage-classes/[storage class] to use for dynamic volume allocation. `selector` (optional):: allows to select a specific persistent volume to use. It contains a `matchLabels` field which contains key:value pairs representing labels for selecting such a volume. `delete-claim` (optional):: boolean value which specifies if the persistent volume claim has to be deleted when the cluster is undeployed. Default is `false`. .Example fragment of a `Kafka` resource configuring Kafka with `persistent-storage` and 1Gi `size` [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... storage: type: persistent-claim size: 1Gi # ... ---- The following example demonstrates use of a storage class. .Example fragment of a `Kafka` resource configuring Kafka with `persistent-storage` using a storage class [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... storage: type: persistent-claim size: 1Gi class: my-storage-class # ... ---- Finally, a `selector` can be used in order to select a specific labelled persistent volume which provides some needed features (such as an SSD) .Example fragment of a `Kafka` resource configuring Kafka with ""match labels"" selector [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... storage: type: persistent-claim size: 1Gi selector: matchLabels: ""hdd-type"": ""ssd"" deleteClaim: true # ... ---- When the ""persistent-claim"" is used, other than the resources already described in the <> section, the following resources are generated : `data-[cluster-name]-kafka-[idx]`:: Persistent Volume Claim for the volume used for storing data for the Kafka broker pod `[idx]`. `data-[cluster-name]-zookeeper-[idx]`:: Persistent Volume Claim for the volume used for storing data for the Zookeeper node pod `[idx]`. See <> and <> for further details. ===== Metrics {ProductName} uses the [Prometheus JMX exporter](https://github.com/prometheus/jmx_exporter) in order to expose metrics on each node. It is possible to configure a `metrics` object in the `kafka` and `zookeeper` objects in `Kafka` resources, and likewise a `metrics` object in the `spec` of `KafkaConnect` resources. In all cases the `metrics` object should be the configuration for the JMX exporter. You can find more information on how to use it in the corresponding GitHub repo. For more information about using the metrics with Prometheus and Grafana, see <<_metrics>> ===== Logging The `logging` field allows the configuration of loggers. These loggers are: [source] log4j.rootLogger connect.root.logger.level log4j.logger.org.apache.zookeeper log4j.logger.org.I0Itec.zkclient log4j.logger.org.reflections The setting can be done in one of two ways. Either by specifying the loggers and their levels directly or by using a custom config map. An example of the latter would look like this:: [source,yaml] ---- logging: fromConfigMap: name : customConfigMap ---- The difference between these two options is that latter is not validated and does not support default values. That means user can supply any logging configuration, even if it is incorrect. First option supports default values. [[resources_json_config]] ===== Resource limits and requests It is possible to configure {ProductPlatformName} resource limits and requests on for the `kafka`, `zookeeper` and `topicOperator` objects in the `Kafka` resource and for for the `spec` object of the `KafkaConnect resource. The object may have a `requests` and a `limits` property, each having the same schema, consisting of `cpu` and `memory` properties. The {ProductPlatformName} syntax is used for the values of `cpu` and `memory`. .Example fragment of a `Kafka` resource configuring resource limits and requests for the Kafka pods [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... resources: requests: cpu: ""1"" memory: ""2Gi"" limits: cpu: ""1"" memory: ""2Gi"" # ... ---- :k8s-docs-version: v1-7 :k8s-resource-request-limit-docs-link: https://{k8s-docs-version}.docs.kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/ `requests.memory`:: the memory request for the container, corresponding directly to {k8s-resource-request-limit-docs-link}[`spec.containers[\\].resources.requests.memory`] setting. {ProductPlatformName} will ensure the containers have at least this much memory by running the pod on a node with at least as much free memory as all the containers require. Optional with no default. `requests.cpu`:: the cpu request for the container, corresponding directly to {k8s-resource-request-limit-docs-link}[`spec.containers[\\].resources.requests.cpu`] setting. {ProductPlatformName} will ensure the containers have at least this much CPU by running the pod on a node with at least as much uncommitted CPU as all the containers require. Optional with no default. `limits.memory`:: the memory limit for the container, corresponding directly to {k8s-resource-request-limit-docs-link}[`spec.containers[\\].resources.limits.memory`] setting. {ProductPlatformName} will limit the containers to this much memory, potentially terminating their pod if they use more. Optional with no default. `limits.cpu`:: the cpu limit for the container, corresponding directly to {k8s-resource-request-limit-docs-link}[`spec.containers[\\].resources.limits.cpu`] setting. {ProductPlatformName} will cap the containers CPU usage to this limit. Optional with no default. More details about resource limits and requests can be found on {k8s-resource-request-limit-docs-link}[{KubernetesName} website]. ====== Minimum Resource Requirements Testing has shown that the Cluster Operator functions adequately with 256Mi of memory and 200m CPU when watching two clusters. It is therefore recommended to use these as a minimum when configuring resource requests and not to run it with lower limits than these. Configuring more generous limits is recommended, especially when it is controlling multiple clusters. [[jvm_json_config]] ===== JVM Options It is possible to configure a subset of available JVM options on Kafka, Zookeeper and Kafka Connect containers. The object has a property for each JVM (`java`) option which can be configured: `-Xmx`:: The maximum heap size. See the <> section for further details. `-Xms`:: The initial heap size. Setting the same value for initial and maximum (`-Xmx`) heap sizes avoids the JVM having to allocate memory after startup, at the cost of possibly allocating more heap than is really needed. For Kafka and Zookeeper pods such allocation could cause unwanted latency. For Kafka Connect avoiding over allocation may be the more important concern, especially in distributed mode where the effects of over-allocation will be multiplied by the number of consumers. NOTE: The units accepted by JVM settings such as `-Xmx` and `-Xms` are those accepted by the JDK `java` binary in the corresponding image. Accordingly, `1g` or `1G` means 1,073,741,824 bytes, and `Gi` is not a valid unit suffix. This is in contrast to the units used for <>, which follow the {ProductPlatformName} convention where `1G` means 1,000,000,000 bytes, and `1Gi` means 1,073,741,824 bytes .Example fragment of a `Kafka` resource configuring `jvmOptions` [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... jvmOptions: ""-Xmx"": ""2g"" ""-Xms"": ""2g"" # ... ---- In the above example, the JVM will use 2 GiB (=2,147,483,648 bytes) for its heap. Its total memory usage will be approximately 8GiB. `-server`:: Selects the server JVM. This option can be set to true or false. Optional. `-XX`:: A JSON Object for configuring advanced runtime options of a JVM. Optional The `-server` and `-XX` options are used to configure the `KAFKA_JVM_PERFORMANCE_OPTS` option of Apache Kafka. .More sophisticated example fragment of a `Kafka` resource configuring `jvmOptions` [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: ""-server"": true, ""-XX"": ""UseG1GC"": true, ""MaxGCPauseMillis"": 20, ""InitiatingHeapOccupancyPercent"": 35, ""ExplicitGCInvokesConcurrent"": true, ""UseParNewGC"": false ---- The example configuration above will result in the following JVM options: [source] ---- -server -XX:+UseG1GC -XX:MaxGCPauseMillis=20 -XX:InitiatingHeapOccupancyPercent=35 -XX:+ExplicitGCInvokesConcurrent -XX:-UseParNewGC ---- When neither of the two options (`-server` and `-XX`) is specified, the default Apache Kafka configuration of `KAFKA_JVM_PERFORMANCE_OPTS` will be used. [[setting_xmx]] ====== Setting `-Xmx` The default value used for `-Xmx` depends on whether there is a <> for the container: * If there is a memory limit, the JVM's maximum memory will be limited according to the kind of pod (Kafka, Zookeeper, Topic Operator) to an appropriate value less than the limit. * Otherwise, when there is no memory limit, the JVM's maximum memory will be set according to the kind of pod and the RAM available to the container. [IMPORTANT] ==== Setting `-Xmx` explicitly is requires some care: * The JVM's overall memory usage will be approximately 4 × the maximum heap, as configured by `-Xmx`. * If `-Xmx` is set without also setting an appropriate {ProductPlatformName} memory limit, it is possible that the container will be killed should the {ProductPlatformName} node experience memory pressure (from other Pods running on it). * If `-Xmx` is set without also setting an appropriate {ProductPlatformName} memory request, it is possible that the container will scheduled to a node with insufficient memory. In this case the container will start but crash (immediately if `-Xms` is set to `-Xmx`, or some later time if not). ==== When setting `-Xmx` explicitly, it is recommended to: * set the memory request and the memory limit to the same value, * use a memory request that is at least 4.5 × the `-Xmx`, * consider setting `-Xms` to the same value as `-Xms`. Furthermore, containers doing lots of disk I/O (such as Kafka broker containers) will need to leave some memory available for use as operating system page cache. On such containers, the request memory should be substantially more than the memory used by the JVM. [[kafka_rack]] ===== Kafka rack It is possible to enable Kafka rack-awareness (more information can be found on the {KafkaRacks}) by specifying the `rack` object in the `spec.kafka` object of the `Kafka` resource. The `rack` object has one mandatory field named `topologyKey`. This key needs to match one of the labels assigned to the {ProductPlatformName} cluster nodes. The label is used by {ProductPlatformName} when scheduling Kafka broker pods to nodes. If the {ProductPlatformName} cluster is running on a cloud provider platform, that label should represent the availability zone where the node is running. Usually, the nodes are labeled with `failure-domain.beta.kubernetes.io/zone` that can be easily used as `topologyKey` value. This will have the effect of spreading the broker pods across zones, and also setting the brokers `broker.rack` configuration parameter. .Example fragment of a `Kafka` resource configuring the `rack` [source,json] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... rack: topologyKey: failure-domain.beta.kubernetes.io/zone # ... ---- In the above example, the `failure-domain.beta.kubernetes.io/zone` node label will be used for scheduling Kafka broker Pods. [[affinity]] ===== Node and Pod Affinity Node and Pod Affinity provide a flexible mechanism to guide the scheduling of pods to nodes by {ProductPlatformName}. Node affinity can be used so that broker pods are preferentially scheduled to nodes with fast disks, for example. Similarly, pod affinity could be used to try to schedule Kafka clients on the same nodes as Kafka brokers. More information can be found on the {K8sAffinity}. The format of the corresponding key is the same as the content supported in the Pod `affinity` in {ProductPlatformName}, that is: `nodeAffinity`, `podAffinity` and `podAntiAffinity`. .Example fragment of a `Kafka` resource configured with `nodeAffinity` [source,yaml] ---- apiVersion: {KafkaApiVersion} kind: Kafka metadata: name: my-cluster spec: kafka: # ... affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: kubernetes.io/e2e-az-name operator: In values: - e2e-az1 - e2e-az2 # ... ---- NOTE: When using both `affinity` and <> be aware that `rack` uses a pod anti-affinity. This is necessary so that broker pods are scheduled in different failure domains, as specified via the `topologyKey`. This anti-affinity will not be present in the `Kafka` resource's `affinity`, but is still present on the StatefulSet and thus will still be considered by the scheduler. [[topic_operator_json_config]] ===== Topic Operator Alongside the Kafka cluster and the Zookeeper ensemble, the Cluster Operator can also deploy the topic operator. In order to do that, a `spec.topicOperator` object has to be included in the `Kafka` resource. This object contains the topic operator configuration. Without this object, the Cluster Operator does not deploy the topic operator. It is still possible to deploy the topic operator by creating appropriate {ProductPlatformName} resources. The YAML representation of the 'topicOperator` has no mandatory fields and if the value is an empty object (just ""{ }""), the Cluster Operator will deploy the topic operator with a default configuration. The configurable fields are the following : `image`:: Docker image to use for the topic operator. Default is determined by the value of the `<>` environment variable of the Cluster Operator. `watchedNamespace`:: The {ProductPlatformName} namespace in which the topic operator watches for topic ConfigMaps. Default is the namespace where the topic operator is running. `reconciliationIntervalMs`:: The interval between periodic reconciliations in milliseconds. Default is 900000 (15 minutes). `zookeeperSessionTimeoutMs`:: The Zookeeper session timeout in milliseconds. Default is 20000 milliseconds (20 seconds). `topicMetadataMaxAttempts`:: The number of attempts for getting topics metadata from Kafka. The time between each attempt is defined as an exponential back-off. You might want to increase this value when topic creation could take more time due to its larger size (i.e. many partitions / replicas). Default is `6`. `resources`:: An object configuring the resource limits and requests for the topic operator container. The accepted JSON format is described in the <> section. `affinity`:: Node and Pod affinity for the Topic Operator, as described in the <> section. The format of the corresponding key is the same as the content supported in the Pod `affinity` in {ProductPlatformName}. .Example Topic Operator JSON configuration [source,json] ---- { ""reconciliationIntervalMs"": ""900000"", ""zookeeperSessionTimeoutMs"": ""20000"" } ---- More information about these configuration parameters in the related <> documentation page. [[kafka_connect_config_map_details]] ==== Kafka Connect The operator watches for `KafkaConnect` resource in order to find and get configuration for a Kafka Connect cluster to deploy. The `KafkaConnectS2I` resource provides configuration for a Kafka Connect cluster deployment using Build and Source2Image features (works only with {OpenShiftName}) Whatever other labels are applied to the `KafkaConnect` or `KafkaConnectS2I` resources will also be applied to the {ProductPlatformName} resources making up the Kafka Connect cluster. This provides a convenient mechanism for those resource to be labelled in whatever way the user requires. The `KafkaConnect` resource supports the following within its `spec`: `nodes`:: Number of Kafka Connect worker nodes. Default is 1. `image`:: The Docker image to use for the Kafka Connect workers. Default is determined by the value of the `<>` environment variable of the Cluster Operator. If S2I is used (only on {OpenShiftName}), then it should be the related S2I image. `healthcheck-delay`:: The initial delay for the liveness and readiness probes for each Kafka Connect worker node. Default is 60. `healthcheck-timeout`:: The timeout on the liveness and readiness probes for each Kafka Connect worker node. Default is 5. `connect-config`:: A JSON string with Kafka Connect configuration. See section <> for more details. `metrics-config`:: A JSON string representing the JMX exporter configuration for exposing metrics from Kafka Connect nodes. When this field is absent no metrics will be exposed. `resources`:: A JSON string configuring the resource limits and requests for Kafka Connect containers. The accepted JSON format is described in the <> section. `jvmOptions`:: A JSON string allowing the JVM running Kafka Connect to be configured. The accepted JSON format is described in the <> section. `affinity`:: Node and Pod affinity for the Kafka Connect pods, as described in the <> section. The format of the corresponding key is the same as the content supported in the Pod `affinity` in {ProductPlatformName}. The following is an example of a `KafkaConnect` resource. .Example KafkaConnect resource [source,yaml,options=""nowrap"",subs=""attributes""] ---- apiVersion: {KafkaConnectApiVersion} kind: KafkaConnect metadata: name: my-connect-cluster spec: nodes: 1 image: {DockerKafkaConnect} readinessProbe: initialDelaySeconds: 60 timeoutSeconds: 5 livenessProbe: initialDelaySeconds: 60 timeoutSeconds: 5 config: bootstrap.servers: my-cluster-kafka:9092 ---- The resources created by the Cluster Operator into the {ProductPlatformName} cluster will be the following : [connect-cluster-name]-connect:: Deployment which is in charge to create the Kafka Connect worker node pods. [connect-cluster-name]-connect:: Service which exposes the REST interface for managing the Kafka Connect cluster. [connect-cluster-name]-metrics-config:: ConfigMap which contains the Kafka Connect metrics configuration and is mounted as a volume by the Kafka Connect pods. [[kafka_connect_configuration_json_config]] ===== Kafka Connect configuration The `spec.config` object of the `KafkaConnect` and `KafkaConnectS2I` resources allows detailed configuration of Apache Kafka Connect. This object should contain the Kafka Connect configuration options as keys. The values could be in one of the following JSON types: * String * Number * Boolean The `config` object supports all Kafka Connect configuration options with the exception of options related to: * Security (Encryption, Authentication and Authorization) * Listener / REST interface configuration * Plugin path configuration Specifically, all configuration options with keys starting with one of the following strings will be ignored: * `ssl.` * `sasl.` * `security.` * `listeners` * `plugin.path` * `rest.` All other options will be passed to Kafka Connect. A list of all the available options can be found on the http://kafka.apache.org/11/documentation.html#connectconfigs[Kafka website]. An example `config` field is provided below. .Example Kafka Connect configuration [source,json] ---- apiVersion: {KafkaConnectApiVersion} kind: KafkaConnect metadata: name: my-connect-cluster spec: config: bootstrap.servers: my-cluster-kafka:9092 group.id: my-connect-cluster offset.storage.topic: my-connect-cluster-offsets config.storage.topic: my-connect-cluster-configs status.storage.topic: my-connect-cluster-status key.converter: org.apache.kafka.connect.json.JsonConverter value.converter: org.apache.kafka.connect.json.JsonConverter key.converter.schemas.enable: true value.converter.schemas.enable: true internal.key.converter: org.apache.kafka.connect.json.JsonConverter internal.value.converter: org.apache.kafka.connect.json.JsonConverter internal.key.converter.schemas.enable: false internal.value.converter.schemas.enable: false config.storage.replication.factor: 3 offset.storage.replication.factor: 3 status.storage.replication.factor: 3 } ---- Selected options have default values: * `group.id` with default value `connect-cluster` * `offset.storage.topic` with default value `connect-cluster-offsets` * `config.storage.topic` with default value `connect-cluster-configs` * `status.storage.topic` with default value `connect-cluster-status` * `key.converter` with default value `org.apache.kafka.connect.json.JsonConverter` * `value.converter` with default value `org.apache.kafka.connect.json.JsonConverter` * `internal.key.converter` with default value `org.apache.kafka.connect.json.JsonConverter` * `internal.value.converter` with default value `org.apache.kafka.connect.json.JsonConverter` * `internal.key.converter.schemas.enable` with default value `false` * `internal.value.converter.schemas.enable` with default value `false` These options will be automatically configured in case they are not present in the `config` object. INFO:: The Cluster Operator does not validate the provided configuration. When invalid configuration is provided, the Kafka Connect cluster might not start or might become unstable. In such cases, the configuration in the `config` object should be fixed and the Cluster Operator will roll out the new configuration to all Kafka Connect instances. ===== Kafka Connect S2I deployment When using {ProductName} together with an {OpenShiftName} cluster, a user can deploy Kafka Connect with support for https://docs.openshift.org/3.9/dev_guide/builds/index.html[{OpenShiftName} Builds] and https://docs.openshift.org/3.9/creating_images/s2i.html#creating-images-s2i[Source-to-Image (S2I)]. To activate the S2I deployment a `KafkaConnectS2I` resource should be used instead of a `KafkaConnect` resource. The following is a full example of `KafkaConnectS2I` resource. .Example `KafkaConnectS2I` resource [source,yaml,options=""nowrap"",subs=""attributes""] ---- apiVersion: {KafkaConnectS2I} kind: KafkaConnectS2I metadata: name: my-connect-cluster spec: nodes: 1 image: {DockerKafkaConnectS2I} readinessProbe: initialDelaySeconds: 60 timeoutSeconds: 5 livenessProbe: initialDelaySeconds: 60 timeoutSeconds: 5 config: bootstrap.servers: my-cluster-kafka:9092 ---- The S2I deployment is very similar to the regular Kafka Connect deployment (as represented by the `KafkaConnect` resource). Compared to the regular deployment, the Cluster Operator will create the following additional resources: [connect-cluster-name]-connect-source:: ImageStream which is used as the base image for the newly-built Docker images. [connect-cluster-name]-connect:: BuildConfig which is responsible for building the new Kafka Connect Docker images. [connect-cluster-name]-connect:: ImageStream where the newly built Docker images will be pushed. [connect-cluster-name]-connect:: DeploymentConfig which is in charge of creating the Kafka Connect worker node pods. [connect-cluster-name]-connect:: Service which exposes the REST interface for managing the Kafka Connect cluster. The Kafka Connect S2I deployment supports the same options as the regular Kafka Connect deployment. A list of supported options can be found in the <> section. The `image` option specifies the Docker image which will be used as the _source image_ - the base image for the newly built Docker image. The default value of the `image` option is determined by the value of the `<>` environment variable of the Cluster Operator. All other options have the same meaning as for the regular `KafkaConnect` deployment. Once the Kafka Connect S2I cluster is deployed, new plugins can be added by starting a new {OpenShiftName} build. Before starting the build, a directory with all the KafkaConnect plugins which should be added has to be created. The plugins and all their dependencies can be in a single directory or can be split into multiple subdirectories. For example: [source,shell] ---- $ tree ./s2i-plugins/ ./s2i-plugins/ ├── debezium-connector-mysql │   ├── CHANGELOG.md │   ├── CONTRIBUTE.md │   ├── COPYRIGHT.txt │   ├── debezium-connector-mysql-0.7.1.jar │   ├── debezium-core-0.7.1.jar │   ├── LICENSE.txt │   ├── mysql-binlog-connector-java-0.13.0.jar │   ├── mysql-connector-java-5.1.40.jar │   ├── README.md │   └── wkb-1.0.2.jar └── debezium-connector-postgres ├── CHANGELOG.md ├── CONTRIBUTE.md ├── COPYRIGHT.txt ├── debezium-connector-postgres-0.7.1.jar ├── debezium-core-0.7.1.jar ├── LICENSE.txt ├── postgresql-42.0.0.jar ├── protobuf-java-2.6.1.jar └── README.md ---- A new build can be started using the following command: [source,shell] oc start-build my-connect-cluster-connect --from-dir ./s2i-plugins/ This command will upload the whole directory into the {OpenShiftName} cluster and start a new build. The build will take the base Docker image from the source ImageStream (named _[connect-cluster-name]-connect-source_) and add the directory and all the files it contains into this image and push the resulting image into the target ImageStream (named _[connect-cluster-name]-connect_). When the new image is pushed to the target ImageStream, a rolling update of the Kafka Connect S2I deployment will be started and will roll out the new version of the image with the added plugins. By default, the `oc start-build` command will trigger the build and complete. The progress of the build can be observed in the {OpenShiftName} console. Alternatively, the option `--follow` can be used to follow the build from the command line: [source,shell] ---- oc start-build my-connect-cluster-connect --from-dir ./s2i-plugins/ --follow Uploading directory ""s2i-plugins"" as binary input for the build ... build ""my-connect-cluster-connect-3"" started Receiving source from STDIN as archive ... Assembling plugins into custom plugin directory /tmp/kafka-plugins Moving plugins to /tmp/kafka-plugins Pushing image 172.30.1.1:5000/myproject/my-connect-cluster-connect:latest ... Pushed 6/10 layers, 60% complete Pushed 7/10 layers, 70% complete Pushed 8/10 layers, 80% complete Pushed 9/10 layers, 90% complete Pushed 10/10 layers, 100% complete Push successful ---- NOTE: The S2I build will always add the additional Kafka Connect plugins to the original source image. They will not be added to the Docker image from a previous build. To add multiple plugins to the deployment, they all have to be added within the same build. === Provisioning Role-Based Access Control (RBAC) for the operator For the operator to function it needs permission within the {ProductPlatformName} cluster to interact with the resources it manages (ConfigMaps, Pods, Deployments, StatefulSets, Services and so on). Such permission is described in terms of {ProductPlatformName} role-based access controls. ==== Using a ServiceAccount The operator is best run using a ServiceAccount: [source,yaml,options=""nowrap""] .Example ServiceAccount for the Cluster Operator ---- include::examples/install/cluster-operator/01-service-account.yaml[] ---- The Deployment of the operator then needs to specify this in the `serviceAccountName` of its `template.spec`: [source,yaml,numbered,options=""nowrap"",highlight='12'] .Partial example Deployment for the Cluster Operator ---- include::examples/install/cluster-operator/08-deployment.yaml[lines=1..13] # ... ---- Note line 12, where the the `strimzi-cluster-operator` ServiceAccount is specified as the `serviceAccountName`. If the rack awareness feature is used, a Kafka init container will be started before the broker container in order to enable it. The application inside this container is best run using a ServiceAccount: [source,yaml,options=""nowrap""] .Example ServiceAccount for the Kafka init container ---- include::examples/install/cluster-operator/04-service-account-kafka.yaml[] ---- The Cluster Operator will be in charge of configuring this ServiceAccount as `serviceAccountName` for the Kafka init container during cluster deployment. ==== Defining a Role The Cluster Operator needs to operate using a Role that gives it access to the necessary resources. Depending on the {ProductPlatformName} cluster setup, a cluster administrator might be needed to create the Role. Cluster administrator rights are only needed for the creation of the Role. The Role itself does not contain any cluster administrator privileges, and the Cluster Operator will not run under the cluster admin account. The Role follows the ""principle of least privilege"" and contains only those privileges needed by the Cluster Operator to operate Kafka, Kafka Connect and Zookeeper clusters. The assigned privileges allow the Cluster Operator to manage {ProductPlatformName} resources such as StatefulSets, Deployments, Pods and ConfigMaps. [source,yaml,options=""nowrap""] .Example Role for the Cluster Operator ---- include::examples/install/cluster-operator/02-role.yaml[] ---- When the Role cannot be created, the predefined ClusterRole named `edit` can be used instead. If the rack awareness feature is used, the started Kafka init container needs to operate using a ClusterRole that gives it access to the necessary resources. [source,yaml,options=""nowrap""] .Example Role for the Kafka init container ---- include::examples/install/cluster-operator/05-role-kafka.yaml[] ---- The assigned privileges allow the Kafka init container to get Nodes information. ==== Defining a RoleBinding Finally, the operator needs a RoleBinding which associates its Role with its ServiceAccount: [source,yaml,options=""nowrap""] .Example RoleBinding for the Cluster Operator ---- include::examples/install/cluster-operator/03-role-binding.yaml[] ---- In case the `edit` ClusterRole is being used, the RoleBinding has to be modified to refer to it instead of the `strimzi-cluster-operator-role` Role: [source,yaml,options=""nowrap""] .Example RoleBinding for the Cluster Operator using the `edit` ClusterRole ---- apiVersion: rbac.authorization.k8s.io/v1beta1 kind: RoleBinding metadata: name: strimzi-cluster-operator-binding labels: app: strimzi subjects: - kind: ServiceAccount name: strimzi-cluster-operator roleRef: kind: ClusterRole name: edit apiGroup: rbac.authorization.k8s.io ---- If the rack awareness feature is used, the Kafka init container needs a ClusterRoleBinding which associates its ClusterRole with its ServiceAccount: [source,yaml,options=""nowrap""] .Example ClusterRoleBinding for the Kafka init container ---- include::examples/install/cluster-operator/06-role-binding-kafka.yaml[] ---- It's important to highlight that the `namespace` field, specified in the ServiceAccount subject, needs to be the same namespace where the Kafka cluster will be deployed. === Operator configuration The operator itself can be configured through the following environment variables. [[STRIMZI_NAMESPACE]] `STRIMZI_NAMESPACE`:: Required. A comma-separated list of namespaces that the operator should operate in. The Cluster Operator deployment might use the https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/#the-downward-api[{KubernetesName} Downward API] to set this automatically to the namespace the Cluster Operator is deployed in. See the example below: + [source,yaml,options=""nowrap""] ---- env: - name: STRIMZI_NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace ---- [[STRIMZI_FULL_RECONCILIATION_INTERVAL_MS]] `STRIMZI_FULL_RECONCILIATION_INTERVAL_MS`:: Optional, default: 120000 ms. The interval between periodic reconciliations, in milliseconds. [[STRIMZI_OPERATION_TIMEOUT_MS]] `STRIMZI_OPERATION_TIMEOUT_MS`:: Optional, default: 300000 ms. The timeout for internal operations, in milliseconds. This value should be increased when using {ProductName} on clusters where regular {ProductPlatformName} operations take longer than usual (because of slow downloading of Docker images, for example). [[STRIMZI_DEFAULT_KAFKA_IMAGE]] `STRIMZI_DEFAULT_KAFKA_IMAGE`:: Optional, default `strimzi/kafka:latest`. The image name to use as a default when deploying Kafka, if no image is specified as the `kafka-image` in the <>. [[STRIMZI_DEFAULT_INIT_KAFKA_IMAGE]] `STRIMZI_DEFAULT_INIT_KAFKA_IMAGE`:: Optional, default `strimzi/init-kafka:latest`. The image name to use as default for the init container started before the broker for doing initial configuration work (that is, rack support), if no image is specified as the `init-kafka-image` in the <>. [[STRIMZI_DEFAULT_KAFKA_CONNECT_IMAGE]] `STRIMZI_DEFAULT_KAFKA_CONNECT_IMAGE`:: Optional, default `strimzi/kafka-connect:latest`. The image name to use as a default when deploying Kafka Connect, if no image is specified as the `image` in the <>. [[STRIMZI_DEFAULT_KAFKA_CONNECT_S2I_IMAGE]] `STRIMZI_DEFAULT_KAFKA_CONNECT_S2I_IMAGE`:: Optional, default `strimzi/kafka-connect-s2i:latest`. The image name to use as a default when deploying Kafka Connect S2I, if no image is specified as the `image` in the cluster ConfigMap. [[STRIMZI_DEFAULT_TOPIC_OPERATOR_IMAGE]] `STRIMZI_DEFAULT_TOPIC_OPERATOR_IMAGE`:: Optional, default `strimzi/topic-operator:latest`. The image name to use as a default when deploying the topic operator, if no image is specified as the `image` in the <> of the Kafka cluster ConfigMap. [[STRIMZI_DEFAULT_ZOOKEEPER_IMAGE]] `STRIMZI_DEFAULT_ZOOKEEPER_IMAGE`:: Optional, default `strimzi/zookeeper:latest`. The image name to use as a default when deploying Zookeeper, if no image is specified as the `zookeeper-image` in the <>. [[STRIMZI_LOG_LEVEL]] `STRIMZI_LOG_LEVEL`:: Optional, default `INFO`. The level for printing logging messages. The value can be set to: `ERROR`, `WARNING`, `INFO`, `DEBUG` and `TRACE`. [[multi-namespace]] ==== Watching multiple namespaces The `STRIMZI_NAMESPACE` environment variable can be used to configure a single operator instance to operate in multiple namespaces. For each namespace given, the operator will watch for cluster ConfigMaps and perform periodic reconciliation. To be able to do this, the operator's ServiceAccount needs access to the necessary resources in those other namespaces. This can be done by creating an additional RoleBinding in each of those namespaces, associating the operator's ServiceAccount (`strimzi-cluster-operator` in the examples) with the operator's Role (`strimzi-operator-role` in the examples). Suppose, for example, that a operator deployed in namespace `foo` needs to operate in namespace `bar`. The following RoleBinding would grant the necessary permissions: .Example RoleBinding for a operator to operate in namespace `bar` [source,yaml,options=""nowrap""] ---- apiVersion: v1 kind: RoleBinding metadata: name: strimzi-cluster-operator-binding-bar namespace: bar labels: app: strimzi subjects: - kind: ServiceAccount name: strimzi-cluster-operator namespace: foo roleRef: kind: Role name: strimzi-cluster-operator-role apiGroup: v1 ---- ",12290,False,2170.4268529085307,median "[[scoreCalculation]] = Score calculation :doctype: book :sectnums: :icons: font [[scoreTerminology]] == Score terminology [[whatIsAScore]] === What is a score? Every `@PlanningSolution` class has a score. The score is an objective way to compare two solutions. The solution with the higher score is better. The `Solver` aims to find the solution with the highest `Score` of all possible solutions. The _best solution_ is the solution with the highest `Score` that `Solver` has encountered during solving, which might be the __optimal solution__. OptaPlanner cannot automatically know which solution is best for your business, so you need to tell it how to calculate the score of a given `@PlanningSolution` instance according to your business needs. If you forget or are unable to implement an important business constraint, the solution is probably useless: image::score-calculation/optimalWithIncompleteConstraints.png[align=""center""] [[formalizeTheBusinessConstraints]] === Formalize the business constraints To implement a verbal business constraint, it needs to be formalized as a score constraint. Luckily, defining constraints in OptaPlanner is very flexible through the following score techniques: * **Score signum (positive or negative)**: maximize or minimize a constraint type * **Score weight**: put a cost/profit on a constraint type * **Score level (hard, soft, ...)**: prioritize a group of constraint types * *Pareto scoring* (rarely used) Take the time to acquaint yourself with the first three techniques. Once you understand them, formalizing most business constraints becomes straightforward. [NOTE] ==== Do not presume that your business knows all its score constraints in advance. Expect score constraints to be added, changed or removed after the first releases. ==== [[scoreConstraintSignum]] === Score constraint signum (positive or negative) All score techniques are based on constraints. A constraint can be a simple pattern (such as __Maximize the apple harvest in the solution__) or a more complex pattern. A positive constraint is a constraint you want to maximize. A negative constraint is a constraint you want to minimize image::score-calculation/positiveAndNegativeConstraints.png[align=""center""] The image above illustrates that **the optimal solution always has the highest score**, regardless if the constraints are positive or negative. Most planning problems have only negative constraints and therefore have a negative score. In that case, the score is the sum of the weight of the negative constraints being broken, with a perfect score of 0. For example in n queens, the score is the negative of the number of queen pairs which can attack each other. Negative and positive constraints can be combined, even in the same score level. When a constraint activates (because the negative constraint is broken or the positive constraint is fulfilled) on a certain planning entity set, it is called a __constraint match__. [[scoreConstraintWeight]] === Score constraint weight Not all score constraints are equally important. If breaking one constraint is equally bad as breaking another constraint x times, then those two constraints have a different weight (but they are in the same score level). For example in vehicle routing, you can make one _unhappy driver_ constraint match count as much as two _fuel tank usage_ constraint matches: image::score-calculation/scoreWeighting.png[align=""center""] Score weighting is easy in use cases where you can __put a price tag on everything__. In that case, the positive constraints maximize revenue and the negative constraints minimize expenses, so together they maximize profit. Alternatively, score weighting is also often used to create social <>. For example, a nurse, who requests a free day, pays a higher weight on New Years eve than on a normal day. The weight of a constraint match can depend on the planning entities involved. For example in cloud balancing, the weight of the soft constraint match for an active `Computer` is the maintenance `cost` of that `Computer` (which differs per computer). Putting a good weight on a constraint is often a difficult analytical decision, because it is about making choices and trade-offs against other constraints. Different stakeholders have different priorities. *Don't waste time with constraint weight discussions at the start of an implementation, instead add a <> and allow users to change them through a UI.* A non-accurate weight is less damaging than mediocre algorithms: image::score-calculation/scoreTradeoffInPerspective.png[align=""center""] Most use cases use a `Score` with `int` weights, such as <>. [[scoreLevel]] === Score constraint level (hard, soft, ...) Sometimes a score constraint outranks another score constraint, no matter how many times the latter is broken. In that case, those score constraints are in different levels. For example, a nurse cannot do two shifts at the same time (due to the constraints of physical reality), so this outranks all nurse happiness constraints. Most use cases have only two score levels, hard and soft. The levels of two scores are compared lexicographically. The first score level gets compared first. If those differ, the remaining score levels are ignored. For example, a score that breaks `0` hard constraints and `1000000` soft constraints is better than a score that breaks `1` hard constraint and `0` soft constraints. image::score-calculation/scoreLevels.png[align=""center""] If there are two (or more) score levels, for example <>, then a score is _feasible_ if no hard constraints are broken. [NOTE] ==== By default, OptaPlanner will always assign all planning variables a planning value. If there is no feasible solution, this means the best solution will be infeasible. To instead leave some of the planning entities unassigned, apply xref:repeated-planning/repeated-planning.adoc#overconstrainedPlanning[overconstrained planning]. ==== For each constraint, you need to pick a score level, a score weight and a score signum. For example: `-1soft` which has score level of ``soft``, a weight of `1` and a negative signum. Do not use a big constraint weight when your business actually wants different score levels. That hack, known as __score folding__, is broken: image::score-calculation/scoreFoldingIsBroken.png[align=""center""] [NOTE] ==== Your business might tell you that your hard constraints all have the same weight, because they cannot be broken (so the weight does not matter). This is not true because if no feasible solution exists for a specific dataset, the least infeasible solution allows the business to estimate how many business resources they are lacking. For example in cloud balancing, how many new computers to buy. Furthermore, it will likely create a <>. For example in cloud balance if a `Computer` has seven CPU too little for its ``Process``es, then it must be weighted seven times as much as if it had only one CPU too little. ==== Three or more score levels are also supported. For example: a company might decide that profit outranks employee satisfaction (or vice versa), while both are outranked by the constraints of physical reality. [NOTE] ==== To model <>, there is no need to use lots of score levels (even though OptaPlanner can handle many score levels). ==== Most use cases use a `Score` with two or three weights, such as <> and <>. [[paretoScoring]] === Pareto scoring (AKA multi-objective optimization scoring) Far less common is the use case of pareto optimization, which is also known as _multi-objective optimization_. In pareto scoring, score constraints are in the same score level, yet they are not weighted against each other. When two scores are compared, each of the score constraints are compared individually and the score with the most dominating score constraints wins. Pareto scoring can even be combined with score levels and score constraint weighting. Consider this example with positive constraints, where we want to get the most apples and oranges. Since it is impossible to compare apples and oranges, we cannot weigh them against each other. Yet, despite that we cannot compare them, we can state that two apples are better than one apple. Similarly, we can state that two apples and one orange are better than just one orange. So despite our inability to compare some Scores conclusively (at which point we declare them equal), we can find a set of optimal scores. Those are called pareto optimal. image::score-calculation/paretoOptimizationScoring.png[align=""center""] Scores are considered equal far more often. It is left up to a human to choose the better out of a set of best solutions (with equal scores) found by OptaPlanner. In the example above, the user must choose between solution A (three apples and one orange) and solution B (one apple and six oranges). It is guaranteed that OptaPlanner has not found another solution which has more apples or more oranges or even a better combination of both (such as two apples and three oranges). Pareto scoring is currently not supported in OptaPlanner. [NOTE] ==== A pareto ``Score``'s `compareTo` method is not transitive because it does a pareto comparison. For example: having two apples is greater than one apple. One apple is equal to One orange. Yet, two apples are not greater than one orange (but actually equal). Pareto comparison violates the contract of the interface ``java.lang.Comparable``'s `compareTo` method, but Planners systems are __pareto comparison safe__, unless explicitly stated otherwise in this documentation. ==== [[combiningScoreTechniques]] === Combining score techniques All the score techniques mentioned above, can be combined seamlessly: image::score-calculation/scoreComposition.png[align=""center""] [[scoreInterface]] === `Score` interface A score is represented by the `Score` interface, which naturally extends ``Comparable``: [source,java,options=""nowrap""] ---- public interface Score<...> extends Comparable<...> { ... } ---- The `Score` implementation to use depends on your use case. Your score might not efficiently fit in a single `long` value. OptaPlanner has several built-in `Score` implementations, but you can implement a custom `Score` too. Most use cases tend to use the built-in ``HardSoftScore``. image::score-calculation/scoreClassDiagram.png[align=""center""] All Score implementations also have an `initScore` (which is an ``int``).It is mostly intended for internal use in OptaPlanner: it is the negative number of uninitialized planning variables. From a user's perspective this is ``0``, unless a Construction Heuristic is terminated before it could initialize all planning variables (in which case `Score.isSolutionInitialized()` returns ``false``). The `Score` implementation (for example ``HardSoftScore``) must be the same throughout a `Solver` runtime. The `Score` implementation is configured in the solution domain class: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... @PlanningScore private HardSoftScore score; } ---- [[avoidFloatingPointNumbersInScoreCalculation]] === Avoid floating point numbers in score calculation Avoid the use of `float` or `double` in score calculation. Use `BigDecimal` or scaled `long` instead. Floating point numbers (``float`` and ``double``) cannot represent a decimal number correctly. For example: a `double` cannot hold the value `0.05` correctly. Instead, it holds the nearest representable value. Arithmetic (including addition and subtraction) with floating point numbers, especially for planning problems, leads to incorrect decisions: image::score-calculation/scoreWeightType.png[align=""center""] Additionally, floating point number addition is not associative: [source,java,options=""nowrap""] ---- System.out.println( ((0.01 + 0.02) + 0.03) == (0.01 + (0.02 + 0.03)) ); // returns false ---- This leads to __score corruption__. Decimal numbers (``BigDecimal``) have none of these problems. [NOTE] ==== BigDecimal arithmetic is considerably slower than ``int``, `long` or `double` arithmetic. In experiments we have seen the score calculation take five times longer. Therefore, in many cases, it can be worthwhile to multiply _all_ numbers for a single score weight by a plural of ten, so the score weight fits in a scaled `int` or ``long``. For example, if we multiply all weights by ``1000``, a fuelCost of `0.07` becomes a fuelCostMillis of `70` and no longer uses a decimal score weight. ==== [[scoreType]] == Choose a score type Depending on the number of score levels and type of score weights you need, choose a `Score` type. Most use cases use a ``HardSoftScore``. [NOTE] ==== To properly write a `Score` to a database (with JPA/Hibernate) or to XML/JSON (with XStream/JAXB/Jackson), see xref:integration/integration.adoc#integration[the integration chapter]. ==== [[simpleScore]] === `SimpleScore` A `SimpleScore` has a single `int` value, for example ``-123``. It has a single score level. [source,java,options=""nowrap""] ---- @PlanningScore private SimpleScore score; ---- Variants of this `Score` type: * `SimpleLongScore` uses a `long` value instead of an `int` value. * `SimpleBigDecimalScore` uses a `BigDecimal` value instead of an `int` value. [[hardSoftScore]] === `HardSoftScore` (Recommended) A `HardSoftScore` has a hard `int` value and a soft `int` value, for example ``-123hard/-456soft``. It has two score levels (hard and soft). [source,java,options=""nowrap""] ---- @PlanningScore private HardSoftScore score; ---- Variants of this `Score` type: * `HardSoftLongScore` uses `long` values instead of `int` values. * `HardSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[hardMediumSoftScore]] === `HardMediumSoftScore` A `HardMediumSoftScore` which has a hard `int` value, a medium `int` value and a soft `int` value, for example ``-123hard/-456medium/-789soft``. It has three score levels (hard, medium and soft). The hard level determines if the solution is feasible, and the medium level and soft level score values determine how well the solution meets business goals. Higher medium values take precedence over soft values irrespective of the soft value. [source,java,options=""nowrap""] ---- @PlanningScore private HardMediumSoftScore score; ---- Variants of this `Score` type: * `HardMediumSoftLongScore` uses `long` values instead of `int` values. * `HardMediumSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[bendableScore]] === `BendableScore` A `BendableScore` has a configurable number of score levels. It has an array of hard `int` values and an array of soft `int` values, for example with two hard levels and three soft levels, the score can be ``[-123/-456]hard/[-789/-012/-345]soft``. In that case, it has five score levels. A solution is feasible if all hard levels are at least zero. A BendableScore with one hard level and one soft level is equivalent to a HardSoftScore, while a BendableScore with one hard level and two soft levels is equivalent to a HardMediumSoftScore. [source,java,options=""nowrap""] ---- @PlanningScore(bendableHardLevelsSize = 2, bendableSoftLevelsSize = 3) private BendableScore score; ---- The number of hard and soft score levels need to be set at compilation time. It is not flexible to change during solving. [NOTE] ==== Do not use a `BendableScore` with seven levels just because you have seven constraints. It is extremely rare to use a different score level for each constraint, because that means one constraint match on soft 0 outweighs even a million constraint matches of soft 1. Usually, multiple constraints share the same level and are weighted against each other. Use <> to get the weight of individual constraints in the same level. ==== Variants of this `Score` type: * `BendableLongScore` uses `long` values instead of `int` values. * `BendableBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[calculateTheScore]] == Calculate the `Score` [[scoreCalculationTypes]] === Score calculation types There are several ways to calculate the `Score` of a solution: * **<>**: Implement all constraints together in a single method in Java (or another JVM language). Does not scale. * **xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams score calculation]**: Implement each constraint as a separate Constraint Stream in Java (or another JVM language). Fast and scalable. * **<>** (not recommended): Implement multiple low-level methods in Java (or another JVM language). Fast and scalable. Very difficult to implement and maintain. * **xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation]**: Implement each constraint as a separate score rule in DRL. Scalable. Every score calculation type can work with any Score definition (such as ``HardSoftScore`` or ``HardMediumSoftScore``). All score calculation types are Object Oriented and can reuse existing Java code. [IMPORTANT] ==== The score calculation must be read-only. It must not change the planning entities or the problem facts in any way. For example, it must not call a setter method on a planning entity in the score calculation. OptaPlanner does not recalculate the score of a solution if it can predict it (unless an xref:planner-configuration/planner-configuration.adoc#environmentMode[environmentMode assertion] is enabled). For example, after a winning step is done, there is no need to calculate the score because that move was done and undone earlier. As a result, there is no guarantee that changes applied during score calculation actually happen. To update planning entities when the planning variable change, use xref:shadow-variable/shadow-variable.adoc#shadowVariable[shadow variables] instead. ==== [[easyJavaScoreCalculation]] === Easy Java score calculation An easy way to implement your score calculation in Java. * Advantages: ** Plain old Java: no learning curve ** Opportunity to delegate score calculation to an existing code base or legacy system * Disadvantages: ** Slower ** Does not scale because there is no <> Implement the one method of the interface ``EasyScoreCalculator``: [source,java,options=""nowrap""] ---- public interface EasyScoreCalculator> { Score_ calculateScore(Solution_ solution); } ---- For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensEasyScoreCalculator implements EasyScoreCalculator { @Override public SimpleScore calculateScore(NQueens nQueens) { int n = nQueens.getN(); List queenList = nQueens.getQueenList(); int score = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { Queen leftQueen = queenList.get(i); Queen rightQueen = queenList.get(j); if (leftQueen.getRow() != null && rightQueen.getRow() != null) { if (leftQueen.getRowIndex() == rightQueen.getRowIndex()) { score--; } if (leftQueen.getAscendingDiagonalIndex() == rightQueen.getAscendingDiagonalIndex()) { score--; } if (leftQueen.getDescendingDiagonalIndex() == rightQueen.getDescendingDiagonalIndex()) { score--; } } } } return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- To configure values of an `EasyScoreCalculator` dynamically in the solver configuration (so the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] can tweak those parameters), add the `easyScoreCalculatorCustomProperties` element and use xref:planner-configuration/planner-configuration.adoc#customPropertiesConfiguration[custom properties]: [source,xml,options=""nowrap""] ---- ...MyEasyScoreCalculator ---- [[incrementalJavaScoreCalculation]] === Incremental Java score calculation A way to implement your score calculation incrementally in Java. * Advantages: ** Very fast and scalable *** Currently the fastest if implemented correctly * Disadvantages: ** Hard to write *** A scalable implementation heavily uses maps, indexes, ... (things the Drools rule engine can do for you) *** You have to learn, design, write and improve all these performance optimizations yourself ** Hard to read *** Regular score constraint changes can lead to a high maintenance cost Implement all the methods of the interface `IncrementalScoreCalculator`: [source,java,options=""nowrap""] ---- public interface IncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution); void beforeEntityAdded(Object entity); void afterEntityAdded(Object entity); void beforeVariableChanged(Object entity, String variableName); void afterVariableChanged(Object entity, String variableName); void beforeEntityRemoved(Object entity); void afterEntityRemoved(Object entity); Score_ calculateScore(); } ---- image::score-calculation/incrementalScoreCalculatorSequenceDiagram.png[align=""center""] For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensAdvancedIncrementalScoreCalculator extends IncrementalScoreCalculator { private Map> rowIndexMap; private Map> ascendingDiagonalIndexMap; private Map> descendingDiagonalIndexMap; private int score; public void resetWorkingSolution(NQueens nQueens) { int n = nQueens.getN(); rowIndexMap = new HashMap>(n); ascendingDiagonalIndexMap = new HashMap>(n * 2); descendingDiagonalIndexMap = new HashMap>(n * 2); for (int i = 0; i < n; i++) { rowIndexMap.put(i, new ArrayList(n)); ascendingDiagonalIndexMap.put(i, new ArrayList(n)); descendingDiagonalIndexMap.put(i, new ArrayList(n)); if (i != 0) { ascendingDiagonalIndexMap.put(n - 1 + i, new ArrayList(n)); descendingDiagonalIndexMap.put((-i), new ArrayList(n)); } } score = 0; for (Queen queen : nQueens.getQueenList()) { insert(queen); } } public void beforeEntityAdded(Object entity) { // Do nothing } public void afterEntityAdded(Object entity) { insert((Queen) entity); } public void beforeVariableChanged(Object entity, String variableName) { retract((Queen) entity); } public void afterVariableChanged(Object entity, String variableName) { insert((Queen) entity); } public void beforeEntityRemoved(Object entity) { retract((Queen) entity); } public void afterEntityRemoved(Object entity) { // Do nothing } private void insert(Queen queen) { Row row = queen.getRow(); if (row != null) { int rowIndex = queen.getRowIndex(); List rowIndexList = rowIndexMap.get(rowIndex); score -= rowIndexList.size(); rowIndexList.add(queen); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); score -= ascendingDiagonalIndexList.size(); ascendingDiagonalIndexList.add(queen); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); score -= descendingDiagonalIndexList.size(); descendingDiagonalIndexList.add(queen); } } private void retract(Queen queen) { Row row = queen.getRow(); if (row != null) { List rowIndexList = rowIndexMap.get(queen.getRowIndex()); rowIndexList.remove(queen); score += rowIndexList.size(); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); ascendingDiagonalIndexList.remove(queen); score += ascendingDiagonalIndexList.size(); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); descendingDiagonalIndexList.remove(queen); score += descendingDiagonalIndexList.size(); } } public SimpleScore calculateScore() { return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensAdvancedIncrementalScoreCalculator ---- [IMPORTANT] ==== A piece of incremental score calculator code can be difficult to write and to review. <> by using an ``EasyScoreCalculator`` to fulfill the assertions triggered by the ``environmentMode``. ==== To configure values of an `IncrementalScoreCalculator` dynamically in the solver configuration (so the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] can tweak those parameters), add the `incrementalScoreCalculatorCustomProperties` element and use xref:planner-configuration/planner-configuration.adoc#customPropertiesConfiguration[custom properties]: [source,xml,options=""nowrap""] ---- ...MyIncrementalScoreCalculator ---- [[constraintMatchAwareIncrementalScoreCalculator]] ==== `ConstraintMatchAwareIncrementalScoreCalculator` Optionally, also implement the `ConstraintMatchAwareIncrementalScoreCalculator` interface to: * Explain a score by splitting it up per score constraint with `ScoreExplanation.getConstraintMatchTotalMap()`. * Visualize or sort planning entities by how many constraints each one breaks with `ScoreExplanation.getIndictmentMap()`. * Receive a detailed analysis if the `IncrementalScoreCalculator` is corrupted in `FAST_ASSERT` or `FULL_ASSERT` `environmentMode`, [source,java,options=""nowrap""] ---- public interface ConstraintMatchAwareIncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution, boolean constraintMatchEnabled); Collection> getConstraintMatchTotals(); Map> getIndictmentMap(); } ---- For example in machine reassignment, create one `ConstraintMatchTotal` per constraint type and call `addConstraintMatch()` for each constraint match: [source,java,options=""nowrap""] ---- public class MachineReassignmentIncrementalScoreCalculator implements ConstraintMatchAwareIncrementalScoreCalculator { ... @Override public void resetWorkingSolution(MachineReassignment workingSolution, boolean constraintMatchEnabled) { resetWorkingSolution(workingSolution); // ignore constraintMatchEnabled, it is always presumed enabled } @Override public Collection> getConstraintMatchTotals() { ConstraintMatchTotal maximumCapacityMatchTotal = new DefaultConstraintMatchTotal<>(CONSTRAINT_PACKAGE, ""maximumCapacity"", HardSoftLongScore.ZERO); ... for (MrMachineScorePart machineScorePart : machineScorePartMap.values()) { for (MrMachineCapacityScorePart machineCapacityScorePart : machineScorePart.machineCapacityScorePartList) { if (machineCapacityScorePart.maximumAvailable < 0L) { maximumCapacityMatchTotal.addConstraintMatch( Arrays.asList(machineCapacityScorePart.machineCapacity), HardSoftLongScore.valueOf(machineCapacityScorePart.maximumAvailable, 0)); } } } ... List> constraintMatchTotalList = new ArrayList<>(4); constraintMatchTotalList.add(maximumCapacityMatchTotal); ... return constraintMatchTotalList; } @Override public Map> getIndictmentMap() { return null; // Calculate it non-incrementally from getConstraintMatchTotals() } } ---- That `getConstraintMatchTotals()` code often duplicates some of the logic of the normal `IncrementalScoreCalculator` methods. Constraint Streams and Drools Score Calculation don't have this disadvantage, because they are constraint match aware automatically when needed, without any extra domain-specific code. [[initializingScoreTrend]] === `InitializingScoreTrend` The `InitializingScoreTrend` specifies how the Score will change as more and more variables are initialized (while the already initialized variables do not change). Some optimization algorithms (such Construction Heuristics and Exhaustive Search) run faster if they have such information. For the Score (or each <> separately), specify a trend: * `ANY` (default): Initializing an extra variable can change the score positively or negatively. Gives no performance gain. * `ONLY_UP` (rare): Initializing an extra variable can only change the score positively. Implies that: ** There are only positive constraints ** And initializing the next variable cannot unmatch a positive constraint that was matched by a previous initialized variable. * ``ONLY_DOWN``: Initializing an extra variable can only change the score negatively. Implies that: ** There are only negative constraints ** And initializing the next variable cannot unmatch a negative constraint that was matched by a previous initialized variable. Most use cases only have negative constraints. Many of those have an `InitializingScoreTrend` that only goes down: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN ---- Alternatively, you can also specify the trend for each score level separately: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN/ONLY_DOWN ---- [[invalidScoreDetection]] === Invalid score detection When you put the xref:planner-configuration/planner-configuration.adoc#environmentMode[`environmentMode`] in `FULL_ASSERT` (or ``FAST_ASSERT``), it will detect score corruption in the <>. However, that will not verify that your score calculator actually implements your score constraints as your business desires. For example, one constraint might consistently match the wrong pattern. To verify the constraints against an independent implementation, configure a ``assertionScoreDirectorFactory``: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... org.optaplanner.examples.nqueens.optional.score.NQueensConstraintProviderorg.optaplanner.examples.nqueens.optional.score.NQueensConstraintProvider org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- This way, the `NQueensConstraintProvider` implementation is validated by the ``EasyScoreCalculator``. [NOTE] ==== This works well to isolate score corruption, but to verify that the constraint implement the real business needs, xref:constraint-streams/constraint-streams.adoc#constraintStreamsTesting[a unit test with a ConstraintVerifier] is usually better. ==== [[scoreCalculationPerformanceTricks]] == Score calculation performance tricks [[scoreCalculationPerformanceTricksOverview]] === Overview The `Solver` will normally spend most of its execution time running the score calculation (which is called in its deepest loops). Faster score calculation will return the same solution in less time with the same algorithm, which normally means a better solution in equal time. [[scoreCalculationSpeed]] === Score calculation speed After solving a problem, the `Solver` will log the __score calculation speed per second__. This is a good measurement of Score calculation performance, despite that it is affected by non score calculation execution time. It depends on the problem scale of the problem dataset. Normally, even for high scale problems, it is higher than ``1000``, except if you are using an ``EasyScoreCalculator``. [IMPORTANT] ==== When improving your score calculation, focus on maximizing the score calculation speed, instead of maximizing the best score. A big improvement in score calculation can sometimes yield little or no best score improvement, for example when the algorithm is stuck in a local or global optima. If you are watching the calculation speed instead, score calculation improvements are far more visible. Furthermore, watching the calculation speed allows you to remove or add score constraints, and still compare it with the original's calculation speed. Comparing the best score with the original's best score is pointless: it's comparing apples and oranges. ==== [[incrementalScoreCalculation]] === Incremental score calculation (with deltas) When a solution changes, incremental score calculation (AKA delta based score calculation) calculates the delta with the previous state to find the new ``Score``, instead of recalculating the entire score on every solution evaluation. For example, when a single queen A moves from row `1` to ``2``, it will not bother to check if queen B and C can attack each other, since neither of them changed: image::score-calculation/incrementalScoreCalculationNQueens04.png[align=""center""] Similarly in employee rostering: image::score-calculation/incrementalScoreCalculationEmployeeRostering.png[align=""center""] This is a huge performance and scalability gain. *xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint Streams] or xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] give you this huge scalability gain without forcing you to write a complicated incremental score calculation algorithm.* Just let the rule engine do the hard work. Notice that the speedup is relative to the size of your planning problem (your __n__), making incremental score calculation far more scalable. [[avoidCallingRemoteServicesDuringScoreCalculation]] === Avoid calling remote services during score calculation Do not call remote services in your score calculation (except if you are bridging `EasyScoreCalculator` to a legacy system). The network latency will kill your score calculation performance. Cache the results of those remote services if possible. If some parts of a constraint can be calculated once, when the `Solver` starts, and never change during solving, then turn them into xref:planner-configuration/planner-configuration.adoc#cachedProblemFact[cached problem facts]. [[pointlessConstraints]] === Pointless constraints If you know a certain constraint can never be broken (or it is always broken), do not write a score constraint for it. For example in n queens, the score calculation does not check if multiple queens occupy the same column, because a ``Queen``'s `column` never changes and every solution starts with each `Queen` on a different ``column``. [NOTE] ==== Do not go overboard with this. If some datasets do not use a specific constraint but others do, just return out of the constraint as soon as you can. There is no need to dynamically change your score calculation based on the dataset. ==== [[buildInHardConstraint]] === Built-in hard constraint Instead of implementing a hard constraint, it can sometimes be built in. For example, if `Lecture` A should never be assigned to `Room` X, but it uses `ValueRangeProvider` on Solution, so the `Solver` will often try to assign it to `Room` X too (only to find out that it breaks a hard constraint). Use xref:planner-configuration/planner-configuration.adoc#valueRangeProviderOnPlanningEntity[a ValueRangeProvider on the planning entity] or xref:move-and-neighborhood-selection/move-and-neighborhood-selection.adoc#filteredSelection[filtered selection] to define that Course A should only be assigned a `Room` different than X. This can give a good performance gain in some use cases, not just because the score calculation is faster, but mainly because most optimization algorithms will spend less time evaluating infeasible solutions. However, usually this is not a good idea because there is a real risk of trading short term benefits for long term harm: * Many optimization algorithms rely on the freedom to break hard constraints when changing planning entities, to get out of local optima. * Both implementation approaches have limitations (feature compatibility, disabling automatic performance optimizations), as explained in their documentation. [[otherScoreCalculationPerformanceTricks]] === Other score calculation performance tricks * Verify that your score calculation happens in the correct `Number` type. If you are making the sum of `int` values, do not sum it in a `double` which takes longer. * For optimal performance, always use server mode (``java -server``). We have seen performance increases of 50% by turning on server mode. * For optimal performance, use the latest Java version. For example, in the past we have seen performance increases of 30% by switching from java 1.5 to 1.6. * Always remember that premature optimization is the root of all evil. Make sure your design is flexible enough to allow configuration based tweaking. [[scoreTrap]] === Score trap Make sure that none of your score constraints cause a score trap. A trapped score constraint uses the same weight for different constraint matches, when it could just as easily use a different weight. It effectively lumps its constraint matches together, which creates a flatlined score function for that constraint. This can cause a solution state in which several moves need to be done to resolve or lower the weight of that single constraint. Some examples of score traps: * You need two doctors at each table, but you are only moving one doctor at a time. So the solver has no incentive to move a doctor to a table with no doctors. Punish a table with no doctors more than a table with only one doctor in that score constraint in the score function. * Two exams need to be conducted at the same time, but you are only moving one exam at a time. So the solver has to move one of those exams to another timeslot without moving the other in the same move. Add a coarse-grained move that moves both exams at the same time. For example, consider this score trap. If the blue item moves from an overloaded computer to an empty computer, the hard score should improve. The trapped score implementation fails to do that: image::score-calculation/scoreTrap.png[align=""center""] The Solver should eventually get out of this trap, but it will take a lot of effort (especially if there are even more processes on the overloaded computer). Before they do that, they might actually start moving more processes into that overloaded computer, as there is no penalty for doing so. [NOTE] ==== Avoiding score traps does not mean that your score function should be smart enough to avoid local optima. Leave it to the optimization algorithms to deal with the local optima. Avoiding score traps means to avoid, for each score constraint individually, a flatlined score function. ==== [IMPORTANT] ==== Always specify the degree of infeasibility. The business will often say ""if the solution is infeasible, it does not matter how infeasible it is."" While that is true for the business, it is not true for score calculation as it benefits from knowing how infeasible it is. In practice, soft constraints usually do this naturally and it is just a matter of doing it for the hard constraints too. ==== There are several ways to deal with a score trap: * Improve the score constraint to make a distinction in the score weight. For example, penalize `-1hard` for every missing CPU, instead of just `-1hard` if any CPU is missing. * If changing the score constraint is not allowed from the business perspective, add a lower score level with a score constraint that makes such a distinction. For example, penalize `-1subsoft` for every missing CPU, on top of `-1hard` if any CPU is missing. The business ignores the subsoft score level. * Add coarse-grained moves and union select them with the existing fine-grained moves. A coarse-grained move effectively does multiple moves to directly get out of a score trap with a single move. For example, move multiple items from the same container to another container. [[stepLimitBenchmark]] === `stepLimit` benchmark Not all score constraints have the same performance cost. Sometimes one score constraint can kill the score calculation performance outright. Use the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] to do a one minute run and check what happens to the score calculation speed if you comment out all but one of the score constraints. [[fairnessScoreConstraints]] === Fairness score constraints Some use cases have a business requirement to provide a fair schedule (usually as a soft score constraint), for example: * Fairly distribute the workload amongst the employees, to avoid envy. * Evenly distribute the workload amongst assets, to improve reliability. Implementing such a constraint can seem difficult (especially because there are different ways to formalize fairness), but usually the _squared workload_ implementation behaves most desirable. For each employee/asset, count the workload `w` and subtract `w²` from the score. image::score-calculation/fairnessScoreConstraint.png[align=""center""] As shown above, the _squared workload_ implementation guarantees that if you select two employees from a given solution and make their distribution between those two employees fairer, then the resulting new solution will have a better overall score. Do not just use the difference from the average workload, as that can lead to unfairness, as demonstrated below. image::score-calculation/fairnessScoreConstraintPitfall.png[align=""center""] [NOTE] ==== Instead of the _squared workload_, it is also possible to use the https://en.wikipedia.org/wiki/Variance[variance] (squared difference to the average) or the http://en.wikipedia.org/wiki/Standard_deviation[standard deviation] (square root of the variance). This has no effect on the score comparison, because the average will not change during planning. It is just more work to implement (because the average needs to be known) and trivially slower (because the calculation is a bit longer). ==== When the workload is perfectly balanced, the user often likes to see a `0` score, instead of the distracting `-34soft` in the image above (for the last solution which is almost perfectly balanced). To nullify this, either add the average multiplied by the number of entities to the score or instead show the variance or standard deviation in the UI. [[constraintConfiguration]] == Constraint configuration: adjust constraint weights dynamically Deciding the correct <> and <> for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: image::score-calculation/parameterizeTheScoreWeights.png[align=""center""] [[createAConstraintConfiguration]] === Create a constraint configuration First, create a new class to hold the constraint weights and other constraint parameters. Annotate it with `@ConstraintConfiguration`: [source,java,options=""nowrap""] ---- @ConstraintConfiguration public class ConferenceConstraintConfiguration { ... } ---- There will be exactly one instance of this class per planning solution. The planning solution and the constraint configuration have a one-to-one relationship, but they serve a different purpose, so they aren't merged into a single class. A `@ConstraintConfiguration` class can extend a parent `@ConstraintConfiguration` class, which can be useful in international use cases with many regional constraints. Add the constraint configuration on the planning solution and annotate that field or property with `@ConstraintConfigurationProvider`: [source,java,options=""nowrap""] ---- @PlanningSolution public class ConferenceSolution { @ConstraintConfigurationProvider private ConferenceConstraintConfiguration constraintConfiguration; ... } ---- The `@ConstraintConfigurationProvider` annotation automatically exposes the constraint configuration as a xref:planner-configuration/planner-configuration.adoc#problemFacts[problem fact], there is no need to add a `@ProblemFactProperty` annotation. The constraint configuration class holds the <>, but it can also hold constraint parameters. For example in conference scheduling, the minimum pause constraint has a constraint weight (like any other constraint), but it also has a constraint parameter that defines the length of the minimum pause between two talks of the same speaker. That pause length depends on the conference (= the planning problem): in some big conferences 20 minutes isn't enough to go from one room to the other. That pause length is a field in the constraint configuration without a `@ConstraintWeight` annotation. [[constraintWeight]] === Add a constraint weight for each constraint In the constraint configuration class, add a `@ConstraintWeight` field or property for each constraint: [source,java,options=""nowrap""] ---- @ConstraintConfiguration(constraintPackage = ""...conferencescheduling.score"") public class ConferenceConstraintConfiguration { @ConstraintWeight(""Speaker conflict"") private HardMediumSoftScore speakerConflict = HardMediumSoftScore.ofHard(10); @ConstraintWeight(""Theme track conflict"") private HardMediumSoftScore themeTrackConflict = HardMediumSoftScore.ofSoft(10); @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ... } ---- The type of the constraint weights must be the same score class as xref:planner-configuration/planner-configuration.adoc#scoreOfASolution[the planning solution's score member]. For example in conference scheduling, `ConferenceSolution.getScore()` and `ConferenceConstraintConfiguration.getSpeakerConflict()` both return a `HardMediumSoftScore`. A constraint weight cannot be null. Give each constraint weight a default value, but expose them in a UI so the business users can tweak them. The example above uses the `ofHard()`, `ofMedium()` and `ofSoft()` methods to do that. Notice how it defaults the _content conflict_ constraint as ten times more important than the _theme track conflict_ constraint. Normally, a constraint weight only uses one score level, but it's possible to use multiple score levels (at a small performance cost). Each constraint has a constraint package and a constraint name, together they form the constraint id. These connect the constraint weight with the constraint implementation. *For each constraint weight, there must be a constraint implementation with the same package and the same name.* * The `@ConstraintConfiguration` annotation has a `constraintPackage` property that defaults to the package of the constraint configuration class. Most cases with xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation], need to override that because the DRLs use another package. For example, the DRL below uses the package `...conferencescheduling.score`, so the constraint configuration above specifies a `constraintPackage`. Cases with xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams], normally don't need to specify it. * The `@ConstraintWeight` annotation has a `value` which is the constraint name (for example ""Speaker conflict""). It inherits the constraint package from the `@ConstraintConfiguration`, but it can override that, for example `@ConstraintWeight(constraintPackage = ""...region.france"", ...)` to use a different constraint package than some of the other weights. So every constraint weight ends up with a constraint package and a constraint name. Each constraint weight links with a constraint implementation, for example in xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation]: [source,options=""nowrap""] ---- package ...conferencescheduling.solver; rule ""Speaker conflict"" when ... then scoreHolder.penalize(kcontext); end rule ""Theme track conflict"" when ... then scoreHolder.penalize(kcontext, ...); end rule ""Content conflict"" when ... then scoreHolder.penalize(kcontext, ...); end ---- Each of the constraint weights defines the score level and score weight of their constraint. The constraint implementation calls `reward()` or `penalize()` and the constraint weight is automatically applied. If the constraint implementation provides a match weight, that *match weight is multiplied with the constraint weight*. For example, the _content conflict_ constraint weight defaults to `100soft` and the constraint implementation penalizes each match based on the number of shared content tags: [source,java,options=""nowrap""] ---- @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ---- [source,options=""nowrap""] ---- rule ""Content conflict"" when $talk1 : Talk(...) $talk2 : Talk(...) then scoreHolder.penalize(kcontext, $talk2.overlappingContentCount($talk1)); end ---- So when 2 overlapping talks share only 1 content tag, the score is impacted by `-100soft`. But when 2 overlapping talks share 3 content tags, the match weight is `3`, so the score is impacted by `-300soft`. [[explainingTheScore]] == Explaining the score: which constraints are broken? The easiest way to explain the score during development is to print the return value of `explainScore()`, but only use that method for diagnostic purposes: [source,java,options=""nowrap""] ---- System.out.println(scoreManager.explainScore(solution)); ---- For example in conference scheduling, this prints that talk `S51` is responsible for breaking the hard constraint `Speaker required room tag`: ---- Explanation of score (-1hard/-806soft): Constraint match totals: -1hard: constraint (Speaker required room tag) has 1 matches: -1hard: justifications ([S51]) -340soft: constraint (Theme track conflict) has 32 matches: -20soft: justifications ([S68, S66]) -20soft: justifications ([S61, S44]) ... ... Indictments (top 5 of 72): -1hard/-22soft: justification (S51) has 12 matches: -1hard: constraint (Speaker required room tag) -10soft: constraint (Theme track conflict) ... ... ---- [IMPORTANT] ==== Do not attempt to parse this string or use it in your UI or exposed services. Instead use the ConstraintMatch API below and do it properly. ==== [[usingScoreCalculationOutsideTheSolver]] === Using score calculation outside the `Solver` If other parts of your application, for example your webUI, need to calculate the score of a solution, use the `ScoreManager` API: [source,java,options=""nowrap""] ---- ScoreManager scoreManager = ScoreManager.create(solverFactory); ScoreExplanation scoreExplanation = scoreManager.explain(cloudBalance); ---- Then use it when you need to calculate the `Score` of a solution: [source,java,options=""nowrap""] ---- HardSoftScore score = scoreExplanation.getScore(); ---- Furthermore, the `ScoreExplanation` can help explain the score through constraint match totals and/or indictments: image::score-calculation/scoreVisualization.png[align=""center""] [[constraintMatchTotal]] === Constraint match total: break down the score by constraint To break down the score per constraint, get the ``ConstraintMatchTotal``s from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Collection> constraintMatchTotals = scoreExplanation.getConstraintMatchTotalMap().values(); for (ConstraintMatchTotal constraintMatchTotal : constraintMatchTotals) { String constraintName = constraintMatchTotal.getConstraintName(); // The score impact of that constraint HardSoftScore totalScore = constraintMatchTotal.getScore(); for (ConstraintMatch constraintMatch : constraintMatchTotal.getConstraintMatchSet()) { List justificationList = constraintMatch.getJustificationList(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `ConstraintMatchTotal` represents one constraint and has a part of the overall score. The sum of all the `ConstraintMatchTotal.getScore()` equals the overall score. [NOTE] ==== xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams] and xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] supports constraint matches automatically, but <> requires <>. ==== [[indictmentHeatMap]] === Indictment heat map: visualize the hot planning entities To show a heat map in the UI that highlights the planning entities and problem facts have an impact on the ``Score``, get the `Indictment` map from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Map> indictmentMap = scoreExplanation.getIndictmentMap(); for (CloudProcess process : cloudBalance.getProcessList()) { Indictment indictment = indictmentMap.get(process); if (indictment == null) { continue; } // The score impact of that planning entity HardSoftScore totalScore = indictment.getScore(); for (ConstraintMatch constraintMatch : indictment.getConstraintMatchSet()) { String constraintName = constraintMatch.getConstraintName(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `Indictment` is the sum of all constraints where that justification object is involved with. The sum of all the `Indictment.getScoreTotal()` differs from the overall score, because multiple ``Indictment``s can share the same `ConstraintMatch`. [NOTE] ==== xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams] and xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] supports constraint matches automatically, but <> requires <>. ==== [[testingScoreConstraints]] == Testing score constraints It's recommended to write a unit test for each score constraint individually to check that it behaves correctly. Different score calculation types come with different tools for testing. For more, see xref:constraint-streams/constraint-streams.adoc#constraintStreamsTesting[testing Constraint Streams] or xref:drools-score-calculation/drools-score-calculation.adoc#testingDroolsConstraints[testing Drools constraints]. ",12285,False,2174.935634444405,median "/******************************************************************************* * Copyright 2017 ROBOTIS CO., LTD. * * 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. *******************************************************************************/ /* Author: SCH, Jay Song, Kayman */ #include #include ""op2_kinematics_dynamics/op2_kinematics_dynamics.h"" namespace robotis_op { OP2KinematicsDynamics::OP2KinematicsDynamics() { } OP2KinematicsDynamics::~OP2KinematicsDynamics() { } OP2KinematicsDynamics::OP2KinematicsDynamics(TreeSelect2 tree) { for (int id = 0; id <= ALL_JOINT_ID; id++) op2_link_data_[id] = new LinkData(); if (tree == WholeBody2) { op2_link_data_[0]->name_ = ""base""; op2_link_data_[0]->parent_ = -1; op2_link_data_[0]->sibling_ = -1; op2_link_data_[0]->child_ = 23; op2_link_data_[0]->mass_ = 0.0; op2_link_data_[0]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[0]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[0]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[0]->joint_limit_max_ = 100.0; op2_link_data_[0]->joint_limit_min_ = -100.0; op2_link_data_[0]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /* ----- passive joint -----*/ op2_link_data_[23]->name_ = ""passive_x""; op2_link_data_[23]->parent_ = 0; op2_link_data_[23]->sibling_ = -1; op2_link_data_[23]->child_ = 24; op2_link_data_[23]->mass_ = 0.0; op2_link_data_[23]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[23]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[23]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[23]->joint_limit_max_ = 100.0; op2_link_data_[23]->joint_limit_min_ = -100.0; op2_link_data_[23]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); op2_link_data_[24]->name_ = ""passive_y""; op2_link_data_[24]->parent_ = 23; op2_link_data_[24]->sibling_ = -1; op2_link_data_[24]->child_ = 25; op2_link_data_[24]->mass_ = 0.0; op2_link_data_[24]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[24]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[24]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[24]->joint_limit_max_ = 100.0; op2_link_data_[24]->joint_limit_min_ = -100.0; op2_link_data_[24]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); op2_link_data_[25]->name_ = ""passive_z""; op2_link_data_[25]->parent_ = 24; op2_link_data_[25]->sibling_ = -1; op2_link_data_[25]->child_ = 26; op2_link_data_[25]->mass_ = 0.0; op2_link_data_[25]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.385); op2_link_data_[25]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[25]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[25]->joint_limit_max_ = 100.0; op2_link_data_[25]->joint_limit_min_ = -100.0; op2_link_data_[25]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); op2_link_data_[26]->name_ = ""passive_roll""; op2_link_data_[26]->parent_ = 25; op2_link_data_[26]->sibling_ = -1; op2_link_data_[26]->child_ = 27; op2_link_data_[26]->mass_ = 0.0; op2_link_data_[26]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[26]->joint_axis_ = robotis_framework::getTransitionXYZ(1.0, 0.0, 0.0); op2_link_data_[26]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[26]->joint_limit_max_ = 100.0; op2_link_data_[26]->joint_limit_min_ = -100.0; op2_link_data_[26]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); op2_link_data_[27]->name_ = ""passive_pitch""; op2_link_data_[27]->parent_ = 26; op2_link_data_[27]->sibling_ = -1; op2_link_data_[27]->child_ = 28; op2_link_data_[27]->mass_ = 0.0; op2_link_data_[27]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[27]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 1.0, 0.0); op2_link_data_[27]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[27]->joint_limit_max_ = 100.0; op2_link_data_[27]->joint_limit_min_ = -100.0; op2_link_data_[27]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); op2_link_data_[28]->name_ = ""passive_yaw""; op2_link_data_[28]->parent_ = 27; op2_link_data_[28]->sibling_ = -1; op2_link_data_[28]->child_ = 29; op2_link_data_[28]->mass_ = 0.0; op2_link_data_[28]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[28]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 1.0); op2_link_data_[28]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[28]->joint_limit_max_ = 100.0; op2_link_data_[28]->joint_limit_min_ = -100.0; op2_link_data_[28]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /* ----- body -----*/ // pelvis_link op2_link_data_[29]->name_ = ""pelvis""; op2_link_data_[29]->parent_ = 28; op2_link_data_[29]->sibling_ = -1; op2_link_data_[29]->child_ = 19; op2_link_data_[29]->mass_ = 6.869; op2_link_data_[29]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[29]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[29]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.011, 0.000, 0.058); op2_link_data_[29]->joint_limit_max_ = 100.0; op2_link_data_[29]->joint_limit_min_ = -100.0; op2_link_data_[29]->inertia_ = robotis_framework::getInertiaXYZ(0.03603, 0.00000, 0.00016, 0.02210, 0.00000, 0.03830); /* ----- head -----*/ // head_pan op2_link_data_[19]->name_ = ""head_pan""; op2_link_data_[19]->parent_ = 29; op2_link_data_[19]->sibling_ = 1; op2_link_data_[19]->child_ = 20; op2_link_data_[19]->mass_ = 0.087; op2_link_data_[19]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0205); op2_link_data_[19]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 1.0); op2_link_data_[19]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.000, -0.002, 0.010); op2_link_data_[19]->joint_limit_max_ = 0.5 * M_PI; op2_link_data_[19]->joint_limit_min_ = -0.5 * M_PI; op2_link_data_[19]->inertia_ = robotis_framework::getInertiaXYZ(0.00011, 0.00000, 0.00000, 0.00003, 0.00000, 0.00012); // head_tilt op2_link_data_[20]->name_ = ""head_tilt""; op2_link_data_[20]->parent_ = 19; op2_link_data_[20]->sibling_ = -1; op2_link_data_[20]->child_ = -1; op2_link_data_[20]->mass_ = 0.724; op2_link_data_[20]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.03); op2_link_data_[20]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 1.0, 0.0); op2_link_data_[20]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.009, 0.046, 0.022); op2_link_data_[20]->joint_limit_max_ = 0.5 * M_PI; op2_link_data_[20]->joint_limit_min_ = -0.5 * M_PI; op2_link_data_[20]->inertia_ = robotis_framework::getInertiaXYZ(0.00113, 0.00001, -0.00005, 0.00114, 0.00002, 0.00084); /*----- right arm -----*/ // right arm shoulder pitch op2_link_data_[1]->name_ = ""r_sho_pitch""; op2_link_data_[1]->parent_ = 29; op2_link_data_[1]->sibling_ = 2; op2_link_data_[1]->child_ = 3; op2_link_data_[1]->mass_ = 0.194; op2_link_data_[1]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, -0.0575, 0.0); op2_link_data_[1]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, -1.0, 0.0); op2_link_data_[1]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.003, -0.020, -0.005); op2_link_data_[1]->joint_limit_max_ = 0.5 * M_PI; op2_link_data_[1]->joint_limit_min_ = -0.5 * M_PI; op2_link_data_[1]->inertia_ = robotis_framework::getInertiaXYZ(0.00018, 0.0, 0.0, 0.00058, -0.00004, 0.00057); // right arm shoulder roll op2_link_data_[3]->name_ = ""r_sho_roll""; op2_link_data_[3]->parent_ = 1; op2_link_data_[3]->sibling_ = -1; op2_link_data_[3]->child_ = 5; op2_link_data_[3]->mass_ = 0.875; op2_link_data_[3]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, -0.0245, -0.016); op2_link_data_[3]->joint_axis_ = robotis_framework::getTransitionXYZ(-1.0, 0.0, 0.0); op2_link_data_[3]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.060, -0.002, 0.000); op2_link_data_[3]->joint_limit_max_ = 0.3 * M_PI; op2_link_data_[3]->joint_limit_min_ = -0.5 * M_PI; op2_link_data_[3]->inertia_ = robotis_framework::getInertiaXYZ(0.00043, 0.00000, 0.00000, 0.00112, 0.00000, 0.00113); // right arm elbow op2_link_data_[5]->name_ = ""r_el""; op2_link_data_[5]->parent_ = 3; op2_link_data_[5]->sibling_ = -1; op2_link_data_[5]->child_ = 21; op2_link_data_[5]->mass_ = 1.122; op2_link_data_[5]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, -0.09, 0.0); op2_link_data_[5]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, -1.0, 0.0); op2_link_data_[5]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.000, -0.073, 0.000); op2_link_data_[5]->joint_limit_max_ = 0.5 * M_PI; op2_link_data_[5]->joint_limit_min_ = -0.5 * M_PI; op2_link_data_[5]->inertia_ = robotis_framework::getInertiaXYZ(0.00277, 0.00002, -0.00001, 0.00090, 0.00004, 0.00255); // right arm end effector op2_link_data_[21]->name_ = ""r_arm_end""; op2_link_data_[21]->parent_ = 5; op2_link_data_[21]->sibling_ = -1; op2_link_data_[21]->child_ = -1; op2_link_data_[21]->mass_ = 0.0; op2_link_data_[21]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, -0.15, 0.0); op2_link_data_[21]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[21]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[21]->joint_limit_max_ = 100.0; op2_link_data_[21]->joint_limit_min_ = -100.0; op2_link_data_[21]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /*----- left arm -----*/ // left arm shoulder pitch op2_link_data_[2]->name_ = ""l_sho_pitch""; op2_link_data_[2]->parent_ = 29; op2_link_data_[2]->sibling_ = -1; op2_link_data_[2]->child_ = 4; op2_link_data_[2]->mass_ = 0.194; op2_link_data_[2]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0575, 0.0); op2_link_data_[2]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 1.0, 0.0); op2_link_data_[2]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.003, 0.020, -0.005); op2_link_data_[2]->joint_limit_max_ = 0.5 * M_PI; op2_link_data_[2]->joint_limit_min_ = -0.5 * M_PI; op2_link_data_[2]->inertia_ = robotis_framework::getInertiaXYZ(0.00018, 0.00000, 0.00000, 0.00058, 0.00004, 0.00057); // left arm shoulder roll op2_link_data_[4]->name_ = ""l_sho_roll""; op2_link_data_[4]->parent_ = 2; op2_link_data_[4]->sibling_ = -1; op2_link_data_[4]->child_ = 6; op2_link_data_[4]->mass_ = 0.875; op2_link_data_[4]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0245, -0.016); op2_link_data_[4]->joint_axis_ = robotis_framework::getTransitionXYZ(-1.0, 0.0, 0.0); op2_link_data_[4]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.060, 0.002, 0.000); op2_link_data_[4]->joint_limit_max_ = 0.5 * M_PI; op2_link_data_[4]->joint_limit_min_ = -0.3 * M_PI; op2_link_data_[4]->inertia_ = robotis_framework::getInertiaXYZ(0.00043, 0.00000, 0.00000, 0.00112, 0.00000, 0.00113); // left arm elbow op2_link_data_[6]->name_ = ""l_el""; op2_link_data_[6]->parent_ = 4; op2_link_data_[6]->sibling_ = -1; op2_link_data_[6]->child_ = 22; op2_link_data_[6]->mass_ = 1.122; op2_link_data_[6]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.09, 0.0); op2_link_data_[6]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 1.0, 0.0); op2_link_data_[6]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.000, 0.073, 0.000); op2_link_data_[6]->joint_limit_max_ = 0.5 * M_PI; op2_link_data_[6]->joint_limit_min_ = -0.5 * M_PI; op2_link_data_[6]->inertia_ = robotis_framework::getInertiaXYZ(0.00277, -0.00002, -0.00001, 0.00090, -0.00004, 0.00255); // left arm end effector op2_link_data_[22]->name_ = ""l_arm_end""; op2_link_data_[22]->parent_ = 6; op2_link_data_[22]->sibling_ = -1; op2_link_data_[22]->child_ = -1; op2_link_data_[22]->mass_ = 0.0; op2_link_data_[22]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.15, 0.0); op2_link_data_[22]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[22]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[22]->joint_limit_max_ = 100.0; op2_link_data_[22]->joint_limit_min_ = -100.0; op2_link_data_[22]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /* ----- right leg -----*/ // right leg hip yaw op2_link_data_[7]->name_ = ""r_hip_yaw""; op2_link_data_[7]->parent_ = 29; op2_link_data_[7]->sibling_ = 8; op2_link_data_[7]->child_ = 9; op2_link_data_[7]->mass_ = 0.243; op2_link_data_[7]->relative_position_ = robotis_framework::getTransitionXYZ(-0.005, -0.035, -0.0907); op2_link_data_[7]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, -1.0); op2_link_data_[7]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.012, 0.000, -0.025); op2_link_data_[7]->joint_limit_max_ = 0.45 * M_PI; op2_link_data_[7]->joint_limit_min_ = -0.45 * M_PI; op2_link_data_[7]->inertia_ = robotis_framework::getInertiaXYZ(0.00024, 0.00000, 0.00000, 0.00101, 0.00000, 0.00092); // right leg hip roll op2_link_data_[9]->name_ = ""r_hip_roll""; op2_link_data_[9]->parent_ = 7; op2_link_data_[9]->sibling_ = -1; op2_link_data_[9]->child_ = 11; op2_link_data_[9]->mass_ = 1.045; op2_link_data_[9]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, -0.0285); op2_link_data_[9]->joint_axis_ = robotis_framework::getTransitionXYZ(-1.0, 0.0, 0.0); op2_link_data_[9]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.068, 0.000, 0.000); op2_link_data_[9]->joint_limit_max_ = 0.3 * M_PI; op2_link_data_[9]->joint_limit_min_ = -0.3 * M_PI; op2_link_data_[9]->inertia_ = robotis_framework::getInertiaXYZ(0.00056, 0.00000, 0.00000, 0.00168, 0.00000, 0.00171); // right leg hip pitch op2_link_data_[11]->name_ = ""r_hip_pitch""; op2_link_data_[11]->parent_ = 9; op2_link_data_[11]->sibling_ = -1; op2_link_data_[11]->child_ = 13; op2_link_data_[11]->mass_ = 3.095; op2_link_data_[11]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, 0.000); op2_link_data_[11]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 1.0, 0.0); op2_link_data_[11]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.022, 0.007, -0.168); op2_link_data_[11]->joint_limit_max_ = 0.4 * M_PI; op2_link_data_[11]->joint_limit_min_ = -0.4 * M_PI; op2_link_data_[11]->inertia_ = robotis_framework::getInertiaXYZ(0.04328, -0.00028, 0.00288, 0.04042, 0.00202, 0.00560); // right leg knee op2_link_data_[13]->name_ = ""r_knee""; op2_link_data_[13]->parent_ = 11; op2_link_data_[13]->sibling_ = -1; op2_link_data_[13]->child_ = 15; op2_link_data_[13]->mass_ = 2.401; op2_link_data_[13]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, -0.110); op2_link_data_[13]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 1.0, 0.0); op2_link_data_[13]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.002, 0.066, -0.183); op2_link_data_[13]->joint_limit_max_ = 0.1 * M_PI; op2_link_data_[13]->joint_limit_min_ = -0.7 * M_PI; op2_link_data_[13]->inertia_ = robotis_framework::getInertiaXYZ(0.01971, -0.00031, -0.00294, 0.01687, -0.00140, 0.00574); // right leg ankle pitch op2_link_data_[15]->name_ = ""r_ank_pitch""; op2_link_data_[15]->parent_ = 13; op2_link_data_[15]->sibling_ = -1; op2_link_data_[15]->child_ = 17; op2_link_data_[15]->mass_ = 1.045; op2_link_data_[15]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, -0.110); op2_link_data_[15]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, -1.0, 0.0); op2_link_data_[15]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.011, 0.033, 0.000); op2_link_data_[15]->joint_limit_max_ = 0.45 * M_PI; op2_link_data_[15]->joint_limit_min_ = -0.45 * M_PI; op2_link_data_[15]->inertia_ = robotis_framework::getInertiaXYZ(0.00056, 0.00000, 0.00000, 0.00168, 0.00000, 0.00171); // right leg ankle roll op2_link_data_[17]->name_ = ""r_ank_roll""; op2_link_data_[17]->parent_ = 15; op2_link_data_[17]->sibling_ = -1; op2_link_data_[17]->child_ = 31; op2_link_data_[17]->mass_ = 0.223; op2_link_data_[17]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, 0.000); op2_link_data_[17]->joint_axis_ = robotis_framework::getTransitionXYZ(1.0, 0.0, 0.0); op2_link_data_[17]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.070, 0.000, -0.048); op2_link_data_[17]->joint_limit_max_ = 0.45 * M_PI; op2_link_data_[17]->joint_limit_min_ = -0.45 * M_PI; op2_link_data_[17]->inertia_ = robotis_framework::getInertiaXYZ(0.00022, 0.00000, -0.00001, 0.00099, 0.00000, 0.00091); // right leg end op2_link_data_[31]->name_ = ""r_leg_end""; op2_link_data_[31]->parent_ = 17; op2_link_data_[31]->sibling_ = -1; op2_link_data_[31]->child_ = -1; op2_link_data_[31]->mass_ = 0.0; op2_link_data_[31]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, -0.0305); op2_link_data_[31]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[31]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[31]->joint_limit_max_ = 100.0; op2_link_data_[31]->joint_limit_min_ = -100.0; op2_link_data_[31]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); /* ----- left leg -----*/ // left leg hip yaw op2_link_data_[8]->name_ = ""l_hip_yaw""; op2_link_data_[8]->parent_ = 29; op2_link_data_[8]->sibling_ = -1; op2_link_data_[8]->child_ = 10; op2_link_data_[8]->mass_ = 0.243; op2_link_data_[8]->relative_position_ = robotis_framework::getTransitionXYZ(-0.005, 0.035, -0.0907); op2_link_data_[8]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, -1.0); op2_link_data_[8]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.012, 0.000, -0.025); op2_link_data_[8]->joint_limit_max_ = 0.45 * M_PI; op2_link_data_[8]->joint_limit_min_ = -0.45 * M_PI; op2_link_data_[8]->inertia_ = robotis_framework::getInertiaXYZ(0.00024, 0.00000, 0.00000, 0.00101, 0.00000, 0.00092); // left leg hip roll op2_link_data_[10]->name_ = ""l_hip_roll""; op2_link_data_[10]->parent_ = 8; op2_link_data_[10]->sibling_ = -1; op2_link_data_[10]->child_ = 12; op2_link_data_[10]->mass_ = 1.045; op2_link_data_[10]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, -0.0285); op2_link_data_[10]->joint_axis_ = robotis_framework::getTransitionXYZ(-1.0, 0.0, 0.0); op2_link_data_[10]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.068, 0.000, 0.000); op2_link_data_[10]->joint_limit_max_ = 0.3 * M_PI; op2_link_data_[10]->joint_limit_min_ = -0.3 * M_PI; op2_link_data_[10]->inertia_ = robotis_framework::getInertiaXYZ(0.00056, 0.00000, 0.00000, 0.00168, 0.00000, 0.00171); // left leg hip pitch op2_link_data_[12]->name_ = ""l_hip_pitch""; op2_link_data_[12]->parent_ = 10; op2_link_data_[12]->sibling_ = -1; op2_link_data_[12]->child_ = 14; op2_link_data_[12]->mass_ = 3.095; op2_link_data_[12]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, 0.000); op2_link_data_[12]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, -1.0, 0.0); op2_link_data_[12]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.022, -0.007, -0.168); op2_link_data_[12]->joint_limit_max_ = 0.4 * M_PI; op2_link_data_[12]->joint_limit_min_ = -0.4 * M_PI; op2_link_data_[12]->inertia_ = robotis_framework::getInertiaXYZ(0.04328, 0.00028, 0.00288, 0.04042, -0.00202, 0.00560); // left leg knee pitch op2_link_data_[14]->name_ = ""l_knee""; op2_link_data_[14]->parent_ = 12; op2_link_data_[14]->sibling_ = -1; op2_link_data_[14]->child_ = 16; op2_link_data_[14]->mass_ = 2.401; op2_link_data_[14]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, -0.110); op2_link_data_[14]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, -1.0, 0.0); op2_link_data_[14]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.002, -0.066, -0.183); op2_link_data_[14]->joint_limit_max_ = 0.7 * M_PI; op2_link_data_[14]->joint_limit_min_ = -0.1 * M_PI; op2_link_data_[14]->inertia_ = robotis_framework::getInertiaXYZ(0.01971, 0.00031, -0.00294, 0.01687, 0.00140, 0.00574); // left leg ankle pitch op2_link_data_[16]->name_ = ""l_ank_pitch""; op2_link_data_[16]->parent_ = 14; op2_link_data_[16]->sibling_ = -1; op2_link_data_[16]->child_ = 18; op2_link_data_[16]->mass_ = 1.045; op2_link_data_[16]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, -0.110); op2_link_data_[16]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 1.0, 0.0); op2_link_data_[16]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.011, -0.033, 0.000); op2_link_data_[16]->joint_limit_max_ = 0.45 * M_PI; op2_link_data_[16]->joint_limit_min_ = -0.45 * M_PI; op2_link_data_[16]->inertia_ = robotis_framework::getInertiaXYZ(0.00056, 0.00000, 0.00000, 0.00168, 0.00000, 0.00171); // left leg ankle roll op2_link_data_[18]->name_ = ""l_ank_roll""; op2_link_data_[18]->parent_ = 16; op2_link_data_[18]->sibling_ = -1; op2_link_data_[18]->child_ = 30; op2_link_data_[18]->mass_ = 0.223; op2_link_data_[18]->relative_position_ = robotis_framework::getTransitionXYZ(0.000, 0.000, 0.000); op2_link_data_[18]->joint_axis_ = robotis_framework::getTransitionXYZ(1.0, 0.0, 0.0); op2_link_data_[18]->center_of_mass_ = robotis_framework::getTransitionXYZ(-0.070, 0.000, -0.048); op2_link_data_[18]->joint_limit_max_ = 0.45 * M_PI; op2_link_data_[18]->joint_limit_min_ = -0.45 * M_PI; op2_link_data_[18]->inertia_ = robotis_framework::getInertiaXYZ(0.00022, 0.00000, -0.00001, 0.00099, 0.00000, 0.00091); // left leg end op2_link_data_[30]->name_ = ""l_leg_end""; op2_link_data_[30]->parent_ = 18; op2_link_data_[30]->sibling_ = -1; op2_link_data_[30]->child_ = -1; op2_link_data_[30]->mass_ = 0.0; op2_link_data_[30]->relative_position_ = robotis_framework::getTransitionXYZ(0.0, 0.0, -0.0305); op2_link_data_[30]->joint_axis_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[30]->center_of_mass_ = robotis_framework::getTransitionXYZ(0.0, 0.0, 0.0); op2_link_data_[30]->joint_limit_max_ = 100.0; op2_link_data_[30]->joint_limit_min_ = -100.0; op2_link_data_[30]->inertia_ = robotis_framework::getInertiaXYZ(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); } thigh_length_m_ = std::fabs(op2_link_data_[ID_R_LEG_START + 2 * 3]->relative_position_.coeff(2, 0)); calf_length_m_ = std::fabs(op2_link_data_[ID_R_LEG_START + 2 * 4]->relative_position_.coeff(2, 0)); ankle_length_m_ = std::fabs(op2_link_data_[ID_R_LEG_END]->relative_position_.coeff(2, 0)); leg_side_offset_m_ = 2.0 * (std::fabs(op2_link_data_[ID_R_LEG_START]->relative_position_.coeff(1, 0))); } std::vector OP2KinematicsDynamics::findRoute(int to) { int id = op2_link_data_[to]->parent_; std::vector idx; if (id == 0) { idx.push_back(0); idx.push_back(to); } else { idx = findRoute(id); idx.push_back(to); } return idx; } std::vector OP2KinematicsDynamics::findRoute(int from, int to) { int id = op2_link_data_[to]->parent_; std::vector idx; if (id == from) { idx.push_back(from); idx.push_back(to); } else if (id != 0) { idx = findRoute(from, id); idx.push_back(to); } return idx; } double OP2KinematicsDynamics::calcTotalMass(int joint_id) { double mass; if (joint_id == -1) mass = 0.0; else mass = op2_link_data_[joint_id]->mass_ + calcTotalMass(op2_link_data_[joint_id]->sibling_) + calcTotalMass(op2_link_data_[joint_id]->child_); return mass; } Eigen::MatrixXd OP2KinematicsDynamics::calcMC(int joint_id) { Eigen::MatrixXd mc(3, 1); if (joint_id == -1) mc = Eigen::MatrixXd::Zero(3, 1); else { mc = op2_link_data_[joint_id]->mass_ * (op2_link_data_[joint_id]->orientation_ * op2_link_data_[joint_id]->center_of_mass_ + op2_link_data_[joint_id]->position_); mc = mc + calcMC(op2_link_data_[joint_id]->sibling_) + calcMC(op2_link_data_[joint_id]->child_); } return mc; } Eigen::MatrixXd OP2KinematicsDynamics::calcCOM(Eigen::MatrixXd mc) { double mass; Eigen::MatrixXd COM(3, 1); mass = calcTotalMass(0); COM = mc / mass; return COM; } void OP2KinematicsDynamics::calcForwardKinematics(int joint_id) { if (joint_id == -1) return; if (joint_id == 0) { op2_link_data_[0]->position_ = Eigen::MatrixXd::Zero(3, 1); op2_link_data_[0]->orientation_ = robotis_framework::calcRodrigues( robotis_framework::calcHatto(op2_link_data_[0]->joint_axis_), op2_link_data_[0]->joint_angle_); } if (joint_id != 0) { int parent = op2_link_data_[joint_id]->parent_; op2_link_data_[joint_id]->position_ = op2_link_data_[parent]->orientation_ * op2_link_data_[joint_id]->relative_position_ + op2_link_data_[parent]->position_; op2_link_data_[joint_id]->orientation_ = op2_link_data_[parent]->orientation_ * robotis_framework::calcRodrigues(robotis_framework::calcHatto(op2_link_data_[joint_id]->joint_axis_), op2_link_data_[joint_id]->joint_angle_); op2_link_data_[joint_id]->transformation_.block<3, 1>(0, 3) = op2_link_data_[joint_id]->position_; op2_link_data_[joint_id]->transformation_.block<3, 3>(0, 0) = op2_link_data_[joint_id]->orientation_; } calcForwardKinematics(op2_link_data_[joint_id]->sibling_); calcForwardKinematics(op2_link_data_[joint_id]->child_); } Eigen::MatrixXd OP2KinematicsDynamics::calcJacobian(std::vector idx) { int idx_size = idx.size(); int end = idx_size - 1; Eigen::MatrixXd tar_position = op2_link_data_[idx[end]]->position_; Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(6, idx_size); for (int id = 0; id < idx_size; id++) { int curr_id = idx[id]; Eigen::MatrixXd tar_orientation = op2_link_data_[curr_id]->orientation_ * op2_link_data_[curr_id]->joint_axis_; jacobian.block(0, id, 3, 1) = robotis_framework::calcCross(tar_orientation, tar_position - op2_link_data_[curr_id]->position_); jacobian.block(3, id, 3, 1) = tar_orientation; } return jacobian; } Eigen::MatrixXd OP2KinematicsDynamics::calcJacobianCOM(std::vector idx) { int idx_size = idx.size(); int end = idx_size - 1; Eigen::MatrixXd tar_position = op2_link_data_[idx[end]]->position_; Eigen::MatrixXd jacobian_com = Eigen::MatrixXd::Zero(6, idx_size); for (int id = 0; id < idx_size; id++) { int curr_id = idx[id]; double mass = calcTotalMass(curr_id); Eigen::MatrixXd og = calcMC(curr_id) / mass - op2_link_data_[curr_id]->position_; Eigen::MatrixXd tar_orientation = op2_link_data_[curr_id]->orientation_ * op2_link_data_[curr_id]->joint_axis_; jacobian_com.block(0, id, 3, 1) = robotis_framework::calcCross(tar_orientation, og); jacobian_com.block(3, id, 3, 1) = tar_orientation; } return jacobian_com; } Eigen::MatrixXd OP2KinematicsDynamics::calcVWerr(Eigen::MatrixXd tar_position, Eigen::MatrixXd curr_position, Eigen::MatrixXd tar_orientation, Eigen::MatrixXd curr_orientation) { Eigen::MatrixXd pos_err = tar_position - curr_position; Eigen::MatrixXd ori_err = curr_orientation.transpose() * tar_orientation; Eigen::MatrixXd ori_err_dash = curr_orientation * robotis_framework::convertRotToOmega(ori_err); Eigen::MatrixXd err = Eigen::MatrixXd::Zero(6, 1); err.block<3, 1>(0, 0) = pos_err; err.block<3, 1>(3, 0) = ori_err_dash; return err; } bool OP2KinematicsDynamics::calcInverseKinematics(int to, Eigen::MatrixXd tar_position, Eigen::MatrixXd tar_orientation, int max_iter, double ik_err) { bool ik_success = false; bool limit_success = false; // calcForwardKinematics(0); std::vector idx = findRoute(to); for (int iter = 0; iter < max_iter; iter++) { Eigen::MatrixXd jacobian = calcJacobian(idx); Eigen::MatrixXd curr_position = op2_link_data_[to]->position_; Eigen::MatrixXd curr_orientation = op2_link_data_[to]->orientation_; Eigen::MatrixXd err = calcVWerr(tar_position, curr_position, tar_orientation, curr_orientation); if (err.norm() < ik_err) { ik_success = true; break; } else ik_success = false; Eigen::MatrixXd jacobian_trans = jacobian * jacobian.transpose(); Eigen::MatrixXd jacobian_inverse = jacobian.transpose() * jacobian_trans.inverse(); Eigen::MatrixXd delta_angle = jacobian_inverse * err; for (int id = 0; id < idx.size(); id++) { int joint_num = idx[id]; op2_link_data_[joint_num]->joint_angle_ += delta_angle.coeff(id); } calcForwardKinematics(0); } for (int id = 0; id < idx.size(); id++) { int joint_num = idx[id]; if (op2_link_data_[joint_num]->joint_angle_ >= op2_link_data_[joint_num]->joint_limit_max_) { limit_success = false; break; } else if (op2_link_data_[joint_num]->joint_angle_ <= op2_link_data_[joint_num]->joint_limit_min_) { limit_success = false; break; } else limit_success = true; } if (ik_success == true && limit_success == true) return true; else return false; } bool OP2KinematicsDynamics::calcInverseKinematics(int from, int to, Eigen::MatrixXd tar_position, Eigen::MatrixXd tar_orientation, int max_iter, double ik_err) { bool ik_success = false; bool limit_success = false; // calcForwardKinematics(0); std::vector idx = findRoute(from, to); for (int iter = 0; iter < max_iter; iter++) { Eigen::MatrixXd jacobian = calcJacobian(idx); Eigen::MatrixXd curr_position = op2_link_data_[to]->position_; Eigen::MatrixXd curr_orientation = op2_link_data_[to]->orientation_; Eigen::MatrixXd err = calcVWerr(tar_position, curr_position, tar_orientation, curr_orientation); if (err.norm() < ik_err) { ik_success = true; break; } else ik_success = false; Eigen::MatrixXd jacobian_trans = jacobian * jacobian.transpose(); Eigen::MatrixXd jacobian_inv = jacobian.transpose() * jacobian_trans.inverse(); Eigen::MatrixXd delta_angle = jacobian_inv * err; for (int id = 0; id < idx.size(); id++) { int joint_num = idx[id]; op2_link_data_[joint_num]->joint_angle_ += delta_angle.coeff(id); } calcForwardKinematics(0); } for (int id = 0; id < idx.size(); id++) { int joint_num = idx[id]; if (op2_link_data_[joint_num]->joint_angle_ >= op2_link_data_[joint_num]->joint_limit_max_) { limit_success = false; break; } else if (op2_link_data_[joint_num]->joint_angle_ <= op2_link_data_[joint_num]->joint_limit_min_) { limit_success = false; break; } else limit_success = true; } if (ik_success == true && limit_success == true) return true; else return false; } bool OP2KinematicsDynamics::calcInverseKinematics(int to, Eigen::MatrixXd tar_position, Eigen::MatrixXd tar_orientation, int max_iter, double ik_err, Eigen::MatrixXd weight) { bool ik_success = false; bool limit_success = false; // calcForwardKinematics(0); std::vector idx = findRoute(to); /* weight */ Eigen::MatrixXd weight_matrix = Eigen::MatrixXd::Identity(idx.size(), idx.size()); for (int ix = 0; ix < idx.size(); ix++) weight_matrix.coeffRef(ix, ix) = weight.coeff(idx[ix], 0); /* damping */ Eigen::MatrixXd eval = Eigen::MatrixXd::Zero(6, 6); double p_damping = 1e-5; double R_damping = 1e-5; for (int ix = 0; ix < 3; ix++) { eval.coeffRef(ix, ix) = p_damping; eval.coeffRef(ix + 3, ix + 3) = R_damping; } /* ik */ for (int iter = 0; iter < max_iter; iter++) { Eigen::MatrixXd jacobian = calcJacobian(idx); Eigen::MatrixXd curr_position = op2_link_data_[to]->position_; Eigen::MatrixXd curr_orientation = op2_link_data_[to]->orientation_; Eigen::MatrixXd err = calcVWerr(tar_position, curr_position, tar_orientation, curr_orientation); if (err.norm() < ik_err) { ik_success = true; break; } else ik_success = false; Eigen::MatrixXd jacobian_trans = (jacobian * weight_matrix * jacobian.transpose() + eval); Eigen::MatrixXd jacobian_inv = weight_matrix * jacobian.transpose() * jacobian_trans.inverse(); Eigen::MatrixXd delta_angle = jacobian_inv * err; for (int id = 0; id < idx.size(); id++) { int joint_id = idx[id]; op2_link_data_[joint_id]->joint_angle_ += delta_angle.coeff(id); } calcForwardKinematics(0); } /* check joint limit */ for (int id = 0; id < idx.size(); id++) { int joint_num = idx[id]; if (op2_link_data_[joint_num]->joint_angle_ >= op2_link_data_[joint_num]->joint_limit_max_) { limit_success = false; break; } else if (op2_link_data_[joint_num]->joint_angle_ <= op2_link_data_[joint_num]->joint_limit_min_) { limit_success = false; break; } else limit_success = true; } if (ik_success == true && limit_success == true) return true; else return false; } bool OP2KinematicsDynamics::calcInverseKinematics(int from, int to, Eigen::MatrixXd tar_position, Eigen::MatrixXd tar_orientation, int max_iter, double ik_err, Eigen::MatrixXd weight) { bool ik_success = false; bool limit_success = false; // calcForwardKinematics(0); std::vector idx = findRoute(from, to); /* weight */ Eigen::MatrixXd weight_matrix = Eigen::MatrixXd::Identity(idx.size(), idx.size()); for (int ix = 0; ix < idx.size(); ix++) weight_matrix.coeffRef(ix, ix) = weight.coeff(idx[ix], 0); /* damping */ Eigen::MatrixXd eval = Eigen::MatrixXd::Zero(6, 6); double p_damping = 1e-5; double R_damping = 1e-5; for (int ix = 0; ix < 3; ix++) { eval.coeffRef(ix, ix) = p_damping; eval.coeffRef(ix + 3, ix + 3) = R_damping; } /* ik */ for (int iter = 0; iter < max_iter; iter++) { Eigen::MatrixXd jacobian = calcJacobian(idx); Eigen::MatrixXd curr_position = op2_link_data_[to]->position_; Eigen::MatrixXd curr_orientation = op2_link_data_[to]->orientation_; Eigen::MatrixXd err = calcVWerr(tar_position, curr_position, tar_orientation, curr_orientation); if (err.norm() < ik_err) { ik_success = true; break; } else ik_success = false; Eigen::MatrixXd jacobian_trans = (jacobian * weight_matrix * jacobian.transpose() + eval); Eigen::MatrixXd jacobian_inv = weight_matrix * jacobian.transpose() * jacobian_trans.inverse(); Eigen::MatrixXd delta_angle = jacobian_inv * err; for (int id = 0; id < idx.size(); id++) { int joint_id = idx[id]; op2_link_data_[joint_id]->joint_angle_ += delta_angle.coeff(id); } calcForwardKinematics(0); } /* check joint limit */ for (int id = 0; id < idx.size(); id++) { int _joint_num = idx[id]; if (op2_link_data_[_joint_num]->joint_angle_ >= op2_link_data_[_joint_num]->joint_limit_max_) { limit_success = false; break; } else if (op2_link_data_[_joint_num]->joint_angle_ <= op2_link_data_[_joint_num]->joint_limit_min_) { limit_success = false; break; } else limit_success = true; } if (ik_success == true && limit_success == true) return true; else return false; } bool OP2KinematicsDynamics::calcInverseKinematicsForLeg(double *out, double x, double y, double z, double roll, double pitch, double yaw) { Eigen::Matrix4d trans_ad, trans_da, trans_cd, trans_dc, trans_ac; Eigen::Vector3d vec; bool invertible; double rac, arc_cos, arc_tan, k, l, m, n, s, c, theta; double thigh_length = thigh_length_m_; double calf_length = calf_length_m_; double ankle_length = ankle_length_m_; trans_ad = robotis_framework::getTransformationXYZRPY(x, y, z, roll, pitch, yaw); vec.coeffRef(0) = trans_ad.coeff(0, 3) + trans_ad.coeff(0, 2) * ankle_length; vec.coeffRef(1) = trans_ad.coeff(1, 3) + trans_ad.coeff(1, 2) * ankle_length; vec.coeffRef(2) = trans_ad.coeff(2, 3) + trans_ad.coeff(2, 2) * ankle_length; // Get Knee rac = vec.norm(); arc_cos = acos( (rac * rac - thigh_length * thigh_length - calf_length * calf_length) / (2.0 * thigh_length * calf_length)); if (std::isnan(arc_cos) == 1) return false; *(out + 3) = arc_cos; // Get Ankle Roll trans_ad.computeInverseWithCheck(trans_da, invertible); if (invertible == false) return false; k = sqrt(trans_da.coeff(1, 3) * trans_da.coeff(1, 3) + trans_da.coeff(2, 3) * trans_da.coeff(2, 3)); l = sqrt( trans_da.coeff(1, 3) * trans_da.coeff(1, 3) + (trans_da.coeff(2, 3) - ankle_length) * (trans_da.coeff(2, 3) - ankle_length)); m = (k * k - l * l - ankle_length * ankle_length) / (2.0 * l * ankle_length); if (m > 1.0) m = 1.0; else if (m < -1.0) m = -1.0; arc_cos = acos(m); if (std::isnan(arc_cos) == 1) return false; if (trans_da.coeff(1, 3) < 0.0) *(out + 5) = -arc_cos; else *(out + 5) = arc_cos; // Get Hip Yaw trans_cd = robotis_framework::getTransformationXYZRPY(0, 0, -ankle_length, *(out + 5), 0, 0); trans_cd.computeInverseWithCheck(trans_dc, invertible); if (invertible == false) return false; trans_ac = trans_ad * trans_dc; arc_tan = atan2(-trans_ac.coeff(0, 1), trans_ac.coeff(1, 1)); if (std::isinf(arc_tan) != 0) return false; *(out) = arc_tan; // Get Hip Roll arc_tan = atan2(trans_ac.coeff(2, 1), -trans_ac.coeff(0, 1) * sin(*(out)) + trans_ac.coeff(1, 1) * cos(*(out))); if (std::isinf(arc_tan) != 0) return false; *(out + 1) = arc_tan; // Get Hip Pitch and Ankle Pitch arc_tan = atan2(trans_ac.coeff(0, 2) * cos(*(out)) + trans_ac.coeff(1, 2) * sin(*(out)), trans_ac.coeff(0, 0) * cos(*(out)) + trans_ac.coeff(1, 0) * sin(*(out))); if (std::isinf(arc_tan) == 1) return false; theta = arc_tan; k = sin(*(out + 3)) * calf_length; l = -thigh_length - cos(*(out + 3)) * calf_length; m = cos(*(out)) * vec.coeff(0) + sin(*(out)) * vec.coeff(1); n = cos(*(out + 1)) * vec.coeff(2) + sin(*(out)) * sin(*(out + 1)) * vec.coeff(0) - cos(*(out)) * sin(*(out + 1)) * vec.coeff(1); s = (k * n + l * m) / (k * k + l * l); c = (n - k * s) / l; arc_tan = atan2(s, c); if (std::isinf(arc_tan) == 1) return false; *(out + 2) = arc_tan; *(out + 4) = theta - *(out + 3) - *(out + 2); return true; } bool OP2KinematicsDynamics::calcInverseKinematicsForRightLeg(double *out, double x, double y, double z, double roll, double pitch, double yaw) { if (calcInverseKinematicsForLeg(out, x, y, z, roll, pitch, yaw) == true) { for(int ix = 0 ; ix < 6; ix++) out[ix] *= getJointDirection(ID_R_LEG_START + 2 * ix); return true; } else return false; } bool OP2KinematicsDynamics::calcInverseKinematicsForLeftLeg(double *out, double x, double y, double z, double roll, double pitch, double yaw) { if (calcInverseKinematicsForLeg(out, x, y, z, roll, pitch, yaw) == true) { for(int ix = 0 ; ix < 6; ix++) out[ix] *= getJointDirection(ID_L_LEG_START + 2 * ix); return true; } else return false; } LinkData *OP2KinematicsDynamics::getLinkData(const std::string link_name) { for (int ix = 0; ix <= ALL_JOINT_ID; ix++) { if (op2_link_data_[ix]->name_ == link_name) { return op2_link_data_[ix]; } } return NULL; } LinkData *OP2KinematicsDynamics::getLinkData(const int link_id) { if (op2_link_data_[link_id] != NULL) { return op2_link_data_[link_id]; } return NULL; } Eigen::MatrixXd OP2KinematicsDynamics::getJointAxis(const std::string link_name) { Eigen::MatrixXd joint_axis; LinkData *link_data = getLinkData(link_name); if (link_data != NULL) { joint_axis = link_data->joint_axis_; } return joint_axis; } double OP2KinematicsDynamics::getJointDirection(const std::string link_name) { double joint_direction = 0.0; LinkData *link_data = getLinkData(link_name); if (link_data != NULL) { joint_direction = link_data->joint_axis_.coeff(0, 0) + link_data->joint_axis_.coeff(1, 0) + link_data->joint_axis_.coeff(2, 0); } return joint_direction; } double OP2KinematicsDynamics::getJointDirection(const int link_id) { double joint_direction = 0.0; LinkData *link_data = getLinkData(link_id); if (link_data != NULL) { joint_direction = link_data->joint_axis_.coeff(0, 0) + link_data->joint_axis_.coeff(1, 0) + link_data->joint_axis_.coeff(2, 0); } return joint_direction; } Eigen::MatrixXd OP2KinematicsDynamics::calcPreviewParam(double preview_time, double control_cycle, double lipm_height, Eigen::MatrixXd K, Eigen::MatrixXd P) { double t = control_cycle; double preview_size_ = round(preview_time/control_cycle) + 1; Eigen::MatrixXd A_; A_.resize(3,3); A_ << 1, t, t*t/2.0, 0, 1, t, 0, 0, 1; Eigen::MatrixXd b_; b_.resize(3,1); b_ << t*t*t/6.0, t*t/2.0, t; Eigen::MatrixXd c_; c_.resize(1,3); c_ << 1, 0, -lipm_height/9.81; Eigen::MatrixXd tempA = Eigen::MatrixXd::Zero(4,4); Eigen::MatrixXd tempb = Eigen::MatrixXd::Zero(4,1); Eigen::MatrixXd tempc = Eigen::MatrixXd::Zero(1,4); tempA.coeffRef(0,0) = 1; tempA.block<1,3>(0,1) = c_*A_; tempA.block<3,3>(1,1) = A_; tempb.coeffRef(0,0) = (c_*b_).coeff(0,0); tempb.block<3,1>(1,0) = b_; tempc.coeffRef(0,0) = 1; double R = 1e-6; double Q_e = 1; double Q_x = 0; Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(4,4); Q.coeffRef(0,0) = Q_e; Q.coeffRef(1,1) = Q_e; Q.coeffRef(2,2) = Q_e; Q.coeffRef(3,3) = Q_x; Eigen::MatrixXd f_; f_.resize(1, preview_size_); Eigen::MatrixXd mat_R = Eigen::MatrixXd::Zero(1,1); mat_R.coeffRef(0,0) = R; Eigen::MatrixXd tempCoeff1 = mat_R + ((tempb.transpose() * P) * tempb); Eigen::MatrixXd tempCoeff1_inv = tempCoeff1.inverse(); Eigen::MatrixXd tempCoeff2 = tempb.transpose(); Eigen::MatrixXd tempCoeff3 = Eigen::MatrixXd::Identity(4,4); Eigen::MatrixXd tempCoeff4 = P*tempc.transpose(); f_.block<1,1>(0,0) = ((tempCoeff1_inv*tempCoeff2)* tempCoeff3) * tempCoeff4; for(int i = 1; i < preview_size_; i++) { tempCoeff3 = tempCoeff3*((tempA - tempb*K).transpose()); f_.block<1,1>(0,i) = ((tempCoeff1_inv*tempCoeff2)* tempCoeff3) * tempCoeff4; } return f_; } } ",16286,True,2860.4377739664255,median "/** * DeepDetect * Copyright (c) 2019-2020 Jolibrain * Author: Louis Jean * Guillaume Infantes * * This file is part of deepdetect. * * deepdetect 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. * * deepdetect 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 deepdetect. If not, see . */ #include ""torchlib.h"" #if !defined(CPU_ONLY) #include #endif #include ""outputconnectorstrategy.h"" #include ""generators/net_caffe.h"" #include ""generators/net_caffe_recurrent.h"" #include #include #include #include ""native/native.h"" #include ""torchsolver.h"" #include ""torchloss.h"" #include ""torchutils.h"" #include ""dto/mllib.hpp"" #include ""utils/bbox.hpp"" using namespace torch; namespace dd { template TorchLib::TorchLib(const TorchModel &tmodel) : MLLib( tmodel) { this->_libname = ""torch""; } template TorchLib::TorchLib(TorchLib &&tl) noexcept : MLLib( std::move(tl)) { this->_libname = ""torch""; _module = std::move(tl._module); _template = tl._template; _nclasses = tl._nclasses; _main_device = tl._main_device; _devices = tl._devices; _masked_lm = tl._masked_lm; _seq_training = tl._seq_training; _finetuning = tl._finetuning; _best_metrics = tl._best_metrics; _best_metric_values = tl._best_metric_values; _classification = tl._classification; _regression = tl._regression; _timeserie = tl._timeserie; _bbox = tl._bbox; _segmentation = tl._segmentation; _loss = tl._loss; _template_params = tl._template_params; _dtype = tl._dtype; } template TorchLib::~TorchLib() { _module.free(); torch_utils::empty_cuda_cache(); } template double TorchLib::unscale(double val, unsigned int k, const TInputConnectorStrategy &inputc) { (void)inputc; (void)k; // unscaling is input connector specific return val; } // full template specialization template <> double TorchLib::unscale( double val, unsigned int k, const CSVTSTorchInputFileConn &inputc) { if (!inputc._scale) return val; if (inputc._scale_type == MINMAX && (inputc._min_vals.empty() || inputc._max_vals.empty())) { this->_logger->info(""not unscaling output because no bounds "" ""data found""); return val; } else if (inputc._scale_type == ZNORM && (inputc._mean_vals.empty() || inputc._variance_vals.empty())) { this->_logger->info(""not unscaling output because no bounds "" ""data found""); return val; } else { if (!inputc._dont_scale_labels) { if (inputc._scale_type == MINMAX) { double max, min; if (inputc._label_pos.size() > 0) // labels case { max = inputc._max_vals[inputc._label_pos[k]]; min = inputc._min_vals[inputc._label_pos[k]]; } else // forecast case { max = inputc._max_vals[k]; min = inputc._min_vals[k]; } if (inputc._scale_between_minus_half_and_half) val += 0.5; val = val * (max - min) + min; } else if (inputc._scale_type == ZNORM) { double mean, variance; if (inputc._label_pos.size() > 0) // labels case { mean = inputc._mean_vals[inputc._label_pos[k]]; variance = inputc._variance_vals[inputc._label_pos[k]]; } else // forecast case { mean = inputc._mean_vals[k]; variance = inputc._variance_vals[k]; } val = val * (sqrt(variance)) + mean; } else throw MLLibInternalException(""unknwon scale type""); } return val; } } /*- from mllib -*/ template void TorchLib::init_mllib(const APIData &lib_ad) { // Get parameters auto mllib_dto = lib_ad.createSharedDTO(); if (mllib_dto->from_repository != nullptr) { this->_mlmodel.copy_to_target(mllib_dto->from_repository->std_str(), this->_mlmodel._repo, this->_logger); this->_mlmodel.read_from_repository(this->_logger); } _template = mllib_dto->model_template->std_str(); if (mllib_dto->gpu && !torch::cuda::is_available()) { throw MLLibBadParamException( ""GPU is not available, service could not be created""); } std::vector gpuids = mllib_dto->gpuid->_ids; if (mllib_dto->nclasses != 0) { _nclasses = mllib_dto->nclasses; } else if (mllib_dto->ntargets != 0) { _nclasses = mllib_dto->ntargets; } std::string self_supervised = mllib_dto->self_supervised->std_str(); int embedding_size = mllib_dto->embedding_size; bool freeze_traced = mllib_dto->freeze_traced; _finetuning = mllib_dto->finetuning; _loss = mllib_dto->loss->std_str(); auto template_params_dto = mllib_dto->template_params; if (template_params_dto != nullptr) { _template_params = lib_ad.getobj(""template_params""); if (mllib_dto->nclasses != 0) _template_params.add(""nclasses"", static_cast(mllib_dto->nclasses)); } std::string dt = mllib_dto->datatype->std_str(); if (dt == ""fp32"") { _dtype = torch::kFloat32; this->_logger->info(""will predict in FP32""); } else if (dt == ""fp16"") { _dtype = torch::kFloat16; this->_logger->info(""will predict in FP16""); } else if (dt == ""fp64"") { _dtype = torch::kFloat64; this->_logger->info(""will predict in FP64""); } else throw MLLibBadParamException(""unknown datatype "" + dt); // Find GPU id if (mllib_dto->gpu != true) { _devices = { torch::Device(DeviceType::CPU) }; } else { // if gpuids = -1, we use all gpus if (gpuids.size() == 1 && gpuids[0] == -1) { gpuids.resize(torch::cuda::device_count()); std::iota(gpuids.begin(), gpuids.end(), 0); } if (gpuids.empty()) gpuids.push_back(0); for (int gpuid : gpuids) _devices.push_back(torch::Device(DeviceType::CUDA, gpuid)); if (_devices.size() > 1) { std::string devices_str = std::to_string(gpuids[0]); for (size_t i = 1; i < _devices.size(); ++i) devices_str += "","" + std::to_string(gpuids[i]); this->_logger->info(""Running on multiple devices: "" + devices_str); } } _main_device = _devices[0]; // Set model type if (mllib_dto->segmentation) { _segmentation = true; } else if (mllib_dto->nclasses != 0) { _classification = true; } else if (mllib_dto->ntargets != 0) { _regression = true; } if (_template == ""bert"") { if (!self_supervised.empty()) { if (self_supervised != ""mask"") { throw MLLibBadParamException( ""Bert does not support self_supervised type: "" + self_supervised); } this->_logger->info(""Masked Language model""); _masked_lm = true; _seq_training = true; } else if (!_classification) { throw MLLibBadParamException( ""BERT only supports self-supervised or classification""); } } else if (_template == ""gpt2"") { _seq_training = true; } else if (_template == ""fasterrcnn"" || _template == ""retinanet"" || _template == ""detr"") { _bbox = true; _classification = false; } else if (_template.find(""recurrent"") != std::string::npos || NativeFactory::is_timeserie(_template)) { _timeserie = true; } if (!_regression && !_timeserie && !_bbox && !_segmentation && self_supervised.empty()) _classification = true; // classification is default // Set mltype if (_bbox) this->_mltype = ""detection""; else if (_timeserie) this->_mltype = ""timeserie""; else if (_regression) this->_mltype = ""regression""; else if (_classification) this->_mltype = ""classification""; else if (_segmentation) this->_mltype = ""segmentation""; // Create the model _module._device = _main_device; _module._logger = this->_logger; _module._finetuning = _finetuning; if (_template == ""recurrent"") { // call caffe net generator before everything else std::string dest_net = this->_mlmodel._repo + '/' + _template + "".prototxt""; if (!fileops::file_exists(dest_net)) { caffe::NetParameter net_param; configure_recurrent_template(lib_ad, this->_inputc, net_param, this->_logger, true); torch_utils::torch_write_proto_to_text_file(net_param, dest_net); } else { this->_logger->info(""prototxt net definition already present in "" ""repo : using old file""); } this->_mlmodel._proto = dest_net; } bool model_not_found = this->_mlmodel._traced.empty() && this->_mlmodel._proto.empty() && !NativeFactory::valid_template_def(_template); if (model_not_found) throw MLLibInternalException(""Use of libtorch backend needs either: "" ""traced net, protofile or native template""); bool multiple_models_found = ((!this->_mlmodel._traced.empty() || !this->_mlmodel._proto.empty()) + NativeFactory::valid_template_def(_template)) > 1; if (multiple_models_found) { this->_logger->error(""traced: {}, proto: {}, template: {}"", this->_mlmodel._traced, this->_mlmodel._proto, _template); throw MLLibInternalException( ""Only one of these must be provided: traced net, protofile or "" ""native template""); } // FIXME(louis): out of if(bert) because we allow not to specify template // at predict. Should we change this? this->_inputc._input_format = ""bert""; if (_template == ""bert"") { // No allocation, use traced model in repo if (_classification) { _module._linear = nn::Linear(embedding_size, _nclasses); _module._linear->to(_main_device); _module._hidden_states = true; _module._linear_in = 1; } } else if (_template == ""gpt2"") { // No allocation, use traced model in repo this->_inputc._input_format = ""gpt2""; } // TorchVision detection models else if (_template == ""fasterrcnn"" || _template == ""retinanet"") { // torchvision models output is a tuple (Loss, Predictions) _module._loss_id = 0; _module._linear_in = 1; } else if (_template == ""detr"") { } else if (!_template.empty()) { bool model_allocated_at_train = NativeFactory::is_timeserie(_template) || _template == ""recurrent""; if (model_allocated_at_train) this->_logger->info(""Model allocated during training""); else if (NativeFactory::valid_template_def(_template)) { _module.create_native_template( _template, _template_params, this->_inputc, this->_mlmodel, _main_device); // XXX: greyscale images are not supported by torchvision models if (std::is_same::value && !NativeFactory::template_supports_bw(_template)) { dynamic_cast(&this->_inputc) ->_supports_bw = false; } } else throw MLLibBadParamException(""invalid torch model template "" + _template); } if (_classification || _regression || _segmentation) { _module._nclasses = _nclasses; if (_finetuning && !_module._native) { _module._require_linear_layer = true; this->_logger->info(""Add linear layer on top of the traced model""); } } // Load weights _module.load(this->_mlmodel); _module.freeze_traced(freeze_traced); _best_metrics = { ""map"", ""meaniou"", ""mlacc"", ""delta_score_0.1"", ""bacc"", ""f1"", ""net_meas"", ""acc"", ""L1_mean_error"", ""eucll"" }; _best_metric_values.resize(1, std::numeric_limits::infinity()); } template void TorchLib::clear_mllib(__attribute__((unused)) const APIData &ad) { std::vector extensions{ "".json"", "".pt"", "".ptw"" }; fileops::remove_directory_files(this->_mlmodel._repo, extensions); this->_logger->info(""Torchlib service cleared""); } template bool TorchLib::is_better(double v1, double v2, std::string metric_name) { if (metric_name == ""eucll"" || metric_name == ""delta_score_0.1"" || metric_name == ""L1_mean_error"") return (v2 > v1); return (v1 > v2); } template int64_t TorchLib::save_if_best(const size_t test_id, APIData &meas_out, int64_t elapsed_it, TorchSolver &tsolver, std::vector best_iteration_numbers) { double cur_meas = std::numeric_limits::infinity(); std::string meas; for (auto m : _best_metrics) { if (meas_out.has(m)) { cur_meas = meas_out.get(m).get(); meas = m; break; } } if (cur_meas == std::numeric_limits::infinity()) { // could not find value for measuring best this->_logger->info( ""could not find any value for measuring best model""); return false; } if (_best_metric_values[test_id] == std::numeric_limits::infinity() || is_better(cur_meas, _best_metric_values[test_id], meas)) { if (best_iteration_numbers[test_id] != -1 && dd_utils::unique(best_iteration_numbers[test_id], best_iteration_numbers)) { remove_model(best_iteration_numbers[test_id]); } _best_metric_values[test_id] = cur_meas; this->snapshot(elapsed_it, tsolver); try { std::ofstream bestfile; std::string bestfilename = this->_mlmodel._repo + fileops::insert_suffix( ""_test_"" + std::to_string(test_id), this->_mlmodel._best_model_filename); bestfile.open(bestfilename, std::ios::out); bestfile << ""iteration:"" << elapsed_it << std::endl; bestfile << meas << "":"" << cur_meas << std::endl; bestfile << ""test_name: ""; if (meas_out.has(""test_name"")) bestfile << meas_out.get(""test_name"").get(); else bestfile << ""noname_"" + std::to_string(test_id); bestfile << std::endl; bestfile.close(); if (test_id == 0) fileops::copy_file(this->_mlmodel._repo + fileops::insert_suffix( ""_test_"" + std::to_string(test_id), this->_mlmodel._best_model_filename), this->_mlmodel._repo + this->_mlmodel._best_model_filename); } catch (std::exception &e) { this->_logger->error(""could not write best model file""); } return elapsed_it; } return best_iteration_numbers[test_id]; } template void TorchLib::remove_model(int64_t elapsed_it) { this->_logger->info(""Deleting superseeded model {} "", elapsed_it); std::remove((this->_mlmodel._repo + ""/solver-"" + std::to_string(elapsed_it) + "".pt"") .c_str()); std::remove((this->_mlmodel._repo + ""/checkpoint-"" + std::to_string(elapsed_it) + "".pt"") .c_str()); std::remove((this->_mlmodel._repo + ""/checkpoint-"" + std::to_string(elapsed_it) + "".npt"") .c_str()); std::remove((this->_mlmodel._repo + ""/checkpoint-"" + std::to_string(elapsed_it) + "".ptw"") .c_str()); } template void TorchLib::snapshot(int64_t elapsed_it, TorchSolver &tsolver) { this->_logger->info(""Saving checkpoint after {} iterations"", elapsed_it); // solver is allowed to modify net during eval()/train() => do this call // before saving net itself tsolver.eval(); this->_module.save_checkpoint(this->_mlmodel, std::to_string(elapsed_it)); tsolver.save(this->_mlmodel._repo + ""/solver-"" + std::to_string(elapsed_it) + "".pt""); tsolver.train(); } template int TorchLib::train(const APIData &ad, APIData &out) { using namespace std::chrono; this->_tjob_running.store(true); TInputConnectorStrategy inputc(this->_inputc); inputc._train = true; APIData ad_input = ad.getobj(""parameters"").getobj(""input""); if (ad_input.has(""shuffle"")) inputc._dataset.set_shuffle(ad_input.get(""shuffle"").get()); inputc._dataset._classification = inputc._test_datasets._classification = _classification; try { inputc.transform(ad); _module.post_transform_train( _template, _template_params, inputc, this->_mlmodel, _main_device); } catch (...) { throw; } // TODO: set inputc dataset data augmentation options APIData ad_mllib = ad.getobj(""parameters"").getobj(""mllib""); bool has_data_augmentation = ad_mllib.has(""mirror"") || ad_mllib.has(""rotate"") || ad_mllib.has(""crop_size"") || ad_mllib.has(""cutout""); if (has_data_augmentation) { bool has_mirror = ad_mllib.has(""mirror"") && ad_mllib.get(""mirror"").get(); this->_logger->info(""mirror: {}"", has_mirror); bool has_rotate = ad_mllib.has(""rotate"") && ad_mllib.get(""rotate"").get(); this->_logger->info(""rotate: {}"", has_rotate); CropParams crop_params; if (ad_mllib.has(""crop_size"")) { int crop_size = ad_mllib.get(""crop_size"").get(); crop_params = CropParams(crop_size, inputc.width(), inputc.height()); this->_logger->info(""crop_size : {}"", crop_size); } CutoutParams cutout_params; if (ad_mllib.has(""cutout"")) { float cutout = ad_mllib.get(""cutout"").get(); cutout_params = CutoutParams(cutout, inputc.width(), inputc.height()); this->_logger->info(""cutout: {}"", cutout); } GeometryParams geometry_params; APIData ad_geometry = ad_mllib.getobj(""geometry""); if (!ad_geometry.empty()) { geometry_params._prob = ad_geometry.get(""prob"").get(); this->_logger->info(""geometry: {}"", geometry_params._prob); if (ad_geometry.has(""persp_vertical"")) geometry_params._geometry_persp_vertical = ad_geometry.get(""persp_vertical"").get(); if (ad_geometry.has(""persp_horizontal"")) geometry_params._geometry_persp_horizontal = ad_geometry.get(""persp_horizontal"").get(); if (ad_geometry.has(""zoom_out"")) geometry_params._geometry_zoom_out = ad_geometry.get(""zoom_out"").get(); if (ad_geometry.has(""zoom_in"")) geometry_params._geometry_zoom_in = ad_geometry.get(""zoom_in"").get(); if (ad_geometry.has(""pad_mode"")) geometry_params._geometry_pad_mode = ad_geometry.get(""pad_mode"").get(); } inputc._dataset._img_rand_aug_cv = TorchImgRandAugCV(has_mirror, has_rotate, crop_params, cutout_params, geometry_params); } int dataloader_threads = 1; if (ad_mllib.has(""dataloader_threads"")) dataloader_threads = ad_mllib.get(""dataloader_threads"").get(); Tensor class_weights = {}; if (ad_mllib.has(""class_weights"")) { std::vector cwv = ad_mllib.get(""class_weights"").get>(); if (cwv.size() != _nclasses) { this->_logger->error(""class weights given, but number of "" ""weights {} do not match "" ""number of classes {}, ignoring"", cwv.size(), _nclasses); } else { this->_logger->info(""using class weights""); auto options = torch::TensorOptions().dtype(torch::kFloat64); class_weights = torch::from_blob(cwv.data(), { _nclasses }, options) .to(torch::kFloat32) .to(_main_device); } } // solver params int64_t iterations = 1; int64_t batch_size = 1; int64_t iter_size = 1; int64_t test_batch_size = 1; int64_t test_interval = 1; int64_t save_period = 0; TorchLoss tloss(_loss, _module.has_model_loss(), _seq_training, _timeserie, _regression, _classification, class_weights, _module, this->_logger); TorchSolver tsolver(_module, tloss, this->_logger); // logging parameters int64_t log_batch_period = 20; if (ad_mllib.has(""template_params"")) _template_params = ad_mllib; if (ad_mllib.has(""solver"")) { APIData ad_solver = ad_mllib.getobj(""solver""); tsolver.configure(ad_solver); if (ad_solver.has(""iterations"")) iterations = ad_solver.get(""iterations"").get(); if (ad_solver.has(""test_interval"")) test_interval = ad_solver.get(""test_interval"").get(); if (ad_solver.has(""iter_size"")) iter_size = ad_solver.get(""iter_size"").get(); if (ad_solver.has(""snapshot"")) save_period = ad_solver.get(""snapshot"").get(); } if (ad_mllib.has(""net"")) { APIData ad_net = ad_mllib.getobj(""net""); if (ad_net.has(""batch_size"")) batch_size = ad_net.get(""batch_size"").get(); if (ad_net.has(""test_batch_size"")) test_batch_size = ad_net.get(""test_batch_size"").get(); } bool retain_graph = ad_mllib.has(""retain_graph"") ? ad_mllib.get(""retain_graph"").get() : false; if (iter_size <= 0) iter_size = 1; size_t gpu_count = _devices.size(); // create dataset for evaluation during training TorchMultipleDataset &eval_dataset = inputc._test_datasets; if (eval_dataset.size() == 0) throw MLLibBadParamException(""empty test dataset""); // create solver std::vector best_iteration_numbers(eval_dataset.size(), -1); _best_metric_values.resize(eval_dataset.size(), std::numeric_limits::infinity()); int it = tsolver.resume(ad_mllib, this->_mlmodel, _main_device, _best_metric_values, best_iteration_numbers, eval_dataset.names()); bool skip_training = it >= iterations; if (skip_training) { this->_logger->info( ""Model was trained for {} iterations, skipping training"", it); } else { this->_logger->info(""Training for {} iterations"", iterations - it); } // [multigpu] initialize all module typedef struct { std::shared_ptr module; std::shared_ptr loss; } Rank; std::vector ranks; for (size_t i = 0; i < _devices.size(); ++i) { ranks.emplace_back(); auto &r = ranks.back(); if (_devices[i] != _main_device) { r.module = _module.clone(_devices[i]); r.module->train(); r.loss = std::make_shared( _loss, r.module->has_model_loss(), _seq_training, _timeserie, _regression, _classification, class_weights, *r.module, this->_logger); } } _module.train(); // create dataloader inputc._dataset.reset(); size_t dataloader_max_jobs = 2 * iter_size * gpu_count; this->_logger->info(""Init dataloader with {} threads and {} prefetch size"", dataloader_threads, dataloader_max_jobs); auto dataloader = torch::data::make_data_loader( inputc._dataset, data::DataLoaderOptions(batch_size) .workers(dataloader_threads) .max_jobs(dataloader_max_jobs)); int batch_id = 0; double last_it_time = 0; double last_test_time = 0; double train_loss = 0; auto data_it = dataloader->begin(); if (data_it == dataloader->end()) { throw MLLibBadParamException(""No data found in training dataset""); } // `it` is the iteration count (not epoch) while (it < iterations) { if (!this->_tjob_running.load()) break; auto tstart = steady_clock::now(); // load batches std::vector batches; batches.reserve(_devices.size()); for (size_t rank = 0; rank < _devices.size(); ++rank) { batches.push_back(*data_it); ++data_it; if (data_it == dataloader->end()) { // +1 epoch data_it = dataloader->begin(); } if (_masked_lm) { batches[rank] = inputc.generate_masked_lm_batch(batches[rank]); } } #pragma omp parallel for num_threads(_devices.size()) for (size_t rank = 0; rank < _devices.size(); ++rank) { TorchBatch batch = batches[rank]; torch::Device device = _devices[rank]; TorchModule &rank_module = device == _main_device ? _module : *ranks[rank].module; TorchLoss &rank_tloss = device == _main_device ? tloss : *ranks[rank].loss; // Batch preprocessing std::vector in_vals; for (Tensor tensor : batch.data) { in_vals.push_back(tensor.to(device)); } if (rank_module.has_model_loss()) { // if the model computes the loss then we pass target as input for (Tensor tensor : batch.target) in_vals.push_back(tensor.to(device)); } if (batch.target.size() == 0) { throw MLLibInternalException( ""Batch "" + std::to_string(batch_id) + "": no target""); } Tensor y = batch.target.at(0).to(device); // Prediction Tensor y_pred; try { y_pred = torch_utils::to_tensor_safe( rank_module.forward(in_vals)); } catch (std::exception &e) { this->_logger->error(std::string(""Libtorch error: "") + e.what()); throw MLLibInternalException(std::string(""Libtorch error: "") + e.what()); } // Compute loss Tensor loss = rank_tloss.loss(y_pred, y, in_vals); if (iter_size > 1) loss /= iter_size; if (gpu_count > 1) loss /= static_cast(gpu_count); // Backward loss.backward({}, /*retain_graph=*/c10::optional(retain_graph), /*create_graph=*/false); #pragma omp critical { // Retain loss for statistics double loss_val = loss.item(); train_loss += loss_val; } } // Reduce gradients on device #0 auto params = _module.parameters(); for (size_t j = 0; j < _devices.size(); ++j) { if (_devices[j] == _main_device) continue; auto params_j = ranks[j].module->parameters(); for (size_t pi = 0; pi < params.size(); ++pi) { Tensor &grad = params[pi].mutable_grad(); Tensor gradj = params_j[pi].grad(); grad.add_(gradj.to(_main_device)); } } // End sync gradients // Timing auto tstop = steady_clock::now(); last_it_time += duration_cast(tstop - tstart).count(); if ((batch_id + 1) % iter_size == 0) { if (!this->_tjob_running.load()) { // Interrupt training if the service was deleted break; } tstart = steady_clock::now(); try { tsolver.step(); tsolver.zero_grad(); } catch (std::exception &e) { this->_logger->error(std::string(""Libtorch error: "") + e.what()); throw MLLibInternalException(std::string(""Libtorch error: "") + e.what()); } // Broadcast weights to all for (size_t j = 0; j < _devices.size(); ++j) { if (_devices[j] == _main_device) continue; auto params_j = ranks[j].module->parameters(); for (size_t pi = 0; pi < params.size(); ++pi) { torch::NoGradGuard guard; Tensor weight = params[pi]; params_j[pi].copy_(weight.to(_devices.at(j))); params_j[pi].grad().zero_(); } } tstop = steady_clock::now(); double base_lr = tsolver.base_lr(); this->add_meas(""learning_rate"", base_lr); this->add_meas(""iteration"", it); // without solver time: this->add_meas(""batch_duration_ms"", last_it_time / iter_size); // for backward compatibility: this->add_meas(""iter_time"", last_it_time / iter_size); // with solver time: last_it_time += duration_cast(tstop - tstart).count(); this->add_meas(""iteration_duration_ms"", last_it_time); double remain_time_ms = last_it_time * (iterations - it); if (test_interval > 0) { int past_tests = (it / test_interval); int total_tests = ((iterations - 1) / test_interval) + 1; remain_time_ms += last_test_time * (total_tests - past_tests); } this->add_meas(""remain_time"", remain_time_ms / 1000.0); this->add_meas(""train_loss"", train_loss); this->add_meas_per_iter(""learning_rate"", base_lr); this->add_meas_per_iter(""train_loss"", train_loss); int64_t elapsed_it = it + 1; if (log_batch_period != 0 && elapsed_it % log_batch_period == 0) { this->_logger->info(""Iteration {}/{}: loss is {}"", elapsed_it, iterations, train_loss); } last_it_time = 0; train_loss = 0; if ((elapsed_it % test_interval == 0 && eval_dataset.size() != 0) || elapsed_it == iterations) { APIData meas_out; this->_logger->info(""Start test""); tstart = steady_clock::now(); tsolver.eval(); test(ad, inputc, eval_dataset, test_batch_size, meas_out); tsolver.train(); last_test_time = duration_cast(steady_clock::now() - tstart) .count(); for (size_t i = 0; i < eval_dataset.size(); ++i) { APIData meas_obj; if (i == 0) meas_obj = meas_out.getobj(""measure""); else meas_obj = meas_out.getv(""measures"")[i]; std::vector meas_names = meas_obj.list_keys(); best_iteration_numbers[i] = save_if_best(i, meas_obj, elapsed_it, tsolver, best_iteration_numbers); this->_logger->info(""measures on test set "" + std::to_string(i) + "" : "" + eval_dataset.name(i)); for (auto name : meas_names) { if (name != ""cmdiag"" && name != ""cmfull"" && name != ""labels"" && name != ""test_id"" && name != ""test_name"") { double mval = meas_obj.get(name).get(); this->_logger->info(""{}={}"", name, mval); this->add_meas(name, mval); this->add_meas_per_iter(name, mval); } else if (name == ""cmdiag"") { std::vector mdiag = meas_obj.get(name) .get>(); std::vector cnames; std::string mdiag_str; for (size_t i = 0; i < mdiag.size(); i++) { mdiag_str += this->_mlmodel.get_hcorresp(i) + "":"" + std::to_string(mdiag.at(i)) + "" ""; this->add_meas_per_iter( name + '_' + this->_mlmodel.get_hcorresp(i), mdiag.at(i)); cnames.push_back( this->_mlmodel.get_hcorresp(i)); } this->_logger->info(""{}=[{}]"", name, mdiag_str); this->add_meas(name, mdiag, cnames); } } } if (elapsed_it == iterations) out = meas_out; } if ((save_period != 0 && elapsed_it % save_period == 0) || elapsed_it == iterations) { bool snapshotted = false; for (size_t i = 0; i < best_iteration_numbers.size(); ++i) { if (best_iteration_numbers[i] == elapsed_it) // current model already snapshoted as best model, // do not remove regular snapshot if it is best // model { best_iteration_numbers[i] = -1; snapshotted = true; } } if (!snapshotted) { snapshot(elapsed_it, tsolver); } } ++it; if (it >= iterations) break; } ++batch_id; } if (!this->_tjob_running.load()) { int64_t elapsed_it = it + 1; this->_logger->info(""Training job interrupted at iteration {}"", elapsed_it); bool snapshotted = false; for (size_t i = 0; i < best_iteration_numbers.size(); ++i) { if (best_iteration_numbers[i] == elapsed_it) // current model already snapshoted as best model, // do not remove regular snapshot if it is best // model { best_iteration_numbers[i] = -1; snapshotted = true; } } if (!snapshotted) snapshot(elapsed_it, tsolver); torch_utils::empty_cuda_cache(); return -1; } if (skip_training) test(ad, inputc, inputc._test_datasets, test_batch_size, out); torch_utils::empty_cuda_cache(); // Update model after training this->_mlmodel.read_from_repository(this->_logger); this->_mlmodel.read_corresp_file(); inputc.response_params(out); this->_logger->info(""Training done.""); return 0; } template int TorchLib::predict(const APIData &ad, APIData &out) { int64_t predict_batch_size = 1; APIData params = ad.getobj(""parameters""); APIData output_params = params.getobj(""output""); std::string extract_layer; bool extract_last = false; std::string forward_method; bool bbox = _bbox; double confidence_threshold = 0.0; int best_count = _nclasses; int best_bbox = -1; std::vector confidences; if (params.has(""mllib"")) { APIData ad_mllib = params.getobj(""mllib""); if (ad_mllib.has(""net"")) { APIData ad_net = ad_mllib.getobj(""net""); if (ad_net.has(""test_batch_size"")) predict_batch_size = ad_net.get(""test_batch_size"").get(); } if (ad_mllib.has(""extract_layer"")) { extract_layer = ad_mllib.get(""extract_layer"").get(); if (extract_layer == ""last"") extract_last = true; } if (ad_mllib.has(""forward_method"")) forward_method = ad_mllib.get(""forward_method"").get(); if (ad_mllib.has(""datatype"")) { std::string dt = ad_mllib.get(""datatype"").get(); if (dt == ""fp32"") _dtype = torch::kFloat32; else if (dt == ""fp16"") { if (_main_device == torch::Device(""cpu"")) throw MLLibBadParamException( ""fp16 inference can be done only on GPU""); _dtype = torch::kFloat16; } else if (dt == ""fp64"") _dtype = torch::kFloat64; else throw MLLibBadParamException(""unknown datatype "" + dt); } } if (output_params.has(""bbox"") && output_params.get(""bbox"").get()) { bbox = true; } if (output_params.has(""confidence_threshold"")) { try { confidence_threshold = output_params.get(""confidence_threshold"").get(); } catch (std::exception &e) { // try from int confidence_threshold = static_cast( output_params.get(""confidence_threshold"").get()); } } if (output_params.has(""best"")) { best_count = output_params.get(""best"").get(); } if (output_params.has(""best_bbox"")) { best_bbox = output_params.get(""best_bbox"").get(); } if (output_params.has(""confidences"")) { confidences = output_params.get(""confidences"").get>(); } bool lstm_continuation = false; TInputConnectorStrategy inputc(this->_inputc); this->_stats.transform_start(); TOutputConnectorStrategy outputc(this->_outputc); outputc._best = best_count; try { inputc.transform(ad); _module.post_transform_predict(_template, _template_params, inputc, this->_mlmodel, _main_device, ad); if (ad.getobj(""parameters"").getobj(""input"").has(""continuation"") && ad.getobj(""parameters"") .getobj(""input"") .get(""continuation"") .get()) lstm_continuation = true; else lstm_continuation = false; } catch (...) { throw; } this->_stats.transform_end(); _module.to(_dtype); torch::Device cpu(""cpu""); _module.eval(); if (!extract_last && !extract_layer.empty() && !_module.extractable(extract_layer)) { std::string els; for (const auto &el : _module.extractable_layers()) els += el + "" ""; this->_logger->error(""Unknown extract layer "" + extract_layer + "" candidates are "" + els); // or we could set back extract_layer to empty string and continue throw MLLibBadParamException(""unknown extract layer "" + extract_layer); } if (output_params.has(""measure"")) { APIData meas_out; test(ad, inputc, inputc._dataset, 1, meas_out); meas_out.erase(""iteration""); meas_out.erase(""train_loss""); out.add(""measure"", meas_out.getobj(""measure"")); torch_utils::empty_cuda_cache(); return 0; } inputc._dataset.reset(false); int batch_size = predict_batch_size; if (lstm_continuation) batch_size = 1; auto dataloader = torch::data::make_data_loader( std::move(inputc._dataset), data::DataLoaderOptions(batch_size)); std::vector results_ads; int nsample = 0; for (TorchBatch batch : *dataloader) { std::vector in_vals; for (Tensor tensor : batch.data) { if (tensor.scalar_type() == torch::kFloat32) tensor = tensor.to(_dtype); in_vals.push_back(tensor.to(_main_device)); } this->_stats.inc_inference_count(batch.data[0].size(0)); c10::IValue out_ivalue; Tensor output; try { if (extract_layer.empty() || extract_last) out_ivalue = _module.forward(in_vals, forward_method); else out_ivalue = _module.extract(in_vals, extract_layer); if (!bbox && !_segmentation) { output = torch_utils::to_tensor_safe(out_ivalue); // TODO move this code somewhere else if (_template == ""gpt2"") { // Keep only the prediction for the last token Tensor input_ids = batch.data[0]; std::vector outputs; for (int i = 0; i < input_ids.size(0); ++i) { // output is (n_batch * sequence_length * vocab_size) // With gpt2, last token is endoftext so we need to // take the previous output. outputs.push_back( output[i][inputc._lengths.at(i) - 2]); } output = torch::stack(outputs); } if (extract_layer.empty() && _classification && !_timeserie) output = torch::softmax(output, 1).to(cpu); else output = output.to(cpu); } } catch (std::exception &e) { throw MLLibInternalException(std::string(""Libtorch error:"") + e.what()); } // Output if (!extract_layer.empty()) { for (int j = 0; j < batch_size; j++) { APIData rad; if (!inputc._ids.empty()) rad.add(""uri"", inputc._ids.at(results_ads.size())); else rad.add(""uri"", std::to_string(results_ads.size())); if (!inputc._meta_uris.empty()) rad.add(""meta_uri"", inputc._meta_uris.at(results_ads.size())); if (!inputc._index_uris.empty()) rad.add(""index_uri"", inputc._index_uris.at(results_ads.size())); rad.add(""loss"", static_cast(0.0)); torch::Tensor fo = torch::flatten(output) .contiguous() .to(torch::kFloat64) .to(torch::Device(""cpu"")); double *startout = fo.data_ptr(); std::vector vals(startout, startout + torch::numel(fo)); rad.add(""vals"", vals); results_ads.push_back(rad); } } else { if (_module._native != nullptr) output = _module._native->cleanup_output(output); if (bbox) { // Supporting only torchvision output format at the moment. auto out_dicts = out_ivalue.toList(); for (size_t i = 0; i < out_dicts.size(); ++i) { std::string uri = inputc._ids.at(i); auto bit = inputc._imgs_size.find(uri); int rows = 1; int cols = 1; if (bit != inputc._imgs_size.end()) { // original image size rows = (*bit).second.first; cols = (*bit).second.second; } else { throw MLLibInternalException( ""Couldn't find original image size for "" + uri); } APIData results_ad; std::vector probs; std::vector cats; std::vector bboxes; auto out_dict = out_dicts.get(i).toGenericDict(); Tensor bboxes_tensor = torch_utils::to_tensor_safe(out_dict.at(""boxes"")) .to(cpu); Tensor labels_tensor = torch_utils::to_tensor_safe(out_dict.at(""labels"")) .to(cpu); Tensor score_tensor = torch_utils::to_tensor_safe(out_dict.at(""scores"")) .to(cpu); auto bboxes_acc = bboxes_tensor.accessor(); auto labels_acc = labels_tensor.accessor(); auto score_acc = score_tensor.accessor(); for (int j = 0; j < labels_tensor.size(0); ++j) { if (best_bbox > 0 && bboxes.size() >= static_cast(best_bbox)) break; double score = score_acc[j]; if (score < confidence_threshold) continue; probs.push_back(score); cats.push_back( this->_mlmodel.get_hcorresp(labels_acc[j])); double bbox[] = { bboxes_acc[j][0] / inputc.width() * (cols - 1), bboxes_acc[j][1] / inputc.height() * (rows - 1), bboxes_acc[j][2] / inputc.width() * (cols - 1), bboxes_acc[j][3] / inputc.height() * (rows - 1), }; // clamp bbox bbox[0] = std::max(0.0, bbox[0]); bbox[1] = std::max(0.0, bbox[1]); bbox[2] = std::min(static_cast(cols - 1), bbox[2]); bbox[3] = std::min(static_cast(cols - 1), bbox[3]); APIData ad_bbox; ad_bbox.add(""xmin"", bbox[0]); ad_bbox.add(""ymin"", bbox[1]); ad_bbox.add(""xmax"", bbox[2]); ad_bbox.add(""ymax"", bbox[3]); bboxes.push_back(ad_bbox); } results_ad.add(""uri"", inputc._uris.at(results_ads.size())); results_ad.add(""loss"", 0.0); results_ad.add(""probs"", probs); results_ad.add(""cats"", cats); results_ad.add(""bboxes"", bboxes); results_ads.push_back(results_ad); } } else if (_classification) { std::tuple sorted_output = output.sort(1, true); Tensor probsf = std::get<0>(sorted_output).to(torch::kFloat); auto probs_acc = probsf.accessor(); auto indices_acc = std::get<1>(sorted_output).accessor(); for (int i = 0; i < output.size(0); ++i) { APIData results_ad; std::vector probs; std::vector cats; for (int j = 0; j < best_count; ++j) { if (probs_acc[i][j] < confidence_threshold) { // break because probs are sorted break; } probs.push_back(probs_acc[i][j]); int index = indices_acc[i][j]; if (_seq_training) { cats.push_back(inputc.get_word(index)); } else { cats.push_back(this->_mlmodel.get_hcorresp(index)); } } results_ad.add(""uri"", inputc._uris.at(results_ads.size())); results_ad.add(""loss"", 0.0); results_ad.add(""cats"", cats); results_ad.add(""probs"", probs); results_ad.add(""nclasses"", (int)_nclasses); results_ads.push_back(results_ad); } } else if (_segmentation) { auto out_dict = out_ivalue.toGenericDict(); output = torch_utils::to_tensor_safe(out_dict.at(""out"")); output = torch::softmax(output, 1); int imgsize = inputc.width() * inputc.height(); torch::Tensor segmap; torch::Tensor confmap; std::tuple maxmap; if (!confidences.empty()) // applies ""best"" confidence lookup { maxmap = torch::max(output.clone().squeeze(), 0, false); confmap = torch::flatten(std::get<0>(maxmap)) .contiguous() .to(torch::kFloat64) .to(cpu); segmap = torch::flatten(std::get<1>(maxmap)) .contiguous() .to(torch::kFloat64) .to(cpu); } else segmap = torch::flatten(torch::argmax(output.squeeze(), 0)) .contiguous() .to(torch::kFloat64) .to(cpu); // squeeze removes the batch size APIData rad; std::string uri; if (!inputc._ids.empty()) uri = inputc._ids.at(results_ads.size()); else uri = std::to_string(results_ads.size()); rad.add(""uri"", uri); rad.add(""loss"", static_cast(0.0)); double *startout = segmap.data_ptr(); std::vector vals(startout, startout + torch::numel(segmap)); std::vector confs; if (!confidences.empty()) { startout = confmap.data_ptr(); confs = std::vector( startout, startout + torch::numel(confmap)); } auto bit = inputc._imgs_size.find(uri); APIData ad_imgsize; ad_imgsize.add(""height"", (*bit).second.first); ad_imgsize.add(""width"", (*bit).second.second); rad.add(""imgsize"", ad_imgsize); if (imgsize != (*bit).second.first * (*bit).second.second) // resizing output // segmentation array { vals = ImgInputFileConn::img_resize_vector( vals, inputc.height(), inputc.width(), (*bit).second.first, (*bit).second.second, true); if (!confidences.empty()) confs = ImgInputFileConn::img_resize_vector( confs, inputc.height(), inputc.width(), (*bit).second.first, (*bit).second.second, false); } rad.add(""vals"", vals); if (!confidences.empty()) { APIData vconfs; vconfs.add(""best"", confs); rad.add(""confidences"", vconfs); } results_ads.push_back(rad); } else if (_regression) { auto probs_acc = output.accessor(); for (int i = 0; i < output.size(0); ++i) { APIData results_ad; std::vector probs; std::vector cats; for (size_t j = 0; j < _nclasses; ++j) { probs.push_back(probs_acc[i][j]); cats.push_back(this->_mlmodel.get_hcorresp(j)); } results_ad.add(""uri"", inputc._uris.at(results_ads.size())); results_ad.add(""loss"", 0.0); results_ad.add(""cats"", cats); results_ad.add(""probs"", probs); results_ad.add(""nclasses"", (int)_nclasses); results_ads.push_back(results_ad); } } else if (_timeserie) { output = output.to(cpu); auto output_acc = output.accessor(); for (int j = 0; j < output.size(0); ++j) { std::vector series; for (int t = 0; t < output.size(1); ++t) { std::vector preds; for (unsigned int k = 0; k < inputc._ntargets; ++k) { double res = output_acc[j][t][k]; preds.push_back(unscale(res, k, inputc)); } APIData ts; ts.add(""out"", preds); series.push_back(ts); } APIData result_ad; if (!inputc._ids.empty()) result_ad.add(""uri"", inputc._ids.at(nsample++)); else result_ad.add(""uri"", std::to_string(nsample++)); result_ad.add(""series"", series); result_ad.add(""probs"", std::vector(series.size(), 1.0)); result_ad.add(""loss"", 0.0); results_ads.push_back(result_ad); } } } } if (extract_layer.empty() && !_segmentation) { outputc.add_results(results_ads); if (_timeserie) out.add(""timeseries"", true); if (_regression) out.add(""regression"", true); out.add(""bbox"", bbox); out.add(""nclasses"", static_cast(_nclasses)); outputc.finalize(output_params, out, static_cast(&this->_mlmodel)); } else { UnsupervisedOutput unsupo; unsupo.add_results(results_ads); unsupo.finalize(output_params, out, static_cast(&this->_mlmodel)); } if (ad.has(""chain"") && ad.get(""chain"").get()) { if (typeid(inputc) == typeid(ImgTorchInputFileConn)) { auto *img_ic = reinterpret_cast(&inputc); APIData chain_input; if (!img_ic->_orig_images.empty()) chain_input.add(""imgs"", img_ic->_orig_images); else chain_input.add(""imgs"", img_ic->_images); chain_input.add(""imgs_size"", img_ic->_images_size); out.add(""input"", chain_input); } } out.add(""status"", 0); return 0; } template int TorchLib::test(const APIData &ad, TInputConnectorStrategy &inputc, TorchMultipleDataset &testsets, int batch_size, APIData &out) { for (size_t i = 0; i < testsets.size(); ++i) test(ad, inputc, testsets[i], batch_size, out, i, testsets.name(i)); return 0; } template int TorchLib::test(const APIData &ad, TInputConnectorStrategy &inputc, TorchDataset &dataset, int batch_size, APIData &out, size_t test_id, const std::string &test_name) { APIData ad_res; APIData ad_bbox; APIData ad_out = ad.getobj(""parameters"").getobj(""output""); int nclasses = _masked_lm ? inputc.vocab_size() : _nclasses; // confusion matrix is irrelevant to masked_lm training if (_masked_lm && ad_out.has(""measure"")) { auto meas = ad_out.get(""measure"").get>(); std::vector::iterator it; if ((it = std::find(meas.begin(), meas.end(), ""cmfull"")) != meas.end()) meas.erase(it); if ((it = std::find(meas.begin(), meas.end(), ""cmdiag"")) != meas.end()) meas.erase(it); ad_out.add(""measure"", meas); } auto dataloader = torch::data::make_data_loader( dataset, data::DataLoaderOptions(batch_size)); torch::Device cpu(""cpu""); _module.eval(); int entry_id = 0; for (TorchBatch batch : *dataloader) { if (_masked_lm) { batch = inputc.generate_masked_lm_batch(batch); } std::vector in_vals; for (Tensor tensor : batch.data) in_vals.push_back(tensor.to(_main_device)); Tensor output; c10::IValue out_ivalue; try { out_ivalue = _module.forward(in_vals); if (!_bbox) { output = torch_utils::to_tensor_safe(out_ivalue); } } catch (std::exception &e) { throw MLLibInternalException(std::string(""Libtorch error: "") + e.what()); } if (batch.target.empty()) throw MLLibBadParamException(""Missing label on data while testing""); Tensor labels; if (_timeserie) { if (_module._native != nullptr) output = _module._native->cleanup_output(output); // iterate over data in batch labels = batch.target[0]; output = output.to(cpu); labels = labels.to(cpu); auto output_acc = output.accessor(); auto target_acc = labels.accessor(); // tensors are test_batch_size x timesteps x ntargets for (int j = 0; j < labels.size(0); ++j) { std::vector targets; std::vector predictions; std::vector targets_unscaled; std::vector predictions_unscaled; for (int t = 0; t < labels.size(1); ++t) for (unsigned int k = 0; k < inputc._ntargets; ++k) { targets.push_back(target_acc[j][t][k]); predictions.push_back(output_acc[j][t][k]); targets_unscaled.push_back( unscale(target_acc[j][t][k], k, inputc)); predictions_unscaled.push_back( unscale(output_acc[j][t][k], k, inputc)); } APIData bad; bad.add(""target"", targets); bad.add(""pred"", predictions); bad.add(""target_unscaled"", targets_unscaled); bad.add(""pred_unscaled"", predictions_unscaled); ad_res.add(std::to_string(entry_id), bad); ++entry_id; } } else if (_bbox) { // Supporting only Faster RCNN format at the moment. auto out_dicts = out_ivalue.toList(); Tensor targ_ids = batch.target.at(0); auto targ_ids_acc = targ_ids.accessor(); Tensor targ_bboxes = batch.target.at(1); Tensor targ_labels = batch.target.at(2); int stop = 0; for (size_t i = 0; i < out_dicts.size(); ++i) { auto out_dict = out_dicts.get(i).toGenericDict(); Tensor bboxes_tensor = torch_utils::to_tensor_safe(out_dict.at(""boxes"")) .to(cpu); Tensor labels_tensor = torch_utils::to_tensor_safe(out_dict.at(""labels"")) .to(cpu); Tensor score_tensor = torch_utils::to_tensor_safe(out_dict.at(""scores"")) .to(cpu); int start = stop; while (stop < static_cast(targ_ids.size(0)) && targ_ids_acc[stop] == static_cast(i)) { ++stop; } auto vbad = get_bbox_stats( targ_bboxes.index({ torch::indexing::Slice(start, stop) }), targ_labels.index({ torch::indexing::Slice(start, stop) }), bboxes_tensor, labels_tensor, score_tensor); ad_bbox.add(std::to_string(entry_id), vbad); ++entry_id; } } else { labels = batch.target[0].view(IntList{ -1 }); if (_masked_lm) { // Convert [n_batch, sequence_length, vocab_size] to [n_batch // * sequence_length, vocab_size] output = output.view(IntList{ -1, output.size(2) }); } if (_classification || _seq_training) { output = torch::softmax(output, 1).to(cpu); auto output_acc = output.accessor(); auto labels_acc = labels.accessor(); for (int j = 0; j < labels.size(0); ++j) { if (_masked_lm && labels_acc[j] == -1) continue; APIData bad; std::vector predictions; for (int c = 0; c < nclasses; ++c) { predictions.push_back(output_acc[j][c]); } bad.add(""target"", static_cast(labels_acc[j])); bad.add(""pred"", predictions); ad_res.add(std::to_string(entry_id), bad); ++entry_id; } } else if (_regression) { output = output.to(cpu); auto output_acc = output.accessor(); auto labels_acc = labels.accessor(); for (int j = 0; j < labels.size(0); ++j) { APIData bad; std::vector predictions; for (int c = 0; c < nclasses; ++c) { predictions.push_back(output_acc[j][c]); } bad.add(""target"", static_cast(labels_acc[j])); bad.add(""pred"", predictions); ad_res.add(std::to_string(entry_id), bad); ++entry_id; } } } // this->_logger->info(""Testing: {}/{} entries processed"", entry_id, // test_size); } ad_res.add(""iteration"", this->get_meas(""iteration"") + 1); ad_res.add(""train_loss"", this->get_meas(""train_loss"")); if (_timeserie) { ad_res.add(""timeserie"", true); ad_res.add(""timeseries"", (int)inputc._ntargets); } else { std::vector clnames; for (int i = 0; i < nclasses; i++) clnames.push_back(this->_mlmodel.get_hcorresp(i)); ad_res.add(""clnames"", clnames); ad_res.add(""nclasses"", nclasses); } if (_bbox) { ad_res.add(""bbox"", true); ad_res.add(""pos_count"", entry_id); ad_res.add(""0"", ad_bbox); } ad_res.add(""batch_size"", entry_id); // here batch_size = tested entries count SupervisedOutput::measure(ad_res, ad_out, out, test_id, test_name); _module.train(); return 0; } template std::vector TorchLib::get_bbox_stats(const at::Tensor &targ_bboxes, const at::Tensor &targ_labels, const at::Tensor &bboxes_tensor, const at::Tensor &labels_tensor, const at::Tensor &score_tensor) { auto targ_bboxes_acc = targ_bboxes.accessor(); auto targ_labels_acc = targ_labels.accessor(); auto bboxes_acc = bboxes_tensor.accessor(); auto labels_acc = labels_tensor.accessor(); auto score_acc = score_tensor.accessor(); APIData bad; // see caffe const int targ_bbox_count = targ_labels.size(0); const int pred_bbox_count = labels_tensor.size(0); std::vector match_used(targ_bbox_count, false); struct eval_info { // every positive score std::vector tp_d; // 1 if true pos, 0 otherwise std::vector tp_i; // every positive score std::vector fp_d; // 1 if false pos, 0 otherwise std::vector fp_i; int num_pos; // XXX: fp variables are useless since tp_d == fp_d & tp_i == !fp_i // This could be refactored along with supervised output // connector }; std::vector eval_infos(_nclasses); for (int j = 0; j < pred_bbox_count; ++j) { double score = score_acc[j]; int cls = labels_acc[j]; if (cls >= static_cast(_nclasses)) { throw MLLibInternalException( ""Model output class: "" + std::to_string(cls) + "" is invalid for nclasses = "" + std::to_string(_nclasses)); } std::vector bbox{ bboxes_acc[j][0], bboxes_acc[j][1], bboxes_acc[j][2], bboxes_acc[j][3], }; bool found = false; for (int k = 0; k < targ_bbox_count; ++k) { if (!match_used[k]) { std::vector targ_bbox{ targ_bboxes_acc[k][0], targ_bboxes_acc[k][1], targ_bboxes_acc[k][2], targ_bboxes_acc[k][3], }; if (bbox_utils::iou(bbox, targ_bbox) > 0.5 && targ_labels_acc[k] == cls) { match_used[k] = true; found = true; eval_infos[cls].tp_d.push_back(score); eval_infos[cls].tp_i.push_back(1); eval_infos[cls].fp_d.push_back(score); eval_infos[cls].fp_i.push_back(0); break; } } } if (!found) { eval_infos[cls].tp_d.push_back(score); eval_infos[cls].tp_i.push_back(0); eval_infos[cls].fp_d.push_back(score); eval_infos[cls].fp_i.push_back(1); } } for (int k = 0; k < targ_bbox_count; ++k) { eval_infos[targ_labels_acc[k]].num_pos++; } std::vector vbad; for (size_t label = 1; label < _nclasses; ++label) { APIData lbad; lbad.add(""tp_d"", eval_infos[label].tp_d); lbad.add(""tp_i"", eval_infos[label].tp_i); lbad.add(""fp_d"", eval_infos[label].fp_d); lbad.add(""fp_i"", eval_infos[label].fp_i); lbad.add(""num_pos"", eval_infos[label].num_pos); lbad.add(""label"", static_cast(label)); vbad.push_back(lbad); } return vbad; } template class TorchLib; template class TorchLib; template class TorchLib; } // namespace dd ",16215,True,2748.5000028272507,median "Let's Get It Started! To make your NEORV32 project run, follow the guides from the upcoming sections. Follow these guides step by step and in the presented order. :sectnums: == Software Toolchain Setup To compile (and debug) executables for the NEORV32 a RISC-V toolchain is required. There are two possibilities to get this: 1. Download and _build_ the official RISC-V GNU toolchain yourself 2. Download and install a prebuilt version of the toolchain; this might also done via the package manager / app store of your OS [TIP] The default toolchain prefix for this project is **`riscv32-unknown-elf-`**. Of course you can use any other RISC-V toolchain (like `riscv64-unknown-elf-`) that is capable to emit code for a `rv32` architecture. Just change the _RISCV_PREFIX_ variable in the application makefile(s) according to your needs or define this variable when invoking the makefile. [IMPORTANT] Keep in mind that – for instance – a rv32imc toolchain only provides library code compiled with compressed (_C_) and `mul`/`div` instructions (_M_)! Hence, this code cannot be executed (without emulation) on an architecture without these extensions! :sectnums: === Building the Toolchain from Scratch To build the toolchain by yourself you can follow the guide from the official https://github.com/riscv/riscv-gnu-toolchain GitHub page. You need to make sure the generated toolchain fits the architecture of the NEORV32 core. To get a toolchain that even supports minimal ISA extension configurations, it is recommend to compile for `rv32i` only. Please note that this minimal ISA also provides further ISA extensions like `m` or `c`. Of course you can use a `multilib` approach to generate toolchains for several target ISAs. .Configuring GCC build for `rv32i` (minimal ISA) [source,bash] ---- riscv-gnu-toolchain$ ./configure --prefix=/opt/riscv --with-arch=rv32i –-with-abi=ilp32 riscv-gnu-toolchain$ make ---- :sectnums: === Downloading and Installing a Prebuilt Toolchain Alternatively, you can download a prebuilt toolchain. :sectnums: ==== Use The Toolchain I have Build I have compiled a GCC toolchain on a 64-bit x86 Ubuntu (Ubuntu on Windows, actually) and uploaded it to GitHub. You can directly download the according toolchain archive as single _zip-file_ within a packed release from https://github.com/stnolting/riscv-gcc-prebuilt. Unpack the downloaded toolchain archive and copy the content to a location in your file system (e.g. `/opt/riscv`). More information about downloading and installing my prebuilt toolchains can be found in the repository's README. :sectnums: ==== Use a Third Party Toolchain Of course you can also use any other prebuilt version of the toolchain. There are a lot RISC-V GCC packages out there - even for Windows. On Linux system you might even be able to fetch a toolchain via your distribution's package manager. [IMPORTANT] Make sure the toolchain can (also) emit code for a `rv32i` architecture, uses the `ilp32` or `ilp32e` ABI and **was not build** using CPU extensions that are not supported by the NEORV32 (like `D`). :sectnums: === Installation Now you have the toolchain binaries. The last step is to add them to your `PATH` environment variable (if you have not already done so): make sure to add the _binaries_ folder (`bin`) of your toolchain. [source,bash] ---- $ export PATH:$PATH:/opt/riscv/bin ---- You should add this command to your `.bashrc` (if you are using bash) to automatically add the RISC-V toolchain at every console start. :sectnums: === Testing the Installation To make sure everything works fine, navigate to an example project in the NEORV32 example folder and execute the following command: [source,bash] ---- neorv32/sw/example/blink_led$ make check ---- This will test all the tools required for the generating NEORV32 executables. Everything is working fine if `Toolchain check OK` appears at the end. <<< // #################################################################################################################### :sectnums: == General Hardware Setup This guide will setup a NEORV32 project for FPGA implementation (or simulation only) _from scratch_ [TIP] If you want to use a complete pre-defined setup to start with, check out the project's `setups` folder (https://github.com/stnolting/neorv32/tree/master/setups), which provides (script-based) demo setups for various FPGA boards and toolchains. This tutorial uses a _simplified_ test setup of the processor to keeps things simple at the beginning as this setup is intended as evaluation or ""hello world"" project to check out the NEORV32. [start=1] . Create a new project with your FPGA EDA tool of choice. . Add all VHDL files from the project's `rtl/core` folder to your project. Make sure to _reference_ the files only – do not copy them. . Make sure to add all the rtl files to a new library called `neorv32`. If your FPGA tools does not provide a field to enter the library name, check out the ""properties"" menu of the added rtl files. . The `rtl/core/neorv32_top.vhd` VHDL file is the top entity of the NEORV32 processor. If you already have a design, instantiate this unit into your design and proceed. [IMPORTANT] Make sure to include the `neorv32` package into your design when instantiating the processor: add `library neorv32;` and `use neorv32.neorv32_package.all;` to your design unit. [start=5] . If you do not have a design yet and just want to check out the NEORV32 – no problem! This guide uses a simplified top entity, that encapsulates the actual processor top entity: add the `rtl/templates/processor/neorv32_ProcessorTop_Test.vhd` VHDL file to your project, too, and select it as _top entity_. . This test setup provides a minimal test hardware setup: .NEORV32 ""hello world"" test setup image::neorv32_test_setup.png[align=center] [start=7] . It only implements some very basic processor and CPU features. Also, only the minimum number of signals is propagated to the outer world. . However, a minimal setup-specific configuration of the NEORV32 processor is required to make it run on your FPGA board of choice. Only the absolutely required modifications will be made while keeping the default configuration for the remaining configuration options: .Cut-out of `neorv32_ProcessorTop_Test.vhd` showing the processor instance and its configuration [source,vhdl] ---- neorv32_top_inst: neorv32_top generic map ( -- General -- CLOCK_FREQUENCY => 100000000, -- in Hz # <1> INT_BOOTLOADER_EN => true, ... -- Internal instruction memory -- MEM_INT_IMEM_EN => true, MEM_INT_IMEM_SIZE => 16*1024, # <2> -- Internal data memory -- MEM_INT_DMEM_EN => true, MEM_INT_DMEM_SIZE => 8*1024, # <3> ... ---- <1> Clock frequency of `clk_i` signal in Hertz <2> Default size of internal instruction memory: 16kB <3> Default size of internal data memory: 8kB [start=9] . There is one generic that has to be set according to your FPGA board setup: the actual clock frequency of the top's clock input signal (`clk_i`). Use the _CLOCK_FREQUENC_Y generic to specify your clock source's frequency in Hertz (Hz) (note ""1""). . If you feel like it – or if your FPGA does not provide many resources – you can modify the **memory sizes** (_MEM_INT_IMEM_SIZE_ and _MEM_INT_DMEM_SIZE_ – marked with notes ""2"" and ""3"") or even exclude certain ISA extensions and peripheral modules from implementation - but as mentioned above, let's keep things simple at first and use the standard configuration for now. [NOTE] If you have changed the default memory configuration (_MEM_INT_IMEM_SIZE_ and _MEM_INT_DMEM_SIZE_ generics) keep those new sizes in mind – these values are required for setting up the software framework in the next section <<_general_software_framework_setup>>. [start=11] . Depending on your FPGA tool of choice, it is time to assign the signals of the test setup top entity to the according pins of your FPGA board. All the signals can be found in the entity declaration: .Entity signals of `neorv32_test_setup.vhd` [source,vhdl] ---- entity neorv32_test_setup is port ( -- Global control -- clk_i : in std_ulogic := '0'; -- global clock, rising edge rstn_i : in std_ulogic := '0'; -- global reset, low-active, async -- GPIO -- gpio_o : out std_ulogic_vector(7 downto 0); -- parallel output -- UART0 -- uart0_txd_o : out std_ulogic; -- UART0 send data uart0_rxd_i : in std_ulogic := '0' -- UART0 receive data ); end neorv32_test_setup; ---- [start=12] . Attach the clock input `clk_i` to your clock source and connect the reset line `rstn_i` to a button of your FPGA board. Check whether it is low-active or high-active – the reset signal of the processor is **low-active**, so maybe you need to invert the input signal. . If possible, connected at least bit `0` of the GPIO output port `gpio_o` to a high-active LED (invert the signal when your LEDs are low-active). This LED will be used as status LED for the setup. . Finally, if your FPGA board provides a serial host interface (USB-to-serial converter) interface, connect the UART communication signals `uart0_txd_o` and `uart0_rxd_i`. . Perform the project HDL compilation (synthesis, mapping, bitstream generation). . Program the generated bitstream into your FPGA and press the button connected to the reset signal. . Done! The assigned status LED should be flashing now for some sections before permanently lighting up. <<< // #################################################################################################################### :sectnums: == General Software Framework Setup To allow executables to be _actually executed_ on the NEORV32 Processor the configuration of the software framework has to be aware to the hardware configuration. This guide focuses on the memory configuration. To enabled certain CPU ISA festures refer to the <<_enabling_risc_v_cpu_extensions>> section. [TIP] If you have **not** changed the _default_ memory configuration in section <<_general_hardware_setup>> you are already done and you can skip the rest of this guide. [start=1] . Open the NEORV32 linker script `sw/common/neorv32.ld` with a text editor. Right at the beginning of this script you will find the `MEMORY` configuration listing the different memory section: .Cut-out of the linker script `neorv32.ld`: `ram` memory section configuration [source,c] ---- MEMORY { ram (rwx) : ORIGIN = 0x80000000, LENGTH = DEFINED(make_bootloader) ? 512 : 8*1024 # <1> ... ---- <1> Size of the data memory address space (right-most value) (internal/external DMEM); here 8kB [start=2] . We only need to change the `ram` section, which presents the available data address space. If you have changed the DMEM (_MEM_INT_DMEM_SIZE_ generic) size adapt the `LENGTH` parameter of the `ram` section (here: `8*1024`) so it is equal to your DMEM hardware configuration. [IMPORTANT] Make sure you only modify the _right-most_ value (here: 8*1024)! + The ""`512`"" are not relevant for the application. [start=3] . Done! Save your changes and close the linker script. .Advanced: Section base address and size [IMPORTANT] More information can be found in the datasheet section https://stnolting.github.io/neorv32/#_address_space[Address Space]. <<< // #################################################################################################################### :sectnums: == Application Program Compilation This guide shows how to compile an example C-code application into a NEORV32 executable that can be uploaded via the bootloader or the on-chip debugger. [IMPORTANT] If your FPGA board does not provide such an interface - don't worry! Section <<_installing_an_executable_directly_into_memory>> shows how to run custom programs on your FPGA setup without having a UART. [start=1] . Open a terminal console and navigate to one of the project's example programs. For instance, navigate to the simple `sw/example_blink_led` example program. This program uses the NEORV32 GPIO module to display an 8-bit counter on the lowest eight bit of the `gpio_o` output port. . To compile the project and generate an executable simply execute: [source,bash] ---- neorv32/sw/example/blink_led$ make clean_all exe ---- [start=3] . We are using the `clean_all` taret to make sure everything is re-build. . This will compile and link the application sources together with all the included libraries. At the end, your application is transformed into an ELF file (`main.elf`). The _NEORV32 image generator_ (in `sw/image_gen`) takes this file and creates a final executable. The makefile will show the resulting memory utilization and the executable size: [source,bash] ---- neorv32/sw/example/blink_led$ make clean_all exe Memory utilization: text data bss dec hex filename 3176 0 120 3296 ce0 main.elf Compiling ../../../sw/image_gen/image_gen Executable (neorv32_exe.bin) size in bytes: 3188 ---- [start=5] . That's it. The `exe` target has created the actual executable `neorv32_exe.bin` in the current folder that is ready to be uploaded to the processor. [TIP] The compilation process will also create a `main.asm` assembly listing file in the current folder, which shows the actual assembly code of the application. <<< // #################################################################################################################### :sectnums: == Uploading and Starting of a Binary Executable Image via UART Follow this guide to use the bootloader to upload an executable via UART. [NOTE] This concept uses the default ""Indirect Boot"" scenario that uses the bootloader to upload new executables. See datasheet section https://stnolting.github.io/neorv32/#_indirect_boot[Indirect Boot] for more information. [IMPORTANT] If your FPGA board does not provide such an interface - don't worry! Section <<_installing_an_executable_directly_into_memory>> shows how to run custom programs on your FPGA setup without having a UART. [start=1] . Connect the primary UART (UART0) interface of your FPGA board to a serial port of your host computer. . Start a terminal program. In this tutorial, I am using TeraTerm for Windows. You can download it fore free from https://ttssh2.osdn.jp/index.html.en [NOTE] _Any_ terminal program that can connect to a serial port should work. However, make sure the program can transfer data in _raw_ byte mode without any protocol overhead around it. [start=3] . Open a connection to the the serial port your UART is connected to. Configure the terminal setting according to the following parameters: * 19200 Baud * 8 data bits * 1 stop bit * no parity bits * _no_ transmission/flow control protocol * receiver (host computer) newline on `\\r\\n` (carriage return & newline) [start=4] . Also make sure that single chars are send from your computer _without_ any consecutive ""new line"" or ""carriage return"" commands (this is highly dependent on your terminal application of choice, TeraTerm only sends the raw chars by default). . Press the NEORV32 reset button to restart the bootloader. The status LED starts blinking and the bootloader intro screen appears in your console. Hurry up and press any key (hit space!) to abort the automatic boot sequence and to start the actual bootloader user interface console. .Bootloader console; aborted auto-boot sequence [source,bash] ---- << NEORV32 Bootloader >> BLDV: Mar 23 2021 HWV: 0x01050208 CLK: 0x05F5E100 MISA: 0x40901105 ZEXT: 0x00000023 PROC: 0x0EFF0037 IMEM: 0x00004000 bytes @ 0x00000000 DMEM: 0x00002000 bytes @ 0x80000000 Autoboot in 8s. Press key to abort. Aborted. Available commands: h: Help r: Restart u: Upload s: Store to flash l: Load from flash e: Execute CMD:> ---- [start=6] . Execute the ""Upload"" command by typing `u`. Now the bootloader is waiting for a binary executable to be send. [source,bash] ---- CMD:> u Awaiting neorv32_exe.bin... ---- [start=7] . Use the ""send file"" option of your terminal program to send a NEORV32 executable (`neorv32_exe.bin`). . Again, make sure to transmit the executable in raw binary mode (no transfer protocol). When using TeraTerm, select the ""binary"" option in the send file dialog. . If everything went fine, OK will appear in your terminal: [source,bash] ---- CMD:> u Awaiting neorv32_exe.bin... OK ---- [start=10] . The executable is now in the instruction memory of the processor. To execute the program right now run the ""Execute"" command by typing `e`: [source,bash] ---- CMD:> u Awaiting neorv32_exe.bin... OK CMD:> e Booting... Blinking LED demo program ---- [start=11] . If everything went fine, you should see the LEDs blinking. [NOTE] The bootloader will print error codes if something went wrong. See section https://stnolting.github.io/neorv32/#_bootloader[Bootloader] of the NEORV32 datasheet for more information. [TIP] See section <<_programming_an_external_spi_flash_via_the_bootloader>> to learn how to use an external SPI flash for nonvolatile program storage. [TIP] Executables can also be uploaded via the **on-chip debugger**. See section <<_debugging_with_gdb>> for more information. <<< // #################################################################################################################### :sectnums: == Installing an Executable Directly Into Memory If you do not want to use the bootloader (or the on-chip debugger) for executable upload or if your setup does not provide a serial interface for that, you can also directly install an application into embedded memory. This concept uses the ""Direct Boot"" scenario that implements the processor-internal IMEM as ROM, which is pre-initialized with the application's executable during synthesis. Hence, it provides _non-volatile_ storage of the executable inside the processor. This storage cannot be altered during runtime and any source code modification of the application requires to re-program the FPGA via the bitstream. [TIP] See datasheet section https://stnolting.github.io/neorv32/#_direct_boot[Direct Boot] for more information. Using the IMEM as ROM: * for this boot concept the bootloader is no longer required * this concept only works for the internal IMEM (but can be extended to work with external memories coupled via the processor's bus interface) * make sure that the memory components (like block RAM) the IMEM is mapped to support an initialization via the bitstream [start=1] . At first, make sure your processor setup actually implements the internal IMEM: the `MEM_INT_IMEM_EN` generics has to be set to `true`: .Processor top entity configuration - enable internal IMEM [source,vhdl] ---- -- Internal Instruction memory -- MEM_INT_IMEM_EN => true, -- implement processor-internal instruction memory ---- [start=2] . For this setup we do not want the bootloader to be implemented at all. Disable implementation of the bootloader by setting the `INT_BOOTLOADER_EN` generic to `false`. This will also modify the processor-internal IMEM so it is initialized with the executable during synthesis. .Processor top entity configuration - disable internal bootloader [source,vhdl] ---- -- General -- INT_BOOTLOADER_EN => false, -- boot configuration: false = boot from int/ext (I)MEM ---- [start=3] . To generate an ""initialization image"" for the IMEM that contains the actual application, run the `install` target when compiling your application: [source,bash] ---- neorv32/sw/example/blink_led$ make clean_all install Memory utilization: text data bss dec hex filename 3176 0 120 3296 ce0 main.elf Compiling ../../../sw/image_gen/image_gen Installing application image to ../../../rtl/core/neorv32_application_image.vhd ---- [start=4] . The `install` target has compiled all the application sources but instead of creating an executable (`neorv32_exe.bit`) that can be uploaded via the bootloader, it has created a VHDL memory initialization image `core/neorv32_application_image.vhd`. . This VHDL file is automatically copied to the core's rtl folder (`rtl/core`) so it will be included for the next synthesis. . Perform a new synthesis. The IMEM will be build as pre-initialized ROM (inferring embedded memories if possible). . Upload your bitstream. Your application code now resides unchangeable in the processor's IMEM and is directly executed after reset. The synthesis tool / simulator will print asserts to inform about the (IMEM) memory / boot configuration: [source] ---- NEORV32 PROCESSOR CONFIG NOTE: Boot configuration: Direct boot from memory (processor-internal IMEM). NEORV32 PROCESSOR CONFIG NOTE: Implementing processor-internal IMEM as ROM (3176 bytes), pre-initialized with application. ---- <<< // #################################################################################################################### :sectnums: == Setup of a New Application Program Project [start=1] . The easiest way of creating a _new_ software application project is to copy an _existing_ one. This will keep all file dependencies. For example you can copy `sw/example/blink_led` to `sw/example/flux_capacitor`. . If you want to place you application somewhere outside `sw/example` you need to adapt the application's makefile. In the makefile you will find a variable that keeps the relative or absolute path to the NEORV32 repo home folder. Just modify this variable according to your new project's home location: [source,makefile] ---- # Relative or absolute path to the NEORV32 home folder (use default if not set by user) NEORV32_HOME ?= ../../.. ---- [start=3] . If your project contains additional source files outside of the project folder, you can add them to the `APP_SRC` variable: [source,makefile] ---- # User's application sources (add additional files here) APP_SRC = $(wildcard *.c) ../somewhere/some_file.c ---- [start=4] . You also can add a folder containing your application's include files to the `APP_INC` variable (do not forget the `-I` prefix): [source,makefile] ---- # User's application include folders (don't forget the '-I' before each entry) APP_INC = -I . -I ../somewhere/include_stuff_folder ---- <<< // #################################################################################################################### :sectnums: == Enabling RISC-V CPU Extensions Whenever you enable/disable a RISC-V CPU extensions via the according `CPU_EXTENSION_RISCV_x` generic, you need to adapt the toolchain configuration so the compiler can actually generate according code for it. To do so, open the makefile of your project (for example `sw/example/blink_led/makefile`) and scroll to the ""USER CONFIGURATION"" section right at the beginning of the file. You need to modify the `MARCH` variable and eventually the `MABI` variable according to your CPU hardware configuration. [source,makefile] ---- # CPU architecture and ABI MARCH = -march=rv32i # <1> MABI = -mabi=ilp32 # <2> ---- <1> MARCH = Machine architecture (""ISA string"") <2> MABI = Machine binary interface For example, if you enable the RISC-V `C` extension (16-bit compressed instructions) via the `CPU_EXTENSION_RISCV_C` generic (set `true`) you need to add the 'c' extension also to the `MARCH` ISA string in order to make the compiler emit compressed instructions. [WARNING] ISA extension enabled in hardware can be a superset of the extensions enabled in software, but not the other way around. For example generating compressed instructions for a CPU configuration that has the `c` extension disabled will cause _illegal instruction exceptions_ at runtime. You can also override the default `MARCH` and `MABI` configurations from the makefile when invoking the makefile: [source,bash] ---- $ make MARCH=-march=rv32ic clean_all all ---- [NOTE] The RISC-V ISA string (for _MARCH_) follows a certain _canonical_ structure: `rev32[i/e][m][a][f][d][g][q][c][b][v][n]...` For example `rv32imac` is valid while `rv32icma` is not valid. <<< // #################################################################################################################### :sectnums: == Customizing the Internal Bootloader The NEORV32 bootloader provides several options to configure and customize it for a certain application setup. This configuration is done by passing _defines_ when compiling the bootloader. Of course you can also modify to bootloader source code to provide a setup that perfectly fits your needs. [IMPORTANT] Each time the bootloader sources are modified, the bootloader has to be re-compiled (and re-installed to the bootloader ROM) and the processor has to be re-synthesized. [NOTE] Keep in mind that the maximum size for the bootloader is limited to 32kB and should be compiled using the base ISA `rv32i` only to ensure it can work independently of the actual CPU configuration. .Bootloader configuration parameters [cols=""<2,^1,^2,<6""] [options=""header"", grid=""rows""] |======================= | Parameter | Default | Legal values | Description 4+^| Serial console interface | `UART_EN` | `1` | `0`, `1` | Set to `0` to disable UART0 (no serial console at all) | `UART_BAUD` | `19200` | _any_ | Baud rate of UART0 4+^| Status LED | `STATUS_LED_EN` | `1` | `0`, `1` | Enable bootloader status led (""heart beat"") at `GPIO` output port pin #`STATUS_LED_PIN` when `1` | `STATUS_LED_PIN` | `0` | `0` ... `31` | `GPIO` output pin used for the high-active status LED 4+^| Boot configuration | `AUTO_BOOT_SPI_EN` | `0` | `0`, `1` | Set `1` to enable immediate boot from external SPI flash | `AUTO_BOOT_OCD_EN` | `0` | `0`, `1` | Set `1` to enable boot via on-chip debugger (OCD) | `AUTO_BOOT_TIMEOUT` | `8` | _any_ | Time in seconds after the auto-boot sequence starts (if there is no UART input by user); set to 0 to disabled auto-boot sequence 4+^| SPI configuration | `SPI_FLASH_CS` | `0` | `0` ... `7` | SPI chip select output (`spi_csn_o`) for selecting flash | `SPI_FLASH_SECTOR_SIZE` | `65536` | _any_ | SPI flash sector size in bytes | `SPI_FLASH_CLK_PRSC` | `CLK_PRSC_8` | `CLK_PRSC_2` `CLK_PRSC_4` `CLK_PRSC_8` `CLK_PRSC_64` `CLK_PRSC_128` `CLK_PRSC_1024` `CLK_PRSC_2024` `CLK_PRSC_4096` | SPI clock pre-scaler (dividing main processor clock) | `SPI_BOOT_BASE_ADDR` | `0x08000000` | _any_ 32-bit value | Defines the _base_ address of the executable in external flash |======================= Each configuration parameter is implemented as C-language `define` that can be manually overridden (_redefined_) when invoking the bootloader's makefile. The according parameter and its new value has to be _appended_ (using `+=`) to the makefile's `USER_FLAGS` variable. Make sure to use the `-D` prefix here. For example, to configure a UART Baud rate of 57600 and redirecting the status LED to output pin 20 use the following command (_in_ the bootloader's source folder `sw/bootloader`): .Example: customizing, re-compiling and re-installing the bootloader [source,console] ---- $ make USER_FLAGS+=-DUART_BAUD=57600 USER_FLAGS+=-DSTATUS_LED_PIN=20 clean_all bootloader ---- [NOTE] The `clean_all` target ensure that all libraries are re-compiled. The `bootloader` target will automatically compile and install the bootloader to the HDL boot ROM (updating `rtl/core/neorv32_bootloader_image.vhd`). :sectnums: === Bootloader Boot Configuration The bootloader provides several _boot configurations_ that define where the actual application's executable shall be fetched from. Note that the non-default boot configurations provide a smaller memory footprint reducing boot ROM implementation costs. :sectnums!: ==== Default Boot Configuration The _default_ bootloader configuration provides a UART-based user interface that allows to upload new executables at any time. Optionally, the executable can also be programmed to an external SPI flash by the bootloader (see section <<_programming_an_external_spi_flash_via_the_bootloader>>). This configuration also provides an _automatic boot sequence_ (auto-boot) which will start fetching an executable from external SPI flash using the default SPI configuration. By this, the default bootloader configuration provides a ""non volatile program storage"" mechanism that automatically boot from external SPI flash (after `AUTO_BOOT_TIMEOUT`) while still providing the option to re-program SPI flash at any time via the UART interface. :sectnums!: ==== `AUTO_BOOT_SPI_EN` The automatic boot from SPI flash (enabled when `AUTO_BOOT_SPI_EN` is `1`) will fetch an executable from an external SPI flash (using the according _SPI configuration_) right after reset. The bootloader will start fetching the image at SPI flash base address `SPI_BOOT_BASE_ADDR`. Note that there is _no_ UART console to interact with the bootloader. However, this boot configuration will output minimal status messages via UART (if `UART_EN` is `1`). :sectnums!: ==== `AUTO_BOOT_OCD_EN` If `AUTO_BOOT_OCD_EN` is `1` the bootloader is implemented as minimal ""halt loop"" to be used with the on-chip debugger. After initializing the hardware, the CPU waits in this endless loop until the on-chip debugger takes control over the core (to upload and run the actual executable). See section <<_debugging_using_the_on_chip_debugger>> for more information on how to use the on-chip debugger to upload and run executables. [NOTE] All bootloader boot configuration support uploading new executables via the on-chip debugger. [WARNING] Note that this boot configuration does not load any executable at all! Hence, this boot configuration is intended to be used with the on-chip debugger only. <<< // #################################################################################################################### :sectnums: == Programming an External SPI Flash via the Bootloader The default processor-internal NEORV32 bootloader supports automatic booting from an external SPI flash. This guide shows how to write an executable to the SPI flash via the bootloader so it can be automatically fetched and executed after processor reset. For example, you can use a section of the FPGA bitstream configuration memory to store an application executable. [NOTE] This section assumes the _default_ configuration of the NEORV32 bootloader. See section <<_customizing_the_internal_bootloader>> on how to customize the bootloader and its setting (for example the SPI chip-select port, the SPI clock speed or the flash base address for storing the executable). :sectnums: === SPI Flash The bootloader can access an SPI compatible flash via the processor top entity's SPI port. By default, the flash chip-select line is to `spi_csn_o(0)` and uses 1/8 of the processor's main clock as clock frequency. The SPI flash has to support single-byte read and write, 24-bit addresses and at least the following standard commands: * READ `0x03` * READ STATUS `0x05` * WRITE ENABLE `0x06` * PAGE PROGRAM `0x02` * SECTOR ERASE `0xD8` * READ ID `0x9E` Compatible (FGPA configuration) SPI flash memories are for example the ""Winbond W25Q64FV2 or the ""Micron N25Q032A"". :sectnums: === Programming an Executable [start=1] . At first, reset the NEORV32 processor and wait until the bootloader start screen appears in your terminal program. . Abort the auto boot sequence and start the user console by pressing any key. . Press u to upload the executable that you want to store to the external flash: [source] ---- CMD:> u Awaiting neorv32_exe.bin... ---- [start=4] . Send the binary in raw binary via your terminal program. When the upload is completed and ""OK"" appears, press `p` to trigger the programming of the flash (do not execute the image via the `e` command as this might corrupt the image): [source] ---- CMD:> u Awaiting neorv32_exe.bin... OK CMD:> p Write 0x000013FC bytes to SPI flash @ 0x00800000? (y/n) ---- [start=5] . The bootloader shows the size of the executable and the base address inside the SPI flash where the executable is going to be stored. A prompt appears: Type `y` to start the programming or type `n` to abort. [TIP] Section <<_customizing_the_internal_bootloader>> show the according C-language `define` that can be modified to specify the base address of the executable inside the SPI flash. [source] ---- CMD:> u Awaiting neorv32_exe.bin... OK CMD:> p Write 0x000013FC bytes to SPI flash @ 0x08000000? (y/n) y Flashing... OK CMD:> ---- [start=6] . If ""OK"" appears in the terminal line, the programming process was successful. Now you can use the auto boot sequence to automatically boot your application from the flash at system start-up without any user interaction. <<< // #################################################################################################################### :sectnums: == Packaging the Processor as IP block for Xilinx Vivado Block Designer .WORK IN PROGRESS [WARNING] This Section Is Under Construction! + + FIXME! <<< // #################################################################################################################### :sectnums: == Simulating the Processor .WORK IN PROGRESS [WARNING] This Section Is Under Construction! + + FIXME! :sectnums: === Testbench The NEORV32 project features a simple default testbench (`sim/neorv32_tb.simple.vhd`) that can be used to simulate and test the processor setup. This testbench features a 100MHz clock and enables all optional peripheral and CPU extensions except for the `E` extension and the TRNG IO module (that CANNOT be simulated due to its combinatorial (looped) oscillator architecture). The simulation setup is configured via the ""User Configuration"" section located right at the beginning of the testbench's architecture. Each configuration constant provides comments to explain the functionality. Besides the actual NEORV32 Processor, the testbench also simulates ""external"" components that are connected to the processor's external bus/memory interface. These components are: * an external instruction memory (that also allows booting from it) * an external data memory * an external memory to simulate ""external IO devices"" * a memory-mapped registers to trigger the processor's interrupt signals The following table shows the base addresses of these four components and their default configuration and properties (attributes: `r` = read, `w` = write, `e` = execute, `a` = atomic accesses possible, `8` = byte-accessible, `16` = half-word-accessible, `32` = word-accessible). .Testbench: processor-external memories [cols=""^4,>3,^5,<11""] [options=""header"",grid=""rows""] |======================= | Base address | Size | Attributes | Description | `0x00000000` | `imem_size_c` | `r/w/e, a, 8/16/32` | external IMEM (initialized with application image) | `0x80000000` | `dmem_size_c` | `r/w/e, a, 8/16/32` | external DMEM | `0xf0000000` | 64 bytes | `r/w/e, !a, 8/16/32` | external ""IO"" memory, atomic accesses will fail | `0xff000000` | 4 bytes | `-/w/-, a, -/-/32` | memory-mapped register to trigger ""machine external"", ""machine software"" and ""SoC Fast Interrupt"" interrupts |======================= The simulated NEORV32 does not use the bootloader and directly boots the current application image (from the `rtl/core/neorv32_application_image.vhd` image file). Make sure to use the `all` target of the makefile to install your application as VHDL image after compilation: [source, bash] ---- sw/example/blink_led$ make clean_all all ---- .Simulation-Optimized CPU/Processors Modules [NOTE] The `sim/rtl_modules` folder provides simulation-optimized versions of certain CPU/processor modules. These alternatives can be used to replace the default CPU/processor HDL files to allow faster/easier/more efficient simulation. **These files are not intended for synthesis!** **Simulation Console Output** Data written to the NEORV32 UART0 / UART1 transmitter is send to a virtual UART receiver implemented as part of the testbench. Received chars are send to the simulator console and are also stored to a log file (`neorv32.testbench_uart0.out` for UART0, `neorv32.testbench_uart1.out` for UART1) inside the simulator home folder. :sectnums: === Faster Simulation Console Output When printing data via the UART the communication speed will always be based on the configured BAUD rate. For a simulation this might take some time. To have faster output you can enable the **simulation mode** or UART0/UART1 (see section https://stnolting.github.io/neorv32/#_primary_universal_asynchronous_receiver_and_transmitter_uart0[Documentation: Primary Universal Asynchronous Receiver and Transmitter (UART0)]). ASCII data send to UART0 will be immediately printed to the simulator console. Additionally, the ASCII data is logged in a file (`neorv32.uart0.sim_mode.text.out`) in the simulator home folder. All written 32-bit data is also dumped as 8-char hexadecimal value into a file (`neorv32.uart0.sim_mode.data.out`) also in the simulator home folder. ASCII data send to UART1 will be immediately printed to the simulator console. Additionally, the ASCII data is logged in a file (`neorv32.uart1.sim_mode.text.out`) in the simulator home folder. All written 32-bit data is also dumped as 8-char hexadecimal value into a file (`neorv32.uart1.sim_mode.data.out`) also in the simulator home folder. You can ""automatically"" enable the simulation mode of UART0/UART1 when compiling an application. In this case the ""real"" UART0/UART1 transmitter unit is permanently disabled. To enable the simulation mode just compile and install your application and add _UART0_SIM_MODE_ for UART0 and/or _UART1_SIM_MODE_ for UART1 to the compiler's _USER_FLAGS_ variable (do not forget the `-D` suffix flag): [source, bash] ---- sw/example/blink_led$ make USER_FLAGS+=-DUART0_SIM_MODE clean_all all ---- The provided define will change the default UART0/UART1 setup function in order to set the simulation mode flag in the according UART's control register. [NOTE] The UART simulation output (to file and to screen) outputs ""complete lines"" at once. A line is completed with a line feed (newline, ASCII `\\n` = 10). :sectnums: === Simulation using GHDL To simulate the processor using _GHDL_ navigate to the `sim` folder and run the provided shell script. Any arguments that are provided while executing this script are passed to GHDL. For example the simulation time can be set to 20ms using `--stop-time=20ms` as argument. [source, bash] ---- neorv32/sim$ sh ghdl_sim.sh --stop-time=20ms ---- <<< // #################################################################################################################### :sectnums: == Building the Documentation The documentation (datasheet + user guide) is written using `asciidoc`. The according source files can be found in `docs/...`. The documentation of the software framework is written _in-code_ using `doxygen`. A makefiles in the project's `docs` directory is provided to build all of the documentation as HTML pages or as PDF documents. [TIP] Pre-rendered PDFs are available online as _nightly pre-releases_: https://github.com/stnolting/neorv32/releases. The HTML-based documentation is also available online at the project's https://stnolting.github.io/neorv32/[GitHub Pages]. The makefile provides a help target to show all available build options and their according outputs. [source,bash] ---- neorv32/docs$ make help ---- .Example: Generate HTML documentation (data sheet) using `asciidoctor` [source,bash] ---- neorv32/docs$ make html ---- [TIP] If you don't have `asciidoctor` / `asciidoctor-pdf` installed, you can still generate all the documentation using a _docker container_ via `make container`. <<< // #################################################################################################################### :sectnums: == FreeRTOS Support A NEORV32-specific port and a simple demo for FreeRTOS (https://github.com/FreeRTOS/FreeRTOS) are available in the `sw/example/demo_freeRTOS` folder. See the according documentation (`sw/example/demo_freeRTOS/README.md`) for more information. // #################################################################################################################### :sectnums: == RISC-V Architecture Test Framework The NEORV32 Processor passes the according tests provided by the official RISC-V Architecture Test Suite (V2.0+), which is available online at GitHub: https://github.com/riscv/riscv-arch-test All files required for executing the test framework on a simulated instance of the processor (including port files) are located in the `riscv-arch-test` folder in the root directory of the NEORV32 repository. Take a look at the provided `riscv-arch-test/README.md` (https://github.com/stnolting/neorv32/blob/master/riscv-arch-test/README.md[online at GitHub]) file for more information on how to run the tests and how testing is conducted in detail. <<< // #################################################################################################################### :sectnums: == Debugging using the On-Chip Debugger The NEORV32 on-chip debugger allows _online_ in-system debugging via an external JTAG access port from a host machine. The general flow is independent of the host machine's operating system. However, this tutorial uses Windows and Linux (Ubuntu on Windows) in parallel. [TIP] See datasheet section https://stnolting.github.io/neorv32/#_on_chip_debugger_ocd[On Chip Debugger (OCD)] for more information. [NOTE] This tutorial uses `gdb` to **directly upload an executable** to the processor. If you are using the default processor setup _with_ internal instruction memory (IMEM) make sure it is implemented as RAM (_INT_BOOTLOADER_EN_ generic = true). :sectnums: === Hardware Requirements Make sure the on-chip debugger of your NEORV32 setups is implemented (_ON_CHIP_DEBUGGER_EN_ generic = true). Connect a JTAG adapter to the NEORV32 `jtag_*` interface signals. If you do not have a full-scale JTAG adapter, you can also use a FTDI-based adapter like the ""FT2232H-56Q Mini Module"", which is a simple and inexpensive FTDI breakout board. .JTAG pin mapping [cols=""^3,^2,^2""] [options=""header"",grid=""rows""] |======================= | NEORV32 top signal | JTAG signal | FTDI port | `jtag_tck_i` | TCK | D0 | `jtag_tdi_i` | TDI | D1 | `jtag_tdo_o` | TDO | D2 | `jtag_tms_i` | TMS | D3 | `jtag_trst_i` | TRST | D4 |======================= [TIP] The low-active JTAG _test reset_ (TRST) signals is _optional_ as a reset can also be triggered via the TAP controller. If TRST is not used make sure to pull the signal _high_. :sectnums: === OpenOCD The NEORV32 on-chip debugger can be accessed using the https://github.com/riscv/riscv-openocd[RISC-V port of OpenOCD]. Prebuilt binaries can be obtained - for example - from https://www.sifive.com/software[SiFive]. A pre-configured OpenOCD configuration file (`sw/openocd/openocd_neorv32.cfg`) is available that allows easy access to the NEORV32 CPU. [NOTE] You might need to adapt `ftdi_vid_pid`, `ftdi_channel` and `ftdi_layout_init` in `sw/openocd/openocd_neorv32.cfg` according to your interface chip and your operating system. [TIP] If you want to modify the JTAG clock speed (via `adapter speed` in `sw/openocd/openocd_neorv32.cfg`) make sure to meet the clock requirements noted in https://stnolting.github.io/neorv32/#_debug_module_dm[Documentation: Debug Transport Module (DTM)]. To access the processor using OpenOCD, open a terminal and start OpenOCD with the pre-configured configuration file. .Connecting via OpenOCD (on Windows) [source, bash] -------------------------- N:\\Projects\\neorv32\\sw\\openocd>openocd -f openocd_neorv32.cfg Open On-Chip Debugger 0.11.0-rc1+dev (SiFive OpenOCD 0.10.0-2020.12.1) Licensed under GNU GPL v2 For bug reports: https://github.com/sifive/freedom-tools/issues 1 Info : Listening on port 6666 for tcl connections Info : Listening on port 4444 for telnet connections Info : clock speed 1000 kHz Info : JTAG tap: neorv32.cpu tap/device found: 0x0cafe001 (mfg: 0x000 (), part: 0xcafe, ver: 0x0) Info : datacount=1 progbufsize=2 Info : Disabling abstract command reads from CSRs. Info : Examined RISC-V core; found 1 harts Info : hart 0: XLEN=32, misa=0x40801105 Info : starting gdb server for neorv32.cpu.0 on 3333 Info : Listening on port 3333 for gdb connections -------------------------- OpenOCD has successfully connected to the NEORV32 on-chip debugger and has examined the CPU (showing the content of the `misa` CSRs). Now you can use `gdb` to connect via port 3333. :sectnums: === Debugging with GDB This guide uses the simple ""blink example"" from `sw/example/blink_led` as simplified test application to show the basics of in-system debugging. At first, the application needs to be compiled. We will use the minimal machine architecture configuration (`rv32i`) here to be independent of the actual processor/CPU configuration. Navigate to `sw/example/blink_led` and compile the application: .Compile the test application [source, bash] -------------------------- .../neorv32/sw/example/blink_led$ make MARCH=-march=rv32i clean_all all -------------------------- This will generate an ELF file `main.elf` that contains all the symbols required for debugging. Furthermore, an assembly listing file `main.asm` is generated that we will use to define breakpoints. Open another terminal in `sw/example/blink_led` and start `gdb`. The GNU debugger is part of the toolchain (see <<_software_toolchain_setup>>). .Starting GDB (on Linux (Ubuntu on Windows)) [source, bash] -------------------------- .../neorv32/sw/example/blink_led$ riscv32-unknown-elf-gdb GNU gdb (GDB) 10.1 Copyright (C) 2020 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type ""show copying"" and ""show warranty"" for details. This GDB was configured as ""--host=x86_64-pc-linux-gnu --target=riscv32-unknown-elf"". Type ""show configuration"" for configuration details. For bug reporting instructions, please see: . Find the GDB manual and other documentation resources online at: . For help, type ""help"". Type ""apropos word"" to search for commands related to ""word"". (gdb) -------------------------- Now connect to OpenOCD using the default port 3333 on your local machine. Set the ELF file we want to debug to the recently generated `main.elf` from the `blink_led` example. Finally, upload the program to the processor. [NOTE] The executable that is uploaded to the processor is **not** the default NEORV32 executable (`neorv32_exe.bin`) that is used for uploading via the bootloader. Instead, all the required sections (like `.text`) are extracted from `mail.elf` by GDB and uploaded via the debugger's indirect memory access. .Running GDB [source, bash] -------------------------- (gdb) target remote localhost:3333 <1> Remote debugging using localhost:3333 warning: No executable has been specified and target does not support determining executable automatically. Try using the ""file"" command. 0xffff0c94 in ?? () <2> (gdb) file main.elf <3> A program is being debugged already. Are you sure you want to change the file? (y or n) y Reading symbols from main.elf... (gdb) load <4> Loading section .text, size 0xd0c lma 0x0 Loading section .rodata, size 0x39c lma 0xd0c Start address 0x00000000, load size 4264 Transfer rate: 43 KB/sec, 2132 bytes/write. (gdb) -------------------------- <1> Connect to OpenOCD <2> The CPU was still executing code from the bootloader ROM - but that does not matter here <3> Select `mail.elf` from the `blink_led` example <4> Upload the executable After the upload, GDB will make the processor jump to the beginning of the uploaded executable (by default, this is the beginning of the instruction memory at `0x00000000`) skipping the bootloader and halting the CPU right before executing the `blink_led` application. :sectnums: ==== Breakpoint Example The following steps are just a small showcase that illustrate a simple debugging scheme. While compiling `blink_led`, an assembly listing file `main.asm` was generated. Open this file with a text editor to check out what the CPU is going to do when resumed. The `blink_led` example implements a simple counter on the 8 lowest GPIO output ports. The program uses ""busy wait"" to have a visible delay between increments. This waiting is done by calling the `neorv32_cpu_delay_ms` function. We will add a _breakpoint_ right at the end of this wait function so we can step through the iterations of the counter. .Cut-out from `main.asm` generated from the `blink_led` example [source, assembly] -------------------------- 00000688 <__neorv32_cpu_delay_ms_end>: 688: 01c12083 lw ra,28(sp) 68c: 02010113 addi sp,sp,32 690: 00008067 ret -------------------------- The very last instruction of the `neorv32_cpu_delay_ms` function is `ret` (= return) at hexadecimal `690` in this example. Add this address as _breakpoint_ to GDB. [NOTE] The address might be different if you use a different version of the software framework or if different ISA options are configured. .Adding a GDB breakpoint [source, bash] -------------------------- (gdb) b * 0x690 Breakpoint 1 at 0x690 -------------------------- Now execute `c` (= continue). The CPU will resume operation until it hits the break-point. By this we can ""step"" from increment to increment. .Iterating from breakpoint to breakpoint [source, bash] -------------------------- Breakpoint 1 at 0x690 (gdb) c Continuing. Breakpoint 1, 0x00000690 in neorv32_cpu_delay_ms () (gdb) c Continuing. Breakpoint 1, 0x00000690 in neorv32_cpu_delay_ms () (gdb) c Continuing. -------------------------- include::../legal.adoc[] ",12473,False,2112.2001908366365,median " #include ""xsheetviewer.h"" #include ""sceneviewerevents.h"" #include ""tapp.h"" #include ""floatingpanelcommand.h"" #include ""menubarcommandids.h"" #include ""toonz/tcolumnhandle.h"" #include ""toonz/txsheethandle.h"" #include ""toonz/tfxhandle.h"" #include ""toonz/tscenehandle.h"" #include ""toonz/tframehandle.h"" #include ""toonz/tobjecthandle.h"" #include ""toonz/txshpalettelevel.h"" #include ""toonz/preferences.h"" #include ""toonz/sceneproperties.h"" #include ""toutputproperties.h"" #include ""toonzqt/tselectionhandle.h"" #include ""toonzqt/icongenerator.h"" #include ""cellselection.h"" #include ""keyframeselection.h"" #include ""cellkeyframeselection.h"" #include ""columnselection.h"" #include ""xsheetdragtool.h"" #include ""toonzqt/gutil.h"" #include ""toonz/txsheet.h"" #include ""toonz/txshcell.h"" #include ""toonz/txshleveltypes.h"" #include ""toonz/txshzeraryfxcolumn.h"" #include ""toonz/toonzscene.h"" #include ""toonz/columnfan.h"" #include ""toonz/txshnoteset.h"" #include ""toonz/childstack.h"" #include ""toonz/txshlevelhandle.h"" #include ""toonz/tproject.h"" #include ""tconvert.h"" #include ""tenv.h"" #include ""tools/toolcommandids.h"" #include ""tools/cursormanager.h"" #include ""tools/cursors.h"" #include #include #include #include TEnv::IntVar FrameDisplayStyleInXsheetRowArea( ""FrameDisplayStyleInXsheetRowArea"", 0); //============================================================================= namespace XsheetGUI { //----------------------------------------------------------------------------- const int ColumnWidth = 74; const int RowHeight = 20; const int SCROLLBAR_WIDTH = 16; const int TOOLBAR_HEIGHT = 29; const int ZOOM_FACTOR_MAX = 100; const int ZOOM_FACTOR_MIN = 20; } // namespace XsheetGUI //============================================================================= // XsheetViewer //----------------------------------------------------------------------------- void XsheetViewer::getCellTypeAndColors(int <ype, QColor &cellColor, QColor &sideColor, const TXshCell &cell, bool isSelected) { if (cell.isEmpty()) ltype = NO_XSHLEVEL; else { ltype = cell.m_level->getType(); switch (ltype) { case TZI_XSHLEVEL: case OVL_XSHLEVEL: cellColor = (isSelected) ? getSelectedFullcolorColumnColor() : getFullcolorColumnColor(); sideColor = getFullcolorColumnBorderColor(); break; case PLI_XSHLEVEL: cellColor = (isSelected) ? getSelectedVectorColumnColor() : getVectorColumnColor(); sideColor = getVectorColumnBorderColor(); break; case TZP_XSHLEVEL: cellColor = (isSelected) ? getSelectedLevelColumnColor() : getLevelColumnColor(); sideColor = getLevelColumnBorderColor(); break; case ZERARYFX_XSHLEVEL: cellColor = (isSelected) ? getSelectedFxColumnColor() : getFxColumnColor(); sideColor = getFxColumnBorderColor(); break; case CHILD_XSHLEVEL: cellColor = (isSelected) ? getSelectedChildColumnColor() : getChildColumnColor(); sideColor = getChildColumnBorderColor(); break; case SND_XSHLEVEL: cellColor = (isSelected) ? m_selectedSoundColumnColor : m_soundColumnColor; sideColor = m_soundColumnBorderColor; break; case SND_TXT_XSHLEVEL: cellColor = (isSelected) ? getSelectedSoundTextColumnColor() : getSoundTextColumnColor(); sideColor = getSoundTextColumnBorderColor(); break; case MESH_XSHLEVEL: cellColor = (isSelected) ? getSelectedMeshColumnColor() : getMeshColumnColor(); sideColor = getMeshColumnBorderColor(); break; case UNKNOWN_XSHLEVEL: case NO_XSHLEVEL: default: // non dovrebbe succedere cellColor = grey210; sideColor = grey150; } } } //----------------------------------------------------------------------------- void XsheetViewer::getColumnColor(QColor &color, QColor &sideColor, int index, TXsheet *xsh) { if (index < 0 || xsh->isColumnEmpty(index)) return; int r0, r1; xsh->getCellRange(index, r0, r1); if (0 <= r0 && r0 <= r1) { // column color depends on the level type in the top-most occupied cell if (xsh->getColumn(index)->getSoundColumn()) { color = m_soundColumnColor; sideColor = m_soundColumnBorderColor; } else { TXshCell cell = xsh->getCell(r0, index); int ltype; getCellTypeAndColors(ltype, color, sideColor, cell); } } if (xsh->getColumn(index)->isMask()) color = QColor(255, 0, 255); } //----------------------------------------------------------------------------- void XsheetViewer::getButton(const int &btype, QColor &bgColor, QImage &iconImage, bool isTimeline) { switch (btype) { case PREVIEW_ON_XSHBUTTON: bgColor = (isTimeline) ? getTimelinePreviewButtonBgOnColor() : getXsheetPreviewButtonBgOnColor(); iconImage = (isTimeline) ? getTimelinePreviewButtonOnImage() : getXsheetPreviewButtonOnImage(); break; case PREVIEW_OFF_XSHBUTTON: bgColor = (isTimeline) ? getTimelinePreviewButtonBgOffColor() : getXsheetPreviewButtonBgOffColor(); iconImage = (isTimeline) ? getTimelinePreviewButtonOffImage() : getXsheetPreviewButtonOffImage(); break; case CAMSTAND_ON_XSHBUTTON: bgColor = (isTimeline) ? getTimelineCamstandButtonBgOnColor() : getXsheetCamstandButtonBgOnColor(); iconImage = (isTimeline) ? getTimelineCamstandButtonOnImage() : getXsheetCamstandButtonOnImage(); break; case CAMSTAND_TRANSP_XSHBUTTON: bgColor = (isTimeline) ? getTimelineCamstandButtonBgOnColor() : getXsheetCamstandButtonBgOnColor(); iconImage = (isTimeline) ? getTimelineCamstandButtonTranspImage() : getXsheetCamstandButtonTranspImage(); break; case CAMSTAND_OFF_XSHBUTTON: bgColor = (isTimeline) ? getTimelineCamstandButtonBgOffColor() : getXsheetCamstandButtonBgOffColor(); iconImage = (isTimeline) ? getTimelineCamstandButtonOffImage() : getXsheetCamstandButtonOffImage(); break; case LOCK_ON_XSHBUTTON: bgColor = (isTimeline) ? getTimelineLockButtonBgOnColor() : getXsheetLockButtonBgOnColor(); iconImage = (isTimeline) ? getTimelineLockButtonOnImage() : getXsheetLockButtonOnImage(); break; case LOCK_OFF_XSHBUTTON: bgColor = (isTimeline) ? getTimelineLockButtonBgOffColor() : getXsheetLockButtonBgOffColor(); iconImage = (isTimeline) ? getTimelineLockButtonOffImage() : getXsheetLockButtonOffImage(); break; case CONFIG_XSHBUTTON: bgColor = (isTimeline) ? getTimelineConfigButtonBgColor() : getXsheetConfigButtonBgColor(); iconImage = (isTimeline) ? getTimelineConfigButtonImage() : getXsheetConfigButtonImage(); break; default: bgColor = grey210; static QImage iconignored; iconImage = iconignored; } } //----------------------------------------------------------------------------- #if QT_VERSION >= 0x050500 XsheetViewer::XsheetViewer(QWidget *parent, Qt::WindowFlags flags) #else XsheetViewer::XsheetViewer(QWidget *parent, Qt::WFlags flags) #endif : QFrame(parent) , m_timerId(0) , m_autoPanSpeed(0, 0) , m_dragTool(0) , m_columnSelection(new TColumnSelection()) , m_cellKeyframeSelection(new TCellKeyframeSelection( new TCellSelection(), new TKeyframeSelection())) , m_scrubCol(-1) , m_scrubRow0(-1) , m_scrubRow1(-1) , m_isCurrentFrameSwitched(false) , m_isCurrentColumnSwitched(false) , m_isComputingSize(false) , m_currentNoteIndex(0) , m_qtModifiers(0) , m_frameDisplayStyle(to_enum(FrameDisplayStyleInXsheetRowArea)) , m_orientation(nullptr) , m_xsheetLayout(""Classic"") , m_frameZoomFactor(100) { m_xsheetLayout = Preferences::instance()->getLoadedXsheetLayout(); setFocusPolicy(Qt::StrongFocus); setFrameStyle(QFrame::StyledPanel); setObjectName(""XsheetViewer""); m_orientation = Orientations::topToBottom(); m_cellKeyframeSelection->setXsheetHandle( TApp::instance()->getCurrentXsheet()); m_toolbarScrollArea = new XsheetScrollArea(this); m_toolbarScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_toolbarScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_toolbar = new XsheetGUI::QuickToolbar(this, 0, true); m_toolbarScrollArea->setWidget(m_toolbar); m_noteArea = new XsheetGUI::NoteArea(this); m_noteScrollArea = new XsheetScrollArea(this); m_noteScrollArea->setObjectName(""xsheetArea""); m_noteScrollArea->setWidget(m_noteArea); m_noteScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_noteScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_cellArea = new XsheetGUI::CellArea(this); m_cellScrollArea = new XsheetScrollArea(this); m_cellScrollArea->setObjectName(""xsheetArea""); m_cellScrollArea->setWidget(m_cellArea); m_cellScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_cellScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_columnArea = new XsheetGUI::ColumnArea(this); m_columnScrollArea = new XsheetScrollArea(this); m_columnScrollArea->setObjectName(""xsheetArea""); m_columnScrollArea->setWidget(m_columnArea); m_columnScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_columnScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_rowArea = new XsheetGUI::RowArea(this); m_rowScrollArea = new XsheetScrollArea(this); m_rowScrollArea->setObjectName(""xsheetArea""); m_rowScrollArea->setWidget(m_rowArea); m_rowScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_rowScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_layerFooterPanel = new LayerFooterPanel(this, this); m_frameScroller.setFrameScrollArea(m_cellScrollArea); connect(&m_frameScroller, &Spreadsheet::FrameScroller::prepareToScrollOffset, this, &XsheetViewer::onPrepareToScrollOffset); connect(&m_frameScroller, &Spreadsheet::FrameScroller::zoomScrollAdjust, this, &XsheetViewer::onZoomScrollAdjust); connectScrollBars(); connect(this, &XsheetViewer::orientationChanged, this, &XsheetViewer::onOrientationChanged); connect(m_toolbar, SIGNAL(updateVisibility()), this, SLOT(positionSections())); emit orientationChanged(orientation()); onPreferenceChanged(""XsheetCamera""); } //----------------------------------------------------------------------------- XsheetViewer::~XsheetViewer() { delete m_cellKeyframeSelection; delete m_dragTool; } //----------------------------------------------------------------------------- void XsheetViewer::setDragTool(XsheetGUI::DragTool *dragTool) { assert(m_dragTool == 0); m_dragTool = dragTool; } //----------------------------------------------------------------------------- void XsheetViewer::dragToolClick(QMouseEvent *e) { if (m_dragTool) m_dragTool->onClick(e); } void XsheetViewer::dragToolDrag(QMouseEvent *e) { if (m_dragTool) m_dragTool->onDrag(e); } void XsheetViewer::dragToolRelease(QMouseEvent *e) { if (m_dragTool) { m_dragTool->onRelease(e); delete getDragTool(); m_dragTool = 0; } } //----------------------------------------------------------------------------- void XsheetViewer::dragToolClick(QDropEvent *e) { if (m_dragTool) m_dragTool->onClick(e); } void XsheetViewer::dragToolDrag(QDropEvent *e) { if (m_dragTool) m_dragTool->onDrag(e); } void XsheetViewer::dragToolRelease(QDropEvent *e) { if (m_dragTool) { m_dragTool->onRelease(e); delete getDragTool(); m_dragTool = 0; } } void XsheetViewer::dragToolLeave(QEvent *e) { if (m_dragTool) { delete getDragTool(); m_dragTool = 0; } } //----------------------------------------------------------------------------- const Orientation *XsheetViewer::orientation() const { if (!m_orientation) throw std::runtime_error(""!m_orientation""); return m_orientation; } void XsheetViewer::flipOrientation() { m_orientation = orientation()->next(); int factor = (m_orientation->isVerticalTimeline()) ? m_frameZoomFactor : 100; TApp::instance()->getCurrentXsheet()->notifyZoomScaleChanged(factor); emit orientationChanged(orientation()); } void XsheetViewer::onOrientationChanged(const Orientation *newOrientation) { disconnectScrollBars(); positionSections(); m_frameScroller.setOrientation(newOrientation); refreshContentSize(0, 0); connectScrollBars(); update(); } void XsheetViewer::positionSections() { if (!isVisible()) return; const Orientation *o = orientation(); QRect size = QRect(QPoint(0, 0), geometry().size()); NumberRange allLayer = o->layerSide(size); NumberRange allFrame = o->frameSide(size); NumberRange headerLayer = o->range(PredefinedRange::HEADER_LAYER); NumberRange headerFrame = o->range(PredefinedRange::HEADER_FRAME); NumberRange bodyLayer(headerLayer.to(), allLayer.to()); NumberRange bodyFrame(headerFrame.to(), allFrame.to()); if (Preferences::instance()->isShowQuickToolbarEnabled()) { m_toolbar->showToolbar(true); int w = visibleRegion().boundingRect().width(); m_toolbarScrollArea->setGeometry(0, 0, w, XsheetGUI::TOOLBAR_HEIGHT); m_toolbar->setFixedWidth(w); if (o->isVerticalTimeline()) { headerFrame = headerFrame.adjusted(XsheetGUI::TOOLBAR_HEIGHT, XsheetGUI::TOOLBAR_HEIGHT); bodyFrame = bodyFrame.adjusted(XsheetGUI::TOOLBAR_HEIGHT, 0); } else { headerLayer = headerLayer.adjusted(XsheetGUI::TOOLBAR_HEIGHT, XsheetGUI::TOOLBAR_HEIGHT); bodyLayer = bodyLayer.adjusted(XsheetGUI::TOOLBAR_HEIGHT, 0); } } else { m_toolbar->showToolbar(false); } m_noteScrollArea->setGeometry(o->frameLayerRect(headerFrame, headerLayer)); m_cellScrollArea->setGeometry(o->frameLayerRect(bodyFrame, bodyLayer)); m_columnScrollArea->setGeometry( o->frameLayerRect(headerFrame.adjusted(-1, -1), bodyLayer.adjusted(0, -XsheetGUI::SCROLLBAR_WIDTH))); m_rowScrollArea->setGeometry(o->frameLayerRect( bodyFrame.adjusted(0, -XsheetGUI::SCROLLBAR_WIDTH), headerLayer)); if (o->isVerticalTimeline()) { m_layerFooterPanel->setGeometry(m_columnScrollArea->geometry().right() + 1, m_columnScrollArea->geometry().top(), 14, m_columnScrollArea->height()); } else { m_layerFooterPanel->setGeometry(0, m_columnScrollArea->geometry().bottom() + 1, m_columnScrollArea->width(), 14); } m_layerFooterPanel->showOrHide(o); } void XsheetViewer::disconnectScrollBars() { connectOrDisconnectScrollBars(false); } void XsheetViewer::connectScrollBars() { connectOrDisconnectScrollBars(true); } void XsheetViewer::connectOrDisconnectScrollBars(bool toConnect) { const Orientation *o = orientation(); bool isVertical = o->isVerticalTimeline(); QWidget *scrolledVertically = (isVertical ? m_rowScrollArea : m_columnScrollArea)->verticalScrollBar(); QWidget *scrolledHorizontally = (isVertical ? m_columnScrollArea : m_rowScrollArea) ->horizontalScrollBar(); connectOrDisconnect(toConnect, scrolledVertically, SIGNAL(valueChanged(int)), m_cellScrollArea->verticalScrollBar(), SLOT(setValue(int))); connectOrDisconnect(toConnect, m_cellScrollArea->verticalScrollBar(), SIGNAL(valueChanged(int)), scrolledVertically, SLOT(setValue(int))); connectOrDisconnect( toConnect, scrolledHorizontally, SIGNAL(valueChanged(int)), m_cellScrollArea->horizontalScrollBar(), SLOT(setValue(int))); connectOrDisconnect(toConnect, m_cellScrollArea->horizontalScrollBar(), SIGNAL(valueChanged(int)), scrolledHorizontally, SLOT(setValue(int))); connectOrDisconnect( toConnect, m_cellScrollArea->verticalScrollBar(), SIGNAL(valueChanged(int)), this, isVertical ? SLOT(updateCellRowAree()) : SLOT(updateCellColumnAree())); connectOrDisconnect( toConnect, m_cellScrollArea->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, isVertical ? SLOT(updateCellColumnAree()) : SLOT(updateCellRowAree())); } void XsheetViewer::connectOrDisconnect(bool toConnect, QWidget *sender, const char *signal, QWidget *receiver, const char *slot) { if (toConnect) connect(sender, signal, receiver, slot); else disconnect(sender, signal, receiver, slot); } //----------------------------------------------------------------------------- TXsheet *XsheetViewer::getXsheet() const { return TApp::instance()->getCurrentXsheet()->getXsheet(); } //----------------------------------------------------------------------------- int XsheetViewer::getCurrentColumn() const { return TApp::instance()->getCurrentColumn()->getColumnIndex(); } //----------------------------------------------------------------------------- int XsheetViewer::getClickedColumn() const { if (!m_columnArea) return -1; return m_columnArea->getClickedColumn(); } //----------------------------------------------------------------------------- int XsheetViewer::getCurrentRow() const { return TApp::instance()->getCurrentFrame()->getFrame(); } //----------------------------------------------------------------------------- TStageObjectId XsheetViewer::getObjectId(int col) const { TXsheet *xsh = getXsheet(); if (col < 0) return TStageObjectId::CameraId(xsh->getCameraColumnIndex()); return TStageObjectId::ColumnId(col); } //----------------------------------------------------------------------------- void XsheetViewer::setCurrentColumn(int col) { TColumnHandle *columnHandle = TApp::instance()->getCurrentColumn(); if (col != columnHandle->getColumnIndex() || !columnHandle->getColumn()) { columnHandle->setColumnIndex(col); // E' necessario per il caso in cui si passa da colonna di camera a altra // colonna // o nel caso in cui si passa da una spline a una colonna. TObjectHandle *objectHandle = TApp::instance()->getCurrentObject(); if (col >= 0 && objectHandle->isSpline()) objectHandle->setIsSpline(false); updateCellColumnAree(); if (col >= 0) { objectHandle->setObjectId(TStageObjectId::ColumnId(col)); TXsheet *xsh = getXsheet(); TXshColumn *column = xsh->getColumn(col); if (!column || !column->getZeraryFxColumn()) return; TFx *fx = column->getZeraryFxColumn()->getZeraryColumnFx(); TApp::instance()->getCurrentFx()->setFx(fx); } return; } } //----------------------------------------------------------------------------- void XsheetViewer::setCurrentRow(int row) { // POTREBBE NON ESSER PIU' NECESSARIO CON LE NUOVE MODIFICHE PER CLEANUP A // COLORI /*TFrameHandle* frameHandle = TApp::instance()->getCurrentFrame(); if(row == frameHandle->getFrameIndex() && frameHandle->getFrameType() == TFrameHandle::SceneFrame) { //E' necessario per il caso in cui la paletta corrente e' la paletta di cleanup. TPaletteHandle* levelPaletteHandle = TApp::instance()->getPaletteController()->getCurrentLevelPalette(); TXshLevel *xl = TApp::instance()->getCurrentLevel()->getLevel(); if(xl && xl->getSimpleLevel()) levelPaletteHandle->setPalette(xl->getSimpleLevel()->getPalette()); else if(xl && xl->getPaletteLevel()) levelPaletteHandle->setPalette(xl->getPaletteLevel()->getPalette()); else levelPaletteHandle->setPalette(0); return; } frameHandle->setFrame(row);*/ TApp::instance()->getCurrentFrame()->setFrame(row); } //----------------------------------------------------------------------------- void XsheetViewer::scroll(QPoint delta) { int x = delta.x(); int y = delta.y(); int valueH = m_cellScrollArea->horizontalScrollBar()->value() + x; int valueV = m_cellScrollArea->verticalScrollBar()->value() + y; int maxValueH = m_cellScrollArea->horizontalScrollBar()->maximum(); int maxValueV = m_cellScrollArea->verticalScrollBar()->maximum(); bool notUpdateSizeH = maxValueH > valueH && x >= 0; bool notUpdateSizeV = maxValueV > valueV && y >= 0; if (!notUpdateSizeH && !notUpdateSizeV) // Resize orizzontale e verticale refreshContentSize(x, y); else if (notUpdateSizeH && !notUpdateSizeV) // Resize verticale refreshContentSize(0, y); else if (!notUpdateSizeH && notUpdateSizeV) // Resize orizzontale refreshContentSize(x, 0); // Recheck in case refreshContentSize changed the max if (!notUpdateSizeH) maxValueH = m_cellScrollArea->horizontalScrollBar()->maximum(); if (!notUpdateSizeV) maxValueV = m_cellScrollArea->verticalScrollBar()->maximum(); if (valueH > maxValueH && x > 0) // Se il valore e' maggiore del max e x>0 // scrollo al massimo valore orizzontale valueH = m_cellScrollArea->horizontalScrollBar()->maximum(); if (valueV > maxValueV && y > 0) // Se il valore e' maggiore del max e y>0 // scrollo al massimo valore verticale valueV = m_cellScrollArea->verticalScrollBar()->maximum(); m_cellScrollArea->horizontalScrollBar()->setValue(valueH); m_cellScrollArea->verticalScrollBar()->setValue(valueV); } //----------------------------------------------------------------------------- int XsheetViewer::getColumnScrollValue() { return m_columnScrollArea->horizontalScrollBar()->value(); } //----------------------------------------------------------------------------- void XsheetViewer::onPrepareToScrollOffset(const QPointF &offset) { refreshContentSize((int)offset.x(), (int)offset.y()); } //----------------------------------------------------------------------------- void XsheetViewer::onZoomScrollAdjust(QPointF &offset, bool toZoom) { double frameZoomFactor = (double)getFrameZoomFactor(); if (orientation()->isVerticalTimeline()) { // toZoom = true: Adjust standardized offset down to zoom factor // toZoom = false: Adjust zoomed offset up to standardized offset double newY; if (toZoom) newY = (offset.y() * frameZoomFactor) / 100.0; else newY = (offset.y() * 100.0) / frameZoomFactor; offset.setY(newY); } else { // toZoom = true: Adjust standardized offset down to zoom factor // toZoom = false: Adjust zoomed offset up to standardized offset double newX; if (toZoom) newX = (offset.x() * frameZoomFactor) / 100.0; else newX = (offset.x() * 100.0) / frameZoomFactor; offset.setX(newX); } } //----------------------------------------------------------------------------- void XsheetViewer::setAutoPanSpeed(const QPoint &speed) { bool wasAutoPanning = isAutoPanning(); m_autoPanSpeed = speed; if (isAutoPanning() && !wasAutoPanning && m_timerId == 0) m_timerId = startTimer(40); else if (!isAutoPanning() && wasAutoPanning && m_timerId != 0) { killTimer(m_timerId); m_timerId = 0; } } //----------------------------------------------------------------------------- static int getAutoPanSpeed(int pixels) { int f = 40; return std::min(100, (f - 1 + pixels * f) / 100); } //----------------------------------------------------------------------------- void XsheetViewer::setAutoPanSpeed(const QRect &widgetBounds, const QPoint &mousePos) { QPoint speed; int limit = 100, factor = 30; if (mousePos.x() < widgetBounds.left()) speed.setX(-getAutoPanSpeed(widgetBounds.left() - mousePos.x())); else if (mousePos.x() > widgetBounds.right()) speed.setX(getAutoPanSpeed(mousePos.x() - widgetBounds.right())); if (mousePos.y() < widgetBounds.top()) speed.setY(-getAutoPanSpeed(widgetBounds.top() - mousePos.y())); else if (mousePos.y() > widgetBounds.bottom()) speed.setY(getAutoPanSpeed(mousePos.y() - widgetBounds.bottom())); setAutoPanSpeed(speed); m_lastAutoPanPos = mousePos; } //----------------------------------------------------------------------------- void XsheetViewer::timerEvent(QTimerEvent *) { if (!isAutoPanning()) return; scroll(m_autoPanSpeed); if (!m_dragTool) return; QMouseEvent mouseEvent(QEvent::MouseMove, m_lastAutoPanPos - m_autoPanSpeed, Qt::NoButton, 0, m_qtModifiers); m_dragTool->onDrag(&mouseEvent); m_lastAutoPanPos += m_autoPanSpeed; } //----------------------------------------------------------------------------- // adjust sizes after scrolling event bool XsheetViewer::refreshContentSize(int dx, int dy) { QSize viewportSize = m_cellScrollArea->viewport()->size(); QPoint offset = m_cellArea->pos(); offset = QPoint(std::min(0, offset.x() - dx), std::min(0, offset.y() - dy)); // what? TXsheet *xsh = getXsheet(); int frameCount = xsh ? xsh->getFrameCount() : 0; int columnCount = xsh ? xsh->getColumnCount() : 0; QPoint contentSize; if (m_orientation->isVerticalTimeline()) contentSize = positionToXY(CellPosition(frameCount + 1, columnCount + 1)); else { int firstCol = Preferences::instance()->isXsheetCameraColumnVisible() ? -1 : 0; contentSize = positionToXY(CellPosition(frameCount + 1, firstCol)); ColumnFan *fan = xsh->getColumnFan(m_orientation); contentSize.setY(contentSize.y() + 1 + (fan->isActive(firstCol) ? m_orientation->cellHeight() : m_orientation->foldedCellSize())); } QSize actualSize(contentSize.x(), contentSize.y()); int x = viewportSize.width() - offset.x(); // wtf is going on int y = viewportSize.height() - offset.y(); if (x > actualSize.width()) actualSize.setWidth(x); if (m_orientation->isVerticalTimeline() && y > actualSize.height()) actualSize.setHeight(y); if (actualSize == m_cellArea->size()) return false; else { const Orientation *o = orientation(); NumberRange allLayer = o->layerSide(QRect(QPoint(0, 0), actualSize)); NumberRange allFrame = o->frameSide(QRect(QPoint(0, 0), actualSize)); NumberRange headerLayer = o->range(PredefinedRange::HEADER_LAYER); NumberRange headerFrame = o->range(PredefinedRange::HEADER_FRAME); m_isComputingSize = true; m_noteArea->setFixedSize(o->rect(PredefinedRect::NOTE_AREA).size()); m_cellArea->setFixedSize(actualSize); m_rowArea->setFixedSize(o->frameLayerRect(allFrame, headerLayer).size()); m_columnArea->setFixedSize(o->frameLayerRect(headerFrame, allLayer).size()); m_isComputingSize = false; return true; } } //----------------------------------------------------------------------------- // call when in doubt void XsheetViewer::updateAreeSize() { const Orientation *o = orientation(); QRect viewArea(QPoint(0, 0), m_cellScrollArea->geometry() .adjusted(0, 0, -XsheetGUI::SCROLLBAR_WIDTH, -XsheetGUI::SCROLLBAR_WIDTH) .size()); QPoint areaFilled(0, 0); TXsheet *xsh = getXsheet(); if (xsh) { if (o->isVerticalTimeline()) areaFilled = positionToXY( CellPosition(xsh->getFrameCount() + 1, xsh->getColumnCount() + 1)); else { int firstCol = Preferences::instance()->isXsheetCameraColumnVisible() ? -1 : 0; areaFilled = positionToXY(CellPosition(xsh->getFrameCount() + 1, firstCol)); ColumnFan *fan = xsh->getColumnFan(m_orientation); areaFilled.setY(areaFilled.y() + 1 + (fan->isActive(firstCol) ? o->cellHeight() : o->foldedCellSize())); } } if (viewArea.width() < areaFilled.x()) viewArea.setWidth(areaFilled.x()); if (viewArea.height() < areaFilled.y() || (!o->isVerticalTimeline() && viewArea.height() != areaFilled.y())) viewArea.setHeight(areaFilled.y()); NumberRange allLayer = o->layerSide(viewArea); NumberRange allFrame = o->frameSide(viewArea); NumberRange headerLayer = o->range(PredefinedRange::HEADER_LAYER); NumberRange headerFrame = o->range(PredefinedRange::HEADER_FRAME); m_cellArea->setFixedSize(viewArea.size()); m_rowArea->setFixedSize(o->frameLayerRect(allFrame, headerLayer).size()); m_columnArea->setFixedSize(o->frameLayerRect(headerFrame, allLayer).size()); } //----------------------------------------------------------------------------- int XsheetViewer::colToTimelineLayerAxis(int layer) const { const Orientation *o = orientation(); TXsheet *xsh = getXsheet(); if (!xsh) return 0; ColumnFan *fan = xsh->getColumnFan(o); int yBottom = o->colToLayerAxis(layer, fan) + (fan->isActive(layer) ? o->cellHeight() : o->foldedCellSize()) - 1; int columnCount = std::max(1, xsh->getColumnCount()); int layerHeightActual = m_columnArea->height() - 2; // o->colToLayerAxis(columnCount, fan) - 1; return layerHeightActual - yBottom; } //----------------------------------------------------------------------------- CellPosition XsheetViewer::xyToPosition(const QPoint &point) const { const Orientation *o = orientation(); QPoint usePoint = point; TXsheet *xsh = getXsheet(); if (!xsh) return CellPosition(0, 0); ColumnFan *fan = xsh->getColumnFan(o); if (o->isVerticalTimeline()) usePoint.setY((usePoint.y() * 100) / getFrameZoomFactor()); else usePoint.setX((usePoint.x() * 100) / getFrameZoomFactor()); if (o->isVerticalTimeline()) return o->xyToPosition(usePoint, fan); // For timeline mode, we need to base the Y axis on the bottom of the column // area // since the layers are flipped int columnCount = std::max(1, xsh->getColumnCount()); int colAreaHeight = o->colToLayerAxis(columnCount, fan); usePoint.setY(colAreaHeight - usePoint.y()); CellPosition resultCP = o->xyToPosition(usePoint, fan); if (point.y() > colAreaHeight) { int colsBelow = ((point.y() - colAreaHeight) / o->cellHeight()) + 1; resultCP.setLayer(-colsBelow); } return resultCP; } CellPosition XsheetViewer::xyToPosition(const TPoint &point) const { return xyToPosition(QPoint(point.x, point.y)); } CellPosition XsheetViewer::xyToPosition(const TPointD &point) const { return xyToPosition(QPoint((int)point.x, (int)point.y)); } //----------------------------------------------------------------------------- QPoint XsheetViewer::positionToXY(const CellPosition &pos) const { const Orientation *o = orientation(); TXsheet *xsh = getXsheet(); if (!xsh) return QPoint(0, 0); ColumnFan *fan = xsh->getColumnFan(o); QPoint usePoint = o->positionToXY(pos, fan); if (o->isVerticalTimeline()) usePoint.setY((usePoint.y() * getFrameZoomFactor()) / 100); else usePoint.setX((usePoint.x() * getFrameZoomFactor()) / 100); if (o->isVerticalTimeline()) return usePoint; // For timeline mode, we need to base the Y axis on the bottom of the column // area // since the layers are flipped usePoint.setY(usePoint.y() - o->cellHeight() + (fan->isActive(pos.layer()) ? o->cellHeight() : o->foldedCellSize())); int columnCount = std::max(1, xsh->getColumnCount()); int colsHeight = o->colToLayerAxis(columnCount, fan); if (colsHeight) usePoint.setY(colsHeight - usePoint.y() - o->cellHeight()); else usePoint.setY(0); return usePoint; } int XsheetViewer::columnToLayerAxis(int layer) const { const Orientation *o = orientation(); TXsheet *xsh = getXsheet(); if (!xsh) return 0; if (o->isVerticalTimeline()) return o->colToLayerAxis(layer, xsh->getColumnFan(o)); else return colToTimelineLayerAxis(layer); } int XsheetViewer::rowToFrameAxis(int frame) const { int result = orientation()->rowToFrameAxis(frame); // if (!orientation()->isVerticalTimeline()) result = (result * getFrameZoomFactor()) / 100; return result; } //----------------------------------------------------------------------------- CellRange XsheetViewer::xyRectToRange(const QRect &rect) const { CellPosition topLeft = xyToPosition(rect.topLeft()); CellPosition bottomRight = xyToPosition(rect.bottomRight()); return CellRange(topLeft, bottomRight); } //----------------------------------------------------------------------------- QRect XsheetViewer::rangeToXYRect(const CellRange &range) const { QPoint from = positionToXY(range.from()); QPoint to = positionToXY(range.to()); QPoint topLeft = QPoint(std::min(from.x(), to.x()), std::min(from.y(), to.y())); QPoint bottomRight = QPoint(std::max(from.x(), to.x()), std::max(from.y(), to.y())); return QRect(topLeft, bottomRight); } //----------------------------------------------------------------------------- void XsheetViewer::drawPredefinedPath(QPainter &p, PredefinedPath which, const CellPosition &pos, optional fill, optional outline) const { QPoint xy = positionToXY(pos); QPainterPath path = orientation()->path(which).translated(xy); if (fill) p.fillPath(path, QBrush(*fill)); if (outline) { p.setPen(*outline); p.drawPath(path); } } //----------------------------------------------------------------------------- void XsheetViewer::drawPredefinedPath(QPainter &p, PredefinedPath which, QPoint xy, optional fill, optional outline) const { QPainterPath path = orientation()->path(which).translated(xy); if (fill) p.fillPath(path, QBrush(*fill)); if (outline) { p.setPen(*outline); p.drawPath(path); } } //----------------------------------------------------------------------------- bool XsheetViewer::areCellsSelectedEmpty() { int r0, c0, r1, c1; getCellSelection()->getSelectedCells(r0, c0, r1, c1); int i, j; for (i = r0; i <= r1; i++) for (j = c0; j <= c1; j++) if (!getXsheet()->getCell(i, j).isEmpty()) return false; return true; } //----------------------------------------------------------------------------- bool XsheetViewer::areSoundCellsSelected() { int r0, c0, r1, c1; getCellSelection()->getSelectedCells(r0, c0, r1, c1); if (c0 < 0) return false; int i, j; for (i = r0; i <= r1; i++) for (j = c0; j <= c1; j++) { TXshCell cell = getXsheet()->getCell(i, j); if (cell.isEmpty() || cell.getSoundLevel()) continue; return false; } return !areCellsSelectedEmpty(); } //----------------------------------------------------------------------------- bool XsheetViewer::areSoundTextCellsSelected() { int r0, c0, r1, c1; getCellSelection()->getSelectedCells(r0, c0, r1, c1); if (c0 < 0) return false; int i, j; for (i = r0; i <= r1; i++) for (j = c0; j <= c1; j++) { TXshCell cell = getXsheet()->getCell(i, j); if (cell.isEmpty() || cell.getSoundTextLevel()) continue; return false; } return !areCellsSelectedEmpty(); } //----------------------------------------------------------------------------- bool XsheetViewer::areCameraCellsSelected() { int r0, c0, r1, c1; getCellSelection()->getSelectedCells(r0, c0, r1, c1); return c0 < 0; } //----------------------------------------------------------------------------- void XsheetViewer::setScrubHighlight(int row, int startRow, int col) { if (m_scrubCol == -1) m_scrubCol = col; m_scrubRow0 = std::min(row, startRow); m_scrubRow1 = std::max(row, startRow); return; } //----------------------------------------------------------------------------- void XsheetViewer::resetScrubHighlight() { m_scrubCol = m_scrubRow0 = m_scrubRow1 = -1; return; } //----------------------------------------------------------------------------- void XsheetViewer::getScrubHeighlight(int &R0, int &R1) { R0 = m_scrubRow0; R1 = m_scrubRow1; return; } //----------------------------------------------------------------------------- bool XsheetViewer::isScrubHighlighted(int row, int col) { if (m_scrubCol == col && m_scrubRow0 <= row && row <= m_scrubRow1) return true; return false; } //----------------------------------------------------------------------------- void XsheetViewer::showEvent(QShowEvent *) { m_frameScroller.registerFrameScroller(); if (m_isCurrentFrameSwitched) onCurrentFrameSwitched(); if (m_isCurrentColumnSwitched) onCurrentColumnSwitched(); m_isCurrentFrameSwitched = false; TApp *app = TApp::instance(); bool ret = connect(app->getCurrentColumn(), SIGNAL(columnIndexSwitched()), this, SLOT(onCurrentColumnSwitched())); ret = ret && connect(app->getCurrentFrame(), SIGNAL(frameSwitched()), this, SLOT(onCurrentFrameSwitched())); ret = ret && connect(app->getCurrentFrame(), SIGNAL(isPlayingStatusChanged()), this, SLOT(onPlayingStatusChanged())); ret = ret && connect(app->getCurrentFrame(), SIGNAL(scrubStopped()), this, SLOT(onScrubStopped())); ret = ret && connect(app->getCurrentObject(), SIGNAL(objectChanged(bool)), this, SLOT(updateAllAree(bool))); TSceneHandle *sceneHandle = app->getCurrentScene(); ret = ret && connect(sceneHandle, SIGNAL(sceneSwitched()), this, SLOT(onSceneSwitched())); ret = ret && connect(sceneHandle, SIGNAL(nameSceneChanged()), this, SLOT(changeWindowTitle())); ret = ret && connect(sceneHandle, SIGNAL(preferenceChanged(const QString &)), this, SLOT(onPreferenceChanged(const QString &))); TXsheetHandle *xsheetHandle = app->getCurrentXsheet(); ret = ret && connect(xsheetHandle, SIGNAL(xsheetSwitched()), this, SLOT(updateAllAree())); ret = ret && connect(xsheetHandle, SIGNAL(xsheetSwitched()), this, SLOT(resetXsheetNotes())); ret = ret && connect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(onXsheetChanged())); ret = ret && connect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(changeWindowTitle())); ret = ret && connect(app->getCurrentSelection(), SIGNAL(selectionSwitched(TSelection *, TSelection *)), this, SLOT(onSelectionSwitched(TSelection *, TSelection *))); // update titlebar when the cell selection region is changed ret = ret && connect(app->getCurrentSelection(), SIGNAL(selectionChanged(TSelection *)), this, SLOT(onSelectionChanged(TSelection *))); // show the current level name to title bar ret = ret && connect(app->getCurrentLevel(), SIGNAL(xshLevelSwitched(TXshLevel *)), this, SLOT(changeWindowTitle())); ret = ret && connect(IconGenerator::instance(), SIGNAL(iconGenerated()), this, SLOT(updateColumnArea())); assert(ret); positionSections(); refreshContentSize(0, 0); updateAllAree(); changeWindowTitle(); xsheetHandle->notifyZoomScaleChanged(m_frameZoomFactor); } //----------------------------------------------------------------------------- void XsheetViewer::hideEvent(QHideEvent *) { m_frameScroller.unregisterFrameScroller(); TApp *app = TApp::instance(); disconnect(app->getCurrentColumn(), SIGNAL(columnIndexSwitched()), this, SLOT(onCurrentColumnSwitched())); disconnect(app->getCurrentFrame(), SIGNAL(frameSwitched()), this, SLOT(onCurrentFrameSwitched())); disconnect(app->getCurrentFrame(), SIGNAL(scrubStopped()), this, SLOT(onScrubStopped())); disconnect(app->getCurrentObject(), SIGNAL(objectChanged(bool)), this, SLOT(updateAllAree(bool))); TSceneHandle *sceneHandle = app->getCurrentScene(); disconnect(sceneHandle, SIGNAL(sceneSwitched()), this, SLOT(onSceneSwitched())); disconnect(sceneHandle, SIGNAL(nameSceneChanged()), this, SLOT(changeWindowTitle())); TXsheetHandle *xsheetHandle = app->getCurrentXsheet(); disconnect(xsheetHandle, SIGNAL(xsheetSwitched()), this, SLOT(updateAllAree())); disconnect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(onXsheetChanged())); disconnect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(changeWindowTitle())); disconnect(app->getCurrentSelection(), SIGNAL(selectionSwitched(TSelection *, TSelection *)), this, SLOT(onSelectionSwitched(TSelection *, TSelection *))); disconnect(app->getCurrentSelection(), SIGNAL(selectionChanged(TSelection *)), this, SLOT(onSelectionChanged(TSelection *))); disconnect(app->getCurrentLevel(), SIGNAL(xshLevelSwitched(TXshLevel *)), this, SLOT(changeWindowTitle())); disconnect(IconGenerator::instance(), SIGNAL(iconGenerated()), this, SLOT(updateColumnArea())); xsheetHandle->notifyZoomScaleChanged(100); } //----------------------------------------------------------------------------- void XsheetViewer::resizeEvent(QResizeEvent *event) { positionSections(); //(New Layout Manager) introduced automatic refresh refreshContentSize( 0, 0); // Don't updateAreeSize because you have to account scrollbars updateAllAree(); } //----------------------------------------------------------------------------- void XsheetViewer::wheelEvent(QWheelEvent *event) { switch (event->source()) { case Qt::MouseEventNotSynthesized: { if (0 != (event->modifiers() & Qt::ControlModifier) && event->angleDelta().y() != 0) { QPoint pos(event->pos().x() - m_columnArea->geometry().width() + m_cellArea->visibleRegion().boundingRect().left(), event->pos().y()); int targetFrame = xyToPosition(pos).frame(); int newFactor = getFrameZoomFactor() + ((event->angleDelta().y() > 0 ? 1 : -1) * 10); if (newFactor > XsheetGUI::ZOOM_FACTOR_MAX) newFactor = XsheetGUI::ZOOM_FACTOR_MAX; else if (newFactor < XsheetGUI::ZOOM_FACTOR_MIN) newFactor = XsheetGUI::ZOOM_FACTOR_MIN; zoomOnFrame(targetFrame, newFactor); event->accept(); return; } int markerDistance = 0, markerOffset = 0; TApp::instance() ->getCurrentScene() ->getScene() ->getProperties() ->getMarkers(markerDistance, markerOffset); if (event->angleDelta().x() == 0) { // vertical scroll if (!orientation()->isVerticalTimeline()) markerDistance = 1; int scrollPixels = (event->angleDelta().y() > 0 ? 1 : -1) * markerDistance * orientation()->cellHeight(); scroll(QPoint(0, -scrollPixels)); } else { // horizontal scroll if (orientation()->isVerticalTimeline()) markerDistance = 1; int scrollPixels = (event->angleDelta().x() > 0 ? 1 : -1) * markerDistance * orientation()->cellWidth(); scroll(QPoint(-scrollPixels, 0)); } break; } case Qt::MouseEventSynthesizedBySystem: // macbook touch-pad { QPoint numPixels = event->pixelDelta(); QPoint numDegrees = event->angleDelta() / 8; if (!numPixels.isNull()) { scroll(-numPixels); } else if (!numDegrees.isNull()) { QPoint numSteps = numDegrees / 15; scroll(-numSteps); } break; } default: // Qt::MouseEventSynthesizedByQt, // Qt::MouseEventSynthesizedByApplication { std::cout << ""not supported event: Qt::MouseEventSynthesizedByQt, "" ""Qt::MouseEventSynthesizedByApplication"" << std::endl; break; } } // end switch } //----------------------------------------------------------------------------- void XsheetViewer::keyPressEvent(QKeyEvent *event) { struct Locals { XsheetViewer *m_this; void scrollVertTo(double y, const QRect &visibleRect) { int deltaY = (y < visibleRect.top()) ? y - visibleRect.top() : y - visibleRect.bottom(); m_this->scroll(QPoint(0, deltaY)); } void scrollHorizTo(double x, const QRect &visibleRect) { int deltaX = (x < visibleRect.left()) ? x - visibleRect.left() : x - visibleRect.right(); m_this->scroll(QPoint(deltaX, 0)); } } locals = {this}; if (changeFrameSkippingHolds(event)) return; int frameCount = getXsheet()->getFrameCount(); CellPosition now(getCurrentRow(), getCurrentColumn()); CellPosition shift = orientation()->arrowShift(event->key()); CellPosition stride(1, 1); // stride in row and column axes TCellSelection *cellSel = dynamic_cast(TSelection::getCurrent()); int firstCol = Preferences::instance()->isXsheetCameraColumnVisible() ? -1 : 0; // Use arrow keys to shift the cell selection. Ctrl + arrow keys to resize the // selection range. if (Preferences::instance()->isUseArrowKeyToShiftCellSelectionEnabled() && cellSel && !cellSel->isEmpty()) { int r0, c0, r1, c1; cellSel->getSelectedCells(r0, c0, r1, c1); stride.setFrame(cellSel->getSelectedCells().getRowCount()); if (m_cellArea->isControlPressed()) { // resize if (r0 == r1 && shift.frame() < 0) return; if (c0 == c1 && shift.layer() < firstCol) return; cellSel->selectCells(r0, c0, r1 + shift.frame(), c1 + shift.layer()); updateCells(); TApp::instance()->getCurrentSelection()->notifySelectionChanged(); return; } else { // shift CellPosition offset(shift * stride); int movedR0 = std::max(0, r0 + offset.frame()); int movedC0 = std::max(firstCol, c0 + offset.layer()); int diffFrame = movedR0 - r0; int diffLayer = movedC0 - c0; cellSel->selectCells(r0 + diffFrame, c0 + diffLayer, r1 + diffFrame, c1 + diffLayer); TApp::instance()->getCurrentSelection()->notifySelectionChanged(); } } if (shift) { now = now + shift * stride; now.ensureValid(); if (now.layer() < firstCol) now.setLayer(firstCol); setCurrentRow(now.frame()); setCurrentColumn(now.layer()); return; } switch (int key = event->key()) { case Qt::Key_Control: // display the upper-directional smart tab only when the ctrl key is pressed m_cellArea->onControlPressed(true); m_columnArea->onControlPressed(true); m_layerFooterPanel->onControlPressed(true); break; default: { QRect visibleRect = m_cellArea->visibleRegion().boundingRect(); int visibleRowCount = visibleRect.height() / orientation()->cellHeight(); switch (key) { case Qt::Key_PageUp: locals.scrollVertTo( visibleRect.top() - visibleRowCount * orientation()->cellHeight(), visibleRect); break; case Qt::Key_PageDown: locals.scrollVertTo( visibleRect.bottom() + visibleRowCount * orientation()->cellHeight(), visibleRect); break; case Qt::Key_Home: if (orientation()->isVerticalTimeline()) locals.scrollVertTo(0, visibleRect); else locals.scrollHorizTo(0, visibleRect); break; case Qt::Key_End: if (orientation()->isVerticalTimeline()) { int y = (((frameCount + 1) * orientation()->cellHeight()) * getFrameZoomFactor()) / 100; locals.scrollVertTo(y, visibleRect); } else { int x = (((frameCount + 1) * orientation()->cellWidth()) * getFrameZoomFactor()) / 100; locals.scrollHorizTo(x, visibleRect); } break; } break; } } } //----------------------------------------------------------------------------- // display the upper-directional smart tab only when the ctrl key is pressed void XsheetViewer::keyReleaseEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Control) { m_cellArea->onControlPressed(false); m_columnArea->onControlPressed(false); m_layerFooterPanel->onControlPressed(false); } } //----------------------------------------------------------------------------- void XsheetViewer::leaveEvent(QEvent *) { m_panningArmed = false; } //----------------------------------------------------------------------------- void XsheetViewer::enterEvent(QEvent *) { m_panningArmed = false; m_cellArea->onControlPressed(false); m_columnArea->onControlPressed(false); TApp *app = TApp::instance(); app->setCurrentXsheetViewer(this); } //----------------------------------------------------------------------------- /*! scroll the cell area to make a cell at (row,col) visible */ void XsheetViewer::scrollTo(int row, int col) { QRect visibleRect = m_cellArea->visibleRegion().boundingRect(); QPoint topLeft = positionToXY(CellPosition(row, col)); QRect cellRect( topLeft, QSize(orientation()->cellWidth(), orientation()->cellHeight())); int deltaX = 0; int deltaY = 0; if (cellRect.left() < visibleRect.left()) deltaX = cellRect.left() - visibleRect.left(); else if (cellRect.right() > visibleRect.right()) deltaX = cellRect.left() - visibleRect.left(); if (cellRect.top() < visibleRect.top()) deltaY = cellRect.top() - visibleRect.top(); else if (cellRect.bottom() > visibleRect.bottom()) deltaY = cellRect.bottom() - visibleRect.bottom(); if (deltaX != 0 || deltaY != 0) { scroll(QPoint(deltaX, deltaY)); } } //----------------------------------------------------------------------------- void XsheetViewer::onSceneSwitched() { refreshContentSize(0, 0); updateAreeSize(); updateAllAree(); clearNoteWidgets(); m_noteArea->updateButtons(); m_layerFooterPanel->m_noteArea->updateButtons(); } //----------------------------------------------------------------------------- void XsheetViewer::onXsheetChanged() { refreshContentSize(0, 0); updateAllAree(); } //----------------------------------------------------------------------------- void XsheetViewer::onPreferenceChanged(const QString &prefName) { if (prefName == ""QuickToolbar"") { positionSections(); refreshContentSize(0, 0); } else if (prefName == ""XsheetCamera"") { refreshContentSize(0, 0); } } //----------------------------------------------------------------------------- void XsheetViewer::onCurrentFrameSwitched() { int row = TApp::instance()->getCurrentFrame()->getFrame(); QRect visibleRect = m_cellArea->visibleRegion().boundingRect(); if (visibleRect.isEmpty()) { m_isCurrentFrameSwitched = true; return; } m_isCurrentFrameSwitched = false; scrollToRow(row); } //----------------------------------------------------------------------------- void XsheetViewer::onPlayingStatusChanged() { if (!Preferences::instance()->isXsheetAutopanEnabled()) onCurrentFrameSwitched(); } //----------------------------------------------------------------------------- void XsheetViewer::onCurrentColumnSwitched() { int col = TApp::instance()->getCurrentColumn()->getColumnIndex(); QRect visibleRect = m_columnArea->visibleRegion().boundingRect(); if (visibleRect.isEmpty()) { m_isCurrentColumnSwitched = true; return; } m_isCurrentColumnSwitched = false; scrollToColumn(col); } //----------------------------------------------------------------------------- void XsheetViewer::scrollToColumn(int col) { int colNext = col + (m_orientation->isVerticalTimeline() ? 1 : -1); if (colNext < 0) colNext = -1; int x0 = columnToLayerAxis(col); int x1 = columnToLayerAxis(colNext); if (orientation()->isVerticalTimeline()) scrollToHorizontalRange(x0, x1); else { if (colNext == col) x1 += m_orientation->cellHeight(); scrollToVerticalRange(x0, x1); } } //----------------------------------------------------------------------------- void XsheetViewer::scrollToHorizontalRange(int x0, int x1) { QRect visibleRect = m_cellArea->visibleRegion().boundingRect(); if (visibleRect.isEmpty()) return; int visibleLeft = visibleRect.left(); int visibleRight = visibleRect.right(); if (visibleLeft > x0) { // If they are out of left visible region int deltaX = x0 - visibleLeft; if (!TApp::instance()->getCurrentFrame()->isPlaying() || Preferences::instance()->isXsheetAutopanEnabled()) { scroll(QPoint(deltaX, 0)); return; } } if (visibleRight < x1) { // If they are out of right visible region int deltaX = x1 + 2 - visibleRight; if (!TApp::instance()->getCurrentFrame()->isPlaying() || Preferences::instance()->isXsheetAutopanEnabled()) { scroll(QPoint(deltaX, 0)); return; } } if (orientation()->isVerticalTimeline()) updateCellColumnAree(); else updateCellRowAree(); } //----------------------------------------------------------------------------- void XsheetViewer::scrollToRow(int row) { int y0 = rowToFrameAxis(row); int y1 = rowToFrameAxis(row + 1); if (orientation()->isVerticalTimeline()) scrollToVerticalRange(y0, y1); else scrollToHorizontalRange(y0, y1); } //----------------------------------------------------------------------------- void XsheetViewer::scrollToVerticalRange(int y0, int y1) { int yMin = std::min(y0, y1); int yMax = std::max(y0, y1); QRect visibleRect = m_cellArea->visibleRegion().boundingRect(); if (visibleRect.isEmpty()) return; int visibleTop = visibleRect.top(); int visibleBottom = visibleRect.bottom(); if (visibleTop > yMin) { // If they are out of top visible region int deltaY = yMin - visibleTop; if (!TApp::instance()->getCurrentFrame()->isPlaying() || Preferences::instance()->isXsheetAutopanEnabled()) { scroll(QPoint(0, deltaY)); return; } } if (visibleBottom < yMax) { // If they are out of bottom visible region int deltaY = yMax + 2 - visibleBottom; if (!TApp::instance()->getCurrentFrame()->isPlaying() || Preferences::instance()->isXsheetAutopanEnabled()) { scroll(QPoint(0, deltaY)); return; } } if (orientation()->isVerticalTimeline()) updateCellRowAree(); else updateCellColumnAree(); } //----------------------------------------------------------------------------- void XsheetViewer::onSelectionSwitched(TSelection *oldSelection, TSelection *newSelection) { if ((TSelection *)getCellSelection() == oldSelection) { m_cellArea->update(m_cellArea->visibleRegion()); m_rowArea->update(m_rowArea->visibleRegion()); changeWindowTitle(); } else if ((TSelection *)m_columnSelection == oldSelection) m_columnArea->update(m_columnArea->visibleRegion()); } //----------------------------------------------------------------------------- /*! update display of the cell selection range in title bar */ void XsheetViewer::onSelectionChanged(TSelection *selection) { if ((TSelection *)getCellSelection() == selection) { changeWindowTitle(); if (Preferences::instance()->isInputCellsWithoutDoubleClickingEnabled()) { TCellSelection *cellSel = getCellSelection(); if (cellSel->isEmpty()) m_cellArea->hideRenameField(); else m_cellArea->showRenameField( cellSel->getSelectedCells().m_r0, cellSel->getSelectedCells().m_c0, cellSel->getSelectedCells().getColCount() > 1); } } } //----------------------------------------------------------------------------- void XsheetViewer::updateAllAree(bool isDragging) { m_cellArea->update(m_cellArea->visibleRegion()); if (!isDragging) { m_rowArea->update(m_rowArea->visibleRegion()); m_columnArea->update(m_columnArea->visibleRegion()); } m_toolbar->update(m_toolbar->visibleRegion()); } //----------------------------------------------------------------------------- void XsheetViewer::updateColumnArea() { m_columnArea->update(m_columnArea->visibleRegion()); } //----------------------------------------------------------------------------- void XsheetViewer::updateCellColumnAree() { if (!m_isComputingSize) refreshContentSize(0, 0); m_columnArea->update(m_columnArea->visibleRegion()); m_cellArea->update(m_cellArea->visibleRegion()); } //----------------------------------------------------------------------------- void XsheetViewer::updateCellRowAree() { if (!m_isComputingSize) refreshContentSize(0, 0); m_rowArea->update(m_rowArea->visibleRegion()); m_cellArea->update(m_cellArea->visibleRegion()); } //----------------------------------------------------------------------------- void XsheetViewer::onScrubStopped() { resetScrubHighlight(); updateCells(); } //----------------------------------------------------------------------------- void XsheetViewer::discardNoteWidget() { if (m_currentNoteIndex == -1) return; TXshNoteSet *notes = getXsheet()->getNotes(); int i; for (i = m_currentNoteIndex + 1; i < m_noteWidgets.size(); i++) { XsheetGUI::NoteWidget *w = m_noteWidgets.at(i); int index = w->getNoteIndex(); w->setNoteIndex(index - 1); w->update(); } delete m_noteWidgets.at(m_currentNoteIndex); m_noteWidgets.removeAt(m_currentNoteIndex); m_noteArea->updateButtons(); m_layerFooterPanel->m_noteArea->updateButtons(); updateCells(); } //----------------------------------------------------------------------------- QList XsheetViewer::getNotesWidget() const { return m_noteWidgets; } //----------------------------------------------------------------------------- void XsheetViewer::addNoteWidget(XsheetGUI::NoteWidget *w) { m_noteWidgets.push_back(w); m_noteArea->updateButtons(); m_layerFooterPanel->m_noteArea->updateButtons(); } //----------------------------------------------------------------------------- int XsheetViewer::getCurrentNoteIndex() const { return m_currentNoteIndex; } //----------------------------------------------------------------------------- void XsheetViewer::setCurrentNoteIndex(int currentNoteIndex) { m_currentNoteIndex = currentNoteIndex; m_noteArea->updateButtons(); m_layerFooterPanel->m_noteArea->updateButtons(); if (currentNoteIndex < 0) return; TXshNoteSet *notes = getXsheet()->getNotes(); int row = notes->getNoteRow(currentNoteIndex); int col = notes->getNoteCol(currentNoteIndex); TPointD pos = notes->getNotePos(currentNoteIndex); QPoint topLeft = positionToXY(CellPosition(row, col)) + QPoint(pos.x, pos.y); // actually xy QSize size(XsheetGUI::NoteWidth, XsheetGUI::NoteHeight); QRect noteRect(topLeft, size); scrollToHorizontalRange(noteRect.left(), noteRect.right()); scrollToVerticalRange(noteRect.top(), noteRect.bottom()); } //----------------------------------------------------------------------------- void XsheetViewer::resetXsheetNotes() { m_noteArea->updateButtons(); m_layerFooterPanel->m_noteArea->updateButtons(); } //----------------------------------------------------------------------------- void XsheetViewer::updateNoteWidgets() { int i; for (i = 0; i < m_noteWidgets.size(); i++) m_noteWidgets.at(i)->update(); if (XsheetGUI::NotePopupWidget) XsheetGUI::NotePopupWidget->update(); updateCells(); } //----------------------------------------------------------------------------- void XsheetViewer::clearNoteWidgets() { int i; for (i = 0; i < m_noteWidgets.size(); i++) delete m_noteWidgets.at(i); m_noteWidgets.clear(); } //----------------------------------------------------------------------------- void XsheetViewer::changeWindowTitle() { TApp *app = TApp::instance(); ToonzScene *scene = app->getCurrentScene()->getScene(); if (!scene || !app->getCurrentFrame()->isEditingScene()) return; TProject *project = scene->getProject(); QString sceneName = QString::fromStdWString(scene->getSceneName()); if (sceneName.isEmpty()) sceneName = tr(""Untitled""); if (app->getCurrentScene()->getDirtyFlag()) sceneName += QString(""*""); QString separator = "" | ""; QString name = tr(""Scene: "") + sceneName; int frameCount = scene->getFrameCount(); name = name + separator + tr(std::to_string(frameCount).c_str()) + (frameCount == 1 ? tr("" Frame"") : tr("" Frames"")); // subXsheet or not ChildStack *childStack = scene->getChildStack(); if (childStack && childStack->getAncestorCount() > 0) { name += tr("" (Sub)""); } // current level name TXshLevel *level = app->getCurrentLevel()->getLevel(); if (level) { QString levelName = QString::fromStdWString(level->getName()); name += separator + tr(""Level: "") + levelName; } // cell selection range if ((TSelection *)getCellSelection() == app->getCurrentSelection()->getSelection() && !getCellSelection()->isEmpty()) { int r0, r1, c0, c1; getCellSelection()->getSelectedCells(r0, c0, r1, c1); name += separator + tr(""Selected: "") + QString::number(r1 - r0 + 1) + ((r1 - r0 + 1 == 1) ? tr("" frame : "") : tr("" frames * "")) + QString::number(c1 - c0 + 1) + ((c1 - c0 + 1 == 1) ? tr("" column"") : tr("" columns"")); } TApp::instance()->setStatusBarFrameInfo(""| "" + name); parentWidget()->setWindowTitle(name); } //----------------------------------------------------------------------------- /*! convert the last one digit of the frame number to alphabet Ex. 12 -> 1B 21 -> 2A 30 -> 3 */ QString XsheetViewer::getFrameNumberWithLetters(int frame) { int letterNum = frame % 10; QChar letter; switch (letterNum) { case 0: letter = QChar(); break; case 1: letter = 'A'; break; case 2: letter = 'B'; break; case 3: letter = 'C'; break; case 4: letter = 'D'; break; case 5: letter = 'E'; break; case 6: letter = 'F'; break; case 7: letter = 'G'; break; case 8: letter = 'H'; break; case 9: letter = 'I'; break; default: letter = QChar(); break; } QString number; if (frame >= 10) { number = QString::number(frame); number.chop(1); } else number = ""0""; return (QChar(letter).isNull()) ? number : number.append(letter); } //----------------------------------------------------------------------------- void XsheetViewer::setFrameDisplayStyle(FrameDisplayStyle style) { m_frameDisplayStyle = style; FrameDisplayStyleInXsheetRowArea = (int)style; } //----------------------------------------------------------------------------- void XsheetViewer::save(QSettings &settings) const { settings.setValue(""orientation"", orientation()->name()); settings.setValue(""frameZoomFactor"", m_frameZoomFactor); } void XsheetViewer::load(QSettings &settings) { QVariant zoomFactor = settings.value(""frameZoomFactor""); QVariant name = settings.value(""orientation""); if (zoomFactor.canConvert(QVariant::Int)) { m_frameZoomFactor = zoomFactor.toInt(); m_layerFooterPanel->setZoomSliderValue(m_frameZoomFactor); } if (name.canConvert(QVariant::String)) { m_orientation = Orientations::byName(name.toString()); emit orientationChanged(orientation()); } } //----------------------------------------------------------------------------- /* TPanel *createXsheetViewer(QWidget *parent) { TPanel *panel = new TPanel(parent); panel->setPanelType(""Xsheet""); panel->setWidget(new XsheetViewer(panel)); return panel; } */ //---------------------------------------------------------------- QList XsheetViewer::availableFramesPerPage() { int frameRate = TApp::instance() ->getCurrentScene() ->getScene() ->getProperties() ->getOutputProperties() ->getFrameRate(); // 1sec, 1.5sec, 2sec, 3sec, 4sec, 6sec QList ret; ret << frameRate; if (frameRate % 2 == 0) ret << frameRate * 3 / 2; ret << frameRate * 2; ret << frameRate * 3; ret << frameRate * 4; ret << frameRate * 6; // visible area size int size = (orientation()->isVerticalTimeline()) ? m_cellScrollArea->viewport()->height() : m_cellScrollArea->viewport()->width(); int scaleMin = (orientation()->isVerticalTimeline()) ? 50 : 20; int scaleMax = 100; int frameMin = (int)std::ceil( (double)size / ((double)orientation()->dimension(PredefinedDimension::FRAME) * (double)scaleMax / 100.0)); int frameMax = (int)std::floor( (double)size / ((double)orientation()->dimension(PredefinedDimension::FRAME) * (double)scaleMin / 100.0)); for (auto itr = ret.begin(); itr != ret.end();) { // erase unavailable items if (*itr < frameMin || *itr > frameMax) { itr = ret.erase(itr); continue; } itr++; } return ret; } //---------------------------------------------------------------- void XsheetViewer::zoomToFramesPerPage(int frames) { int size = (orientation()->isVerticalTimeline()) ? m_cellScrollArea->viewport()->height() : m_cellScrollArea->viewport()->width(); int frameDim = orientation()->dimension(PredefinedDimension::FRAME); double scale = (double)size / ((double)frameDim * (double)frames); // convert to factor value int factor; if (orientation()->isVerticalTimeline()) factor = (int)std::round((0.2 + (scale - 0.5) * 8.0 / 5.0) * 100); else factor = (int)std::round(scale * 100); zoomOnFrame(getCurrentRow(), factor); } //---------------------------------------------------------------- int XsheetViewer::getFrameZoomFactor() const { if (orientation()->isVerticalTimeline()) return 50 + (m_frameZoomFactor - 20) * 5 / 8; return m_frameZoomFactor; } QPoint XsheetViewer::getFrameZoomAdjustment() { // if (orientation()->isVerticalTimeline()) return 0; QRect frameRect = orientation()->rect(PredefinedRect::FRAME_HEADER); int adj; if (orientation()->isVerticalTimeline()) { adj = frameRect.height() - ((frameRect.height() * getFrameZoomFactor()) / 100) - 1; return QPoint(0, std::max(0, adj)); } else { adj = frameRect.width() - ((frameRect.width() * getFrameZoomFactor()) / 100) - 1; return QPoint(std::max(0, adj), 0); } } void XsheetViewer::zoomOnFrame(int frame, int factor) { QPoint xyOrig = positionToXY(CellPosition(frame, -1)); m_frameZoomFactor = factor; m_layerFooterPanel->setZoomSliderValue(m_frameZoomFactor); QPoint xyNew = positionToXY(CellPosition(frame, -1)); scroll(xyNew - xyOrig); TApp::instance()->getCurrentXsheet()->notifyXsheetChanged(); if (orientation()->isVerticalTimeline()) TApp::instance()->getCurrentXsheet()->notifyZoomScaleChanged(factor); m_rowArea->update(); } QColor XsheetViewer::getSelectedColumnTextColor() const { // get colors TPixel currentColumnPixel; Preferences::instance()->getCurrentColumnData(currentColumnPixel); QColor currentColumnColor((int)currentColumnPixel.r, (int)currentColumnPixel.g, (int)currentColumnPixel.b, 255); return currentColumnColor; } QColor XsheetViewer::getCellFocusColor() const { // get colors TPixel currentCellPixel; Preferences::instance()->getCurrentCellData(currentCellPixel); QColor currentCellColor((int)currentCellPixel.r, (int)currentCellPixel.g, (int)currentCellPixel.b, 255); return currentCellColor; } //----------------------------------------------------------------------------- bool XsheetViewer::event(QEvent *e) { if (e->type() != QEvent::KeyPress && e->type() != QEvent::ShortcutOverride && e->type() != QEvent::KeyRelease) return QFrame::event(e); QKeyEvent *keyEvent = static_cast(e); std::string keyStr = QKeySequence(keyEvent->key() + keyEvent->modifiers()) .toString() .toStdString(); QAction *action = CommandManager::instance()->getActionFromShortcut(keyStr); std::string actionId = CommandManager::instance()->getIdFromAction(action); if (actionId != T_Hand) return QFrame::event(e); if (e->type() == QEvent::KeyPress || e->type() == QEvent::ShortcutOverride) { m_panningArmed = true; action->setEnabled(false); m_cellArea->updateCursor(); e->accept(); return true; } else if (e->type() == QEvent::KeyRelease) { if (!keyEvent->isAutoRepeat()) m_panningArmed = false; action->setEnabled(true); m_cellArea->updateCursor(); e->accept(); return true; } return QFrame::event(e); } //============================================================================= // XSheetViewerCommand //----------------------------------------------------------------------------- OpenFloatingPanel openXsheetViewerCommand(MI_OpenXshView, ""Xsheet"", QObject::tr(""Xsheet"")); OpenFloatingPanel openTimelineViewerCommand(MI_OpenTimelineView, ""Timeline"", QObject::tr(""Timeline"")); ",16300,True,2890.320344432325,median "= Volant - Developer Guide :site-section: DeveloperGuide :toc: :toc-title: Table of Contents :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: endif::[] :repoURL: https://github.com/AY1920S2-CS2103T-F09-4/main By: `AY1920S2-CS2103T-F09-4`      Since: `Jan 2020`      Licence: `MIT` == Introduction This document is a Developer Guide written for developers who wish to contribute to or extend our project. It is technical, and explains the inner workings of Volant and how the different components of our application work together. ==== *Reading this Developer Guide* * *Important Notations* + [TIP] This icon denotes useful tips to note of during development. [NOTE] This icon denotes important details to take note of during development. * *Understanding Diagrams* + The diagrams in this Developer Guide are colour coded according to the different components. + image::dg-diagram-legend.png[] ==== == Setting up Refer to the guide <>. == Design [[Design-Architecture]] === Architecture .Architecture Diagram image::ArchitectureDiagram.png[align=""center""] The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component. `Main` has two classes called link:{repoURL}/src/main/java/seedu/location/Main.java[`Main`] and link:{repoURL}/src/main/java/seedu/location/MainApp.java[`MainApp`]. It is responsible for, * At app launch: Initializes the components in the correct sequence, and connects them up with each other. * At shut down: Shuts down the components and invokes cleanup method where necessary. * <> represents a collection of classes used by multiple other components. The following class plays an important role at the architecture level: * `LogsCenter` is used by many classes to write log messages to the App's log file, `volant.log`. The rest of the App consists of four main components. * <>: The UI of the App. * <>: The command executor depending on the view the user is on. * <>: Holds the data of the App in-memory depending in the view the user is on. * <>: Reads data from, and writes data to, the hard disk. Each of the four components * Defines its _API_ in an `interface` with the same name as the Component. * Exposes its functionality using a `{Component Name} Manager` class. For example, the `Logic` component (see the class diagram given below) defines its API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class. ==== Views in Volant There are 4 types of pages/views in this App: `HOME`, `TRIP`, `ITINERARY`, `JOURNAL`. Each view has their own `{Component Name} Manager` classes for both `Logic` and `Model`. These individual `{Component Name} Manager` classes for `Logic` and `Model` provide a context for commands to be executed in, e.g. when the user is on the `HOME` page, the `add` command modifies the trip list, when the user is on the `ITINERARY` page, the `add` command modifies the itinerary. For example, the `JOURNAL` view has its own `JournalLogicManager` and `JournalModelManager` to provide the context for command execution on the `JOURNAL` page. .Class Diagram of the Journal Logic Component image::JournalLogic.png[align=""center""] [discrete] ==== How the architecture components interact with each other The _Sequence Diagram_ below shows how the components interact with each other for the scenario where the user issues the command `back` when in a `TRIP` view. View switching is executed by the `Ui` component. [[view-switch-sequence]] .Component interactions for `home` command in the `JOURNAL` page. image::home-command-sequence.png[align=""center""] The _Sequence Diagram_ below illustrates how the components interact with each other for the scenario where the user issues the command `goto 1` when in a `HOME` page view. View switching is executed by the `Ui` component. .Component interactions for `goto 1` command in the `HOME` page view. image::gotoCommandSequenceDiagram.png[align=""center""] The sections below give more details about each component. [[Design-Ui]] === UI component .Structure of the UI Component when a user is on a `TRIP` page image::UIClassDiagram.png[align=""center""] *API* : link:{repoURL}/src/main/java/seedu/location/ui/Ui.java[`Ui.java`] The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `StatusBarFooter`, `mainPanel` etc. All these, including the `MainWindow`, inherit from the abstract `UiPart` class. The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files that are in the `src/main/resources/view` folder. For example, the layout of the link:{repoURL}/src/main/java/seedu/location/ui/MainWindow.java[`MainWindow`] is specified in link:{repoURL}/src/main/resources/view/MainWindow.fxml[`MainWindow.fxml`] The `UI` component, * Executes user commands using the `Logic` component. * Listens for changes to `Model` data so that the UI can be updated with the modified data. ==== View Switching As there are four different views in Volant. Upon startup of the App, the `mainPanel` is set to `HomePage`. There are certain commands will cause the `MainWindow` display to switch views. For example, `goto`, `back` and `home` navigation commands. When a view is switched, `MainWindow` will do the following: ==== For example, if a user is switching from a `TRIP` view to the `HOME` view through the command, `back`. . Reassign the `Logic` component from `TripPageLogicManager` to a new `HomePageLogicManager`. . Reassign the `Model` component from `TripPageModelManager` to a new `HomePageModelManager`. . Reassign the value of `StackPane` `mainPanel` from `TripPage` to `HomePage`. <> ==== _More details on the implementation of view switching can be found in <>._ [[Design-Logic]] === Logic component [[fig-LogicClassDiagram1]] .Structure of the Logic Component image::JournalLogic.png[align=""center""] *API* : link:https://github.com/AY1920S2-CS2103T-F09-4/main/blob/master/src/main/java/seedu/volant/commons/logic/Logic.java[`Logic.java`] . `Logic` uses the `JournalInputParser` class of the current feature to parse the user command. . This results in a `Command` object which is executed by the `JournalLogicManager` of the current feature. . The command execution can affect the `Model` of the current feature (e.g. adding a trip). . The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`. . In addition, the `CommandResult` object can also instruct the `Ui` to perform certain actions, such as displaying help to the user. Given below is the Sequence Diagram for interactions within the `Logic` component of the Itinerary feature for the `execute(""delete 1"")` API call. .Interactions Inside the Logic Component for the `delete 1` Command image::DeleteItinerary.png[align=""center""] [[Design-Model]] === Model component .Class Diagram for the Model component on the `HOME` page image::HomeClassDiagram.png[align=""center""] .Structure of the Model Component in Journal image::JournalModelDiagram.png[align=""center""] *API* : link:{repoURL}/src/main/java/seedu/location/model/Model.java[`Model.java`] The `Model` for `JOURNAL`, * stores a `UserPref` object that represents the user's preferences. * stores an `Entry` 's data. * exposes an unmodifiable `ObservableList` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. * does not depend on any of the other three components. .Structure of the Model Component in Itinerary image::ItineraryModelDiagram.png[align=""center""] The `Model` for `ITINERARY`, *API* : link:https://github.com/AY1920S2-CS2103T-F09-4/main/blob/master/src/main/java/seedu/volant/commons/model/Model.java[`Model.java`] * stores a `UserPref` object that represents the user's preferences. * stores an `Activity` 's data. * exposes an unmodifiable `ObservableList` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. * does not depend on any of the other three components. [[Design-Storage]] === Storage component .Structure of the Storage Component image::StorageClassDiagram.png[align=""center""] *API* : link:https://github.com/AY1920S2-CS2103T-F09-4/main/blob/master/src/main/java/seedu/volant/commons/storage/Storage.java[`Storage.java`] The `Storage` component, * can save `UserPref` objects in json format and read it back. * can save the `XYZList` data in json format and read it back. [[Design-Commons]] === Common classes Classes used by multiple components are in the `seedu.volant.commons` package. == Implementation This section describes some noteworthy details on how certain features are implemented. [[implementation-view-switching]] === View Switching for Navigation Commands The entire process of view switching is executed in the `MainWindow.java` class. [TIP] ==== *List of Navigation Commands* * `goto` on the `HOME` page * `goto` on the `TRIP` page * `back` * `home` ==== ==== Implementation Each `CommandResult` from an execution in the `MainWindow` class stores data on *if a command is a navigation command or not, and which navigation command it is.* If the command is a navigation command, the `MainWindow` will execute the appropriate functions to facilitate view switching. In the view switching process, the `MainWindow` will do the following: + . Switch the logic component of the program to the logic component of the next page . Switch the model component of the program to the model component of the next page . Switch the current storage of the program to the storage component of the next page . Load the GUI components for the next page For example, for the `back` command, the `MainWindow`: .Activity diagram for view switching process in `MainWindow` for `back` command image::back-activity-diagram.png[] ==== Design Considerations Pros: + * As each page has its own components, the back end of the program is neater and better abstracted. * Specialised logic components for each page allow for the same keywords to be used (e.g `add`, `delete`) on certain pages. Cons: + * There are many steps to switching views * If there are more pages, there will be many logic and model components to keep track of. ==== Special Cases * When `back` command is used in the <>, this would not have any effect on the current GUI being displayed. * When the `home` command is used in the <>, this would not have any effect on the current GUI being displayed as the user is already on the HOME page. === Specific Help Windows for different pages ==== Implementation Each page in Volant has its own `{Page}HelpWindow` class. <>, the `MainWindow` will create a new `{Page}HelpWindow` containing details of the commands that can be used on that page. ==== Design Considerations ===== Aspect: Syntax of the find command * **Alternative 1 (current choice):** Help Window specifically details the commands that can be used on the page that the user is currently on. ** Pros: Very specific and allows added convenience for users when they want to use commands with many fields that they cannot remember without having to refer to the User Guide. ** Cons: Every single page has to have its own class file for the Help Window, if there are many pages, there will be many files to keep track of. * **Alternative 2:** Use a general Help Window that lists every single command for every page in Volant ** Pros: Only one Help Window class file needed and it is easy to implement. ** Cons: If all the commands are detailed on a single long Help Window, the user will have to inconveniently scroll through the window to reach the section that details commands for the page that they are on. === Adding a trip in Home Page ==== Implementation Adding a trip The add trip feature allows user to add a trip to Volant. This feature is facilitated by `HomeInputParser`, `AddCommandParser`, and `AddCommand`. Given below is an example usage scenario and how the trip add mechanism behaves at each step: 1. The user executes the add command in `HOME` page and provides the required metadata in the correct format to be added. 2. `HomeInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `AddCommandParser` parses the remaining input by the user for metadata denoted with prefixes. 4. `AddCommandParser` checks if the metadata input by the user is in the desired format. 5. `AddCommandParser` creates a new `AddCommand` based on the metadata provided. 6. `HomeLogicManager` executes the `AddCommand`. 7. `HomeModelManager` checks if the new `TRIP` has any logical conflicts with existing `TRIP`(s) 8. `HomeModelManager` adds the module to the `UniqueTripList`. 9. A new folder with the `TRIP` name is created. 10. `HomeLogicManager` updates storage with updated `UniqueTripList`. 11. `MainWindow` receives `CommandResult` from `HomeLogicManager` containing success message to be displayed to user. 12. Trips displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes a add trip command: .Activity Diagram for `add` Command image::AddTripActivityDiagram.png[align=""center""] ==== Design Considerations ===== Aspect: How data is stored * **Alternative 1 (current choice):** Saves the trip details in main volant json folder and create a folder corresponding to `TRIP` name. ** Pros: Easy to implement. ** Cons: Less organised as all trip details are stored in one location. Any error in the way one trip is stored will cause all trips not to be loaded. * **Alternative 2:** Create a individual json file for each trip details. ** Pros: An error in the file of one trip will not affect the loading of other trips. ** Cons: Harder to implement retrieval. === Sorting entries in Journal Page ==== Implementation Sorting journal entries The sort feature allows user to sort the entries in the `JOURNAL` of a trip. This feature is facilitated by `JournalInputParser`, `SortCommandParser`, and `SortCommand`. Given below is an example usage scenario and how the journal sort mechanism behaves at each step: 1. The user executes the sort command in `JOURNAL` page and provides a field which they want the entries to be sorted by. 2. `JournalInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `SortCommandParser` parses the remaining input by the user for field. 4. `SortCommandParser` checks if the field input by the user is a valid field to sort by. 5. `SortCommandParser` creates a new `SortCommand` based on the field provided. 6. `JournalLogicManager` executes the `SortCommand`. 7. `JournalModelManager` sorts the entries according to the input field. 8. `JournalLogicManager` updates storage with updated `UniqueEntryList`. 9. `MainWindow` receives `CommandResult` from `HomeLogicManager` containing success message to be displayed to user. 10. Jounral entries displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarizes what happens when a user executes a sort journal command: .Activity Diagram for `sort` Command image::sortActivityDiagram.png[align=""center""]] === Adding activities in Itinerary Page ==== Implementation Adding an activity The add activity feature allows user to add an activity to a current trip. This feature is faciliated by `ItineraryInputParser`, `AddCommandParser`, and `AddCommand`. Given below is an example usage scenario and how the activity add mechanism behaves at each step: 1. The user executes the add command in `ITINERARY` page and provides the required metadata in the correct format to be added. 2. `ItineraryInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `AddCommandParser` parses the remaining input by the user for metadata denoted with prefixes. 4. `AddCommandParser` checks if the metadata input by the user is in the desired format. 5. `AddCommandParser` creates a new `AddCommand` based on the metadata provided. 6. `ItineraryLogicManager` executes the `AddCommand`. 7. `ItineraryModelManager` checks if the new `ACTIVITY` has any logical conflicts with existing `ACTIVITY`(s) 8. `ItineraryModelManager` adds the activity to the `UniqueActivityList`. 9. The `itinerary.json` file in the current trip folder in storage is updated 10. `ItineraryLogicManager` updates storage with updated `UniqueActivityList`. 11. `MainWindow` receives `CommandResult` from `ItineraryLogicManager` containing success message to be displayed to user. 12. Activities displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarizes what happens when a user executes a add activity command: .Activity Diagram for `add` Command image::AddActivity.png[align=""center""]] ==== Design Considerations ===== Aspect: Prerequisite of the command Since each trip is associated with one itinerary, when the user wants to use the add activity command, a trip must have already been created. This is why the order of the scence switching is important as it disallows user to create an activity that is not associated with any trip. === Finding activities in Itinerary Page ==== Implementation Finding an activity The find activity feature allows user to find one or several activities in the current trip with matching keywords provided. This feature is faciliated by `ItineraryInputParser`, `FindCommandParser`, and `FindCommand`. Given below is an example usage scenario and how the activity find mechanism behaves at each step: 1. The user executes the find command in `ITINERARY` page and provides one or several field(s) which they want to be displayed with the current keyword. 2. `ItineraryInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `FindCommandParser` parses the remaining input by the user for fields to be found. 4. `FindCommandParser` checks if the field input by the user is a valid field to find. 5. `FindCommandParser` creates a new `FindCommand` based on the fields provided. 6. `ItineraryLogicManager` executes the `FindCommand`. 7. A new find predicate is created to check for matching keyword from the current list of activities. 8. `ItineraryModelManager` checks the current `UniqueActivityList` to find activities with matching keywords provided based on the predicate created. 9. `ItineraryModelManager` updates the activities that matched in the `FilteredActivityList`. 10. `MainWindow` receives `CommandResult` from `ItineraryLogicManager` containing success message to be displayed to user. 11. Jounral entries displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarizes what happens when a user executes a find activity command: .Activity Diagram for `find` Command image::FindItinerary.png[align=""center""]] ==== Design Considerations ===== Aspect: Syntax of the find command * **Alternative 1 (current choice):** Users are allowed to find according to specific fields. This is done by adding the prefixes(t/ for `title`, l/ for `location`, d/ for `date`, and t/ for `time`) before the keyword to be found ** Pros: Allows users to be very specific in the find command. This means that users can find activities with the keywords in the specific field that they want. This implementation also allows users to append one find command with multiple fields to narrow down the search in less steps. ** Cons: Cannot find the same keyword for multiple fields. The current implementation can also cause the CLI by the users to be longer as there is a need to specify the fields to find. Furthermore, this implementation is more troublesome to implement. * **Alternative 2:** Users can find with one or a few keywords without the need to specify the fields. ** Pros: The commands would be a lot shorter and easy to use. This allows for cross-field search which is not possible with the current implementation. This implementation is also easier to implement. ** Cons: This makes it difficult to narrow down the search if the users want to be specific about which field the keyword is in. The current implementation allows for greater freedom in choosing the fields to search for, something this implementation would not be able to accomplish. Furthermore, as `date` and `time` have different format from `location` and `title`, the specified field would make it easier for users to search for activities with the same `date` or `time`. The following activity diagram summarises what happens when a user executes a sort journal command: .Activity Diagram for `sort` Command image::SortActivityDiagram.png[align=""center""]] === Deleting Trip in Home Page ==== Implementation The delete trip feature allows user to delete a trip in Volant. This feature is faciliated by `HomeInputParser`, `DeleteCommandParser`, and `DeleteCommand`. Given below is an example usage scenario and how the delete mechanism behaves at each step: 1. The user executes the delete command in `HOME` page and provides the desired index for deletion. 2. `HomeInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `DeleteCommandParser` parses the remaining input by the user for the index. 4. `DeleteCommandParser` checks if the index provided is valid; at most the number of trips in the list. 5. `DeleteCommandParser` creates a new `DeleteCommand` with the index provided. 6. `HomeLogicManager` executes the `DeleteCommand`. 7. `The trip folder in the file path along with its contents are deleted during execution. 8. `HomeModelManager` updates the `UniqueTripList`. 9. `HomeLogicManager` updates storage with updated `UniqueTripList`. 10. `MainWindow` receives `CommandResult` from `HomeLogicManager` containing success message to be displayed to user. 11. Trips displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes an add activity command: .Activity Diagram for `delete` Command image::deleteTripActivityDiagram.png[align=""center""]] ==== Design Considerations ===== Aspect: How to delete the trip Since each trip is a folder containing the data of the trip's itinerary and journal. If the trip is deleted, the corresponding itinerary and journal json files should also be deleted. This prevents unnecessary files from being stored in the program. === Adding an activity in Itinerary Page ==== Implementation The add activity feature allows user to add an activity to a current trip. This feature is faciliated by `ItineraryInputParser`, `AddCommandParser`, and `AddCommand`. Given below is an example usage scenario and how the activity add mechanism behaves at each step: 1. The user executes the add command in `ITINERARY` page and provides the required metadata in the correct format to be added. 2. `ItineraryInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `AddCommandParser` parses the remaining input by the user for metadata denoted with prefixes. 4. `AddCommandParser` checks if the metadata input by the user is in the desired format. 5. `AddCommandParser` creates a new `AddCommand` based on the metadata provided. 6. `ItineraryLogicManager` executes the `AddCommand`. 7. `ItineraryModelManager` checks if the new `ACTIVITY` has any logical conflicts with existing `ACTIVITY`(s) 8. `ItineraryModelManager` adds the activity to the `UniqueActivityList`. 9. The `itinerary.json` file in the current trip folder in storage is updated 10. `ItineraryLogicManager` updates storage with updated `UniqueActivityList`. 11. `MainWindow` receives `CommandResult` from `ItineraryLogicManager` containing success message to be displayed to user. 12. Activities displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes an add activity command: .Activity Diagram for `add` Command image::AddActivity.png[align=""center""]] ==== Design Considerations ===== Aspect: Prerequisite of the command Since each trip is associated with one itinerary, when the user wants to use the add activity command, a trip must have already been created. This is why the order of the scence switching is important as it disallows user to create an activity that is not associated with any trip. === Finding activities in Itinerary Page ==== Implementation The find activity feature allows user to find one or several activities in the current trip with matching keywords provided. This feature is faciliated by `ItineraryInputParser`, `FindCommandParser`, and `FindCommand`. Given below is an example usage scenario and how the activity find mechanism behaves at each step: 1. The user executes the find command in `ITINERARY` page and provides one or several field(s) which they want to be displayed with the current keyword. 2. `ItineraryInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `FindCommandParser` parses the remaining input by the user for fields to be found. 4. `FindCommandParser` checks if the field input by the user is a valid field to find. 5. `FindCommandParser` creates a new `FindCommand` based on the fields provided. 6. `ItineraryLogicManager` executes the `FindCommand`. 7. A new find predicate is created to check for matching keyword from the current list of activities. 8. `ItineraryModelManager` checks the current `UniqueActivityList` to find activities with matching keywords provided based on the predicate created. 9. `ItineraryModelManager` updates the activities that matched in the `FilteredActivityList`. 10. `MainWindow` receives `CommandResult` from `ItineraryLogicManager` containing success message to be displayed to user. 11. Journal entries displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes a find activity command: .Activity Diagram for `find` Command image::FindItinerary.png[align=""center""]] ==== Design Considerations ===== Aspect: Syntax of the find command * **Alternative 1 (current choice):** Users are allowed to find according to specific fields. This is done by adding the prefixes(t/ for `title`, l/ for `location`, d/ for `date`, and t/ for `time`) before the keyword to be found ** Pros: Allows users to be very specific in the find command. This means that users can find activities with the keywords in the specific field that they want. This implementation also allows users to append one find command with multiple fields to narrow down the search in less steps. ** Cons: Cannot find the same keyword for multiple fields. The current implementation can also cause the CLI by the users to be longer as there is a need to specify the fields to find. Furthermore, this implementation is more troublesome to implement. * **Alternative 2:** Users can find with one or a few keywords without the need to specify the fields. ** Pros: The commands would be a lot shorter and easy to use. This allows for cross-field search which is not possible with the current implementation. This implementation is also easier to implement. ** Cons: This makes it difficult to narrow down the search if the users want to be specific about which field the keyword is in. The current implementation allows for greater freedom in choosing the fields to search for, something this implementation would not be able to accomplish. Furthermore, as `date` and `time` have different format from `location` and `title`, the specified field would make it easier for users to search for activities with the same `date` or `time`. === Refreshing trips in Home Page ==== Implementation The refresh feature allows user to repopulate the current page with the same data in the storage. This feature is faciliated by `HomeInputParser`, `RefreshCommandParser`, and `RefreshCommand`. Given below is an example usage scenario and how the refresh mechanism behaves at each step: 1. The user executes the rf command in `HOME` page. 2. `HomeInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `FindCommandParser` creates a new `RefreshCommand`. 4. `HomeLogicManager` executes the `RefreshCommand`. 5. `MainWindow` receives `CommandResult` and success message from `HomeLogicManager`. 6. `MainWindow` checks the current page user is on and repopulates display with list from `HomeModelManager`. 7. `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes a find activity command: .Activity Diagram for `rf` Command image::rfActivityDiagram.png[align=""center""]] ==== Design Considerations ===== Aspect: How to get the list to repopulate the data with After sorting or finding a list, the user needed a way to view the original data. The construction of each model includes a list that contains the relevant data in storage. Using that list, the view can be repopulated with the original data. === Data Storage All data (trip details, journal entry details and itinerary details) is saved in the `main.data` directory. ==== Organisation .Data Storage in Volant image::user-guide/data-storage.png[align=""center""] The data files are organised in a way that trip details are stored in `volant.json`, while journal and itinerary details are stored in a `journal.json` file and a `itinerary.json` file respectively. Both of these data files are organised under a directory that represents the trip that the journal and itinerary are associated with. The following explanation provides more details about these data files: * Within the `main.data` directory, the `volant.json` file contains a list of JSON objects, each representing a trip, with key-value pairs identifying the trip name, location and date range.Upon creation of a trip named ""ABC"", the `volant.json` file is updated with a new JSON object representing the trip. The `main.data.ABC` directory is also created. * When an activity is added to the itinerary, a `itinerary.json` file is created in the `main.data.ABC` directory, containing a list of JSON objects, each representing an activity, with key-value pairs identifying the activity title, location, date and time. * When an entry is added to the journal, a `journal.json` file is created in the `main.data.ABC` directory, containing a list of JSON objects, each representing a journal entry, with key-value pairs identifying the entry content, date, time, location, feeling and weather. ==== Design Considerations Pros: * Each data file can be kept small in size. * This allows for faster retrieval of trip/journal/itinerary information from these data files. Cons: * There is no single data file that provides an overview of all of a user's data. ==== Data storage implementation: Adding a new trip/activity Given below is an example usage scenario where a user adds a new trip: 1. The user executes the add command and provides the name, location and date range. 2. A new `Trip` object is created with the specified name, location and date range. 3. In `HomeModelManager`, the `Trip` object is added to the `TripList`. 4. A new folder is created in the `main.data` directory with the specified trip name. 5. `HomeLogicManager` accesses the `volant.json` file in the `main.data` directory. 6. Each `Trip` object in the `TripList` is converted into a `JsonAdaptedTrip` object. 7. A new `JsonSerializableTripList` object is created with the `JsonAdaptedTrip` objects. 8. The new `JsonSerializableTripList` object is saved to the `volant.json` data file. 9. The program log displays a success message. The following activity diagram summarises what happens when a user adds a new trip: .Activity diagram for adding a new trip image::addTripStorageActivityDiagram.png[align=""center""] The process is similar for the scenario where the user adds a new activity to the itinerary, and the `itinerary.json` data file is updated. The following activity diagram summarises this process: .Activity diagram for adding a new activity image::addActivityStorageActivityDiagram.png[align=""center""] ==== Data storage implementation: Editing a trip Given below is an example usage scenario where a user edits a trip: 1. The user executes the edit command and provides the updated details. 2. `HomeLogicManager` checks if the name of the trip was updated. If it was, a new directory will be created with the new trip name. Data files in the previous folder are moved into this new folder. Following that, the old folder is deleted. 3. `HomeLogicManager` accesses the `volant.json` file in the `main.data` directory. 4. Each `Trip` object in the `TripList` is converted into a `JsonAdaptedTrip` object. 5. A new `JsonSerializableTripList` object is created with the `JsonAdaptedTrip` objects. 6. The new `JsonSerializableTripList` object is saved to the `volant.json` data file. 7. The program log displays a success message. The following activity diagram summarises what happens when a user edits a trip: .Activity diagram for editing a trip image::editTripStorageActivityDiagram.png[align=""center""] ==== Data storage implementation: Deleting a journal entry/itinerary activity Given below is an example usage scenario where a user deletes a journal entry: 1. The user executes the delete command. 2. In `JournalModelManager`, the identified `Entry` is removed from the `EntryList`. 3. `JournalLogicManager` accesses the `journal.json` file in the specific trip directory. 4. Each remaining `Entry` object in the `EntryList` is converted into a `JsonAdaptedEntry` object. 5. A new `JsonSerializableEntryList` object is created with the `JsonAdaptedEntry` objects. 6. The new `JsonSerializableEntryList` object is saved to the `journal.json` data file. 7. The program log displays a success message. This process is the same for scenarios where the user deletes an itinerary activity. The following activity diagram summarises what happens when a user deletes a journal entry or itinerary activity: .Activity diagram for deleting a journal entry/itinerary activity image::deleteStorageActivityDiagram.png[align=""center""] === Logging We are using `java.util.logging` package for logging. The `LogsCenter` class is used to manage the logging levels and logging destinations. * The logging level can be controlled using the `logLevel` setting in the configuration file (See <>) * The `Logger` for a class can be obtained using `LogsCenter.getLogger(Class)` which will log messages according to the specified logging level * Currently log messages are output through: `Console` and to a `.log` file. *Logging Levels* * `SEVERE` : Critical problem detected which may possibly cause the termination of the application * `WARNING` : Can continue, but with caution * `INFO` : Information showing the noteworthy actions by the App * `FINE` : Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size [[Implementation-Configuration]] === Configuration Certain properties of the application can be controlled (e.g user prefs file location, logging level) through the configuration file (default: `config.json`). == Documentation Refer to the guide <>. == Testing Refer to the guide <>. == Dev Ops Refer to the guide <>. [appendix] == Product Scope *Target user profile*: * is a solo traveller * prefers desktop apps over other types * can type fast * prefers typing over mouse input * is reasonably comfortable using CLI apps *Value proposition*: convenient travel assistant to for solo travelers who are always on their feet. [appendix] == User Stories *Priorities* * High (must have) - `* * *` * Medium (nice to have) - `* *` * Low (not useful) - `*` [width=""80%"",cols=""22%,<23%,<25%,<30%"",options=""header"",] |======================================================================= |Priority |As a ... |I want to ... |So that I can ... |`* * *` | frequent traveler | add a travel entry with weather, location and time metadata | document my past travels |`* * *` | traveler always on the go | record short text entries recording my travels, similar to that of a Tweet on Twitter | can keep track of my activities without excessive typing |`* * *` |user |add an activity into an itinerary list |see my planned activities at a glance and better plan my trip |`* * *` |user |tag a location to each activity in the itinerary |view where each activity is taking place |`* * *` |user |edit the entries in my itinerary list |amend any mistakes when entering data, or change my travel plans |`* * *` |user |see a chronological timeline of the activities in the itinerary |have a clear idea of my travel plans and schedule |`* * *` |user |view my itinerary and journal separately |view them in a less cluttered manner |`* * *` |frequent traveler |see a record of all my past itineraries |can review my past travels |`* * *` |traveler always meeting new people overseas |add a contact that I met during my trip with metadata including their name, age, phone number, location where I met them, and their country of origin |can keep in contact with them |`* * *` |user |delete contacts |get rid of contacts that I have not been in touch with for some time |`* * *` |user |view my itineraries, contact lists and journals specific to the trip they are relevant to |effectively plan for multiple trips simultaneously |`* * *` |user |customize trip names |distinguish between different trips that happen in the same location within similar date ranges |`* *` |frequent traveler |to be able to see a timeline view of all my short journal entries and photos, including the location and time of the photos and entries, per trip |relieve the memories of the trip in its original sequence |`* *` |food lover |add a meal with description, photo, price and location |keep track of what I ate |`* *` |user |sort my travel entries by category depending on the ‘feeling’ tag of each travel entry |see my best moments |`* *` |user |record items in a packing list|remind myself what I will need on a trip |`* *` |busy user |list |easily reference what I need for a trip at a glance |`* *` |fickle-minded user |delete packing list entries |remove items I feel I no longer need for the trip from the packing list |======================================================================= _{All user stories can be viewed in our issue tracker.}_ [appendix] == Use Cases (For all use cases below, the *System* is `Volant (V)` and the *Actor* is the `user`, unless specified otherwise) [discrete] === UC01 - Adding New Trip **Precondition: **Start from home page *Guarantee:* A new Trip will be created *<>* 1. User enters details of trip to be added 2. V adds new trip to trip list + Use case ends *<>* [none] * 1a. V detects invalid characters in trip details * 1a1. V outputs error informing user of invalid command + Use case ends [none] * 1b. V detects missing fields in trip details * 1b1. V outputs error informing user of missing fields + Use case ends [none] * 1c. V detects that trip has a clashing date range with another trip on the trip list * 1c1. V outputs error informing user of clashing date range between trip and another trip on the list + Use case ends [none] * 1d. V detects that trip has the same name as another trip on the trip list * 1d1. V outputs error informing user that the trip already exists on the trip list + Use case ends [none] * 1e. V is unable to detect a valid command keyword * 1e1. V outputs error informing user of invalid command + Use case ends [discrete] === UC02 - Editing Existing Trip **Precondition: **User is in the home page **Guarantee: **Metadata of existing trip will be changed *MSS* 1. User inputs command to edit an existing trip 2. V updates metadata of corresponding trip according to user input 3. Trip list is updated and the changes are reflected for user to see + Use case ends *Extensions* [none] * 1a. V is unable to detect any specified fields to edit * 1a1. V outputs error informing user that a field to edit must be specified + Use case ends [none] * 1b. V detects an invalid index i.e. index out of range or negative index * 1b1. V outputs error informing user of invalid index specified + Use case ends [none] * 1c. V detects invalid characters for the fields * 1c1. V outputs error informing user of invalid command + Use case ends [none] * 1d. V is unable to detect a valid command keyword * 1d1. V outputs error informing user of invalid command + Use case ends [discrete] === UC03 - Navigating to Trip Page *Precondition:* User has added a trip *Guarantee:* User will be moved to the Trip page *MSS* 1. User changes directory to specific trip folder in trip list using index 2. V loads and displays trip page + Use case ends *Extensions* [none] * 1a. V detects an invalid index i.e. index out of range or negative index * 1a1. V outputs error informing user of invalid index specified + Use case ends [none] * 1b. V is unable to detect a valid command keyword * 1b1. V outputs error informing user of invalid command + Use case ends [discrete] === UC04 - Accessing Trip Feature Pages (Itinerary / Journal) *Precondition:* User is in the home page *Guarantee:* User will be moved to the desired page *MSS* 1. User navigates to a specific trip (UC03) 2. User requests to navigate to the desired page in current trip 3. V loads and displays the desired page + Use case ends *Extensions* [none] * 2a. V detects invalid field to navigate to the page * 2a1. V outputs error informing user of invalid command + Use case ends [none] * 2b. V is unable to detect a valid command keyword * 2b1. V outputs error informing user of invalid command + Use case ends [discrete] === UC05 - Adding a travel Entry into Journal of a Trip **Precondition: **User is already in the Journal page of Trip **Guarantee: **A new travel entry will be added to the Travel Journal *MSS* 1. User enters details of the travel entry 2. V confirms successful entry and displays new entry in the journal + Use case ends *Extensions* [none] * 1a. V detects invalid characters in travel entry * 1a1. V outputs error informing user of invalid command + Use case ends [none] * 1b. V detects missing fields in travel entry * 1b1. V outputs error informing user of missing travel entry + Use case ends [none] * 1c. V is unable to detect a valid command keyword * 1c1. V outputs error informing user of invalid command + Use case ends [none] * 1d. V detects that text field is greater 280 characters long * 1d1. V outputs error informing user of character limit and how many characters over the limit their input was + Use case ends [discrete] === UC06 - Adding Activities into Itinerary **Precondition: **User is already in the Itinerary page of the Trip **Guarantee: **A new activity will be added to the Itinerary *MSS* 1. User enters details of activity 2. V confirms successful entry and displays updated itinerary + Use case ends *Extensions* [none] * 1a. V detects invalid characters into activity entry * 1a1. V outputs error informing user of invalid command + Use case ends [none] * 1b. V detects missing fields in activity entry * 1b1. V outputs error informing user of missing activity entry + Use case ends [none] * 1c. V is unable to detect a valid command keyword * 1c1. V outputs error informing user of invalid command + Use case ends [discrete] === UC07 - Editing Existing Journal Entry **Precondition: **User is on the Journal page and has added one or more entries already **Guarantee: **Metadata of an existing entry will be changed *MSS* 1. User inputs command to edit an entry 2. V updates metadata of corresponding entry according to user input 3. Entry list is updated and the changes are reflected for user to see + Use case ends *Extensions* [none] * 1a. V is unable to detect any specified fields to edit * 1a1. V outputs error informing user that a field to edit must be specified + Use case ends [none] * 1b. V detects incorrect date or time format * 1b1. V outputs error informing user that the acceptable format for date and time input + Use case ends [none] * 1c. V detects an invalid index i.e. index out of range or negative index * 1c1. V outputs error informing user of invalid index specified + Use case ends [none] * 1d. V detects invalid characters for the fields * 1d1. V outputs error informing user of invalid command + Use case ends [none] * 1e. V is unable to detect a valid command keyword * 1e1. V outputs error informing user of invalid command + Use case ends [discrete] === UC08 - Editing Existing Activity **Precondition: **User is on the Itinerary page and has added one or more activities already **Guarantee: **Metadata of an existing activity will be changed *MSS* 1. User inputs command to edit an activity. 2. V updates metadata of corresponding activity according to user input 3. Activity list is updated and the changes are reflected for user to see + Use case ends *Extensions* [none] * 1a. V is unable to detect any specified fields to edit * 1a1. V outputs error informing user that a field to edit must be specified + Use case ends [none] * 1b. V detects incorrect date or time format * 1b1. V outputs error informing user that the acceptable format for date and time input + Use case ends [none] * 1c. V detects an invalid index i.e. index out of range or negative index * 1c1. V outputs error informing user of invalid index specified + Use case ends [none] * 1d. V detects invalid characters for the fields * 1d1. V outputs error informing user of invalid command + Use case ends [none] * 1e. V is unable to detect a valid command keyword * 1e1. V outputs error informing user of invalid command + Use case ends [discrete] === UC09 - Sorting Journal Entries **Precondition: **User is on the Journal page and has added one or more entries already **Guarantee: **Entry list will be sorted *MSS* 1. User inputs sort command 2. V sorts the entry list according to user's input 3. Entry list is updated and the sorted list is displayed to the user + Use case ends Extensions [none] * 1a. V does not detect an argument for sort type in user's input * 1a1. V outputs error message informing user to include a sort type + Use case ends [none] * 1b. V detects invalid characters for the sort type input * 1b1. V outputs error informing user of invalid sort type + Use case ends [none] * 1c. V is unable to detect a valid command keyword * 1c1. V outputs error informing user of invalid command + Use case ends [discrete] === UC10 - Finding Itinerary Activities **Precondition: **User is on the Itinerary page and has added one or more activities already **Guarantee: **Activity list containing matching search terms is displayed *MSS* 1. User inputs find command 2. V checks the activity list for activities with metadata that matches the given search term(s) 3. V outputs an activity list containing all the activities matching the given search term(s) + Use case ends Extensions [none] * 1a. V does not find any activities that match the given search term(s) * 1a1. V outputs message informing user that no matching activities were found + Use case ends [none] * 1b. V detects invalid characters for the given search term(s) * 1b1. V outputs error informing user of invalid command + Use case ends [none] * 1c. V is unable to detect a valid command keyword * 1c1. V outputs error informing user of invalid command + Use case ends [appendix] == Non Functional Requirements . Volant should work on any <> as long as it has Java `11` or above installed. . Volant should work without any internet connection. . Volant should be able to hold up to 100 trips without noticing a increase in response time from the system for typical usage. . A user who is able to type above 40 words per minute (wpm) for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse. . Commands should be <> commands as opposed to <>. . A user should have minimum 100 Megabytes (MB) free disk space on their computer to store the program. . Input by the user should only be in English. . Volant source code should be covered by tests as much as possible. . Volant should work for a single user only. [appendix] == Glossary [[extensions]] Extensions:: ""add-on""s to the MSS that describe exceptional/alternative flow of events. [[mainstream-os]] Mainstream OS:: Windows, Linux, Unix, OS-X [[mss]] MSS:: Main Success Scenario [[multi-level-c]] Multi-level Commands:: Commands that require multiple lines of user input for execution. [[root-page]] Root Page:: The first page the shows up when Volant is opened. By default, this is the `HOME` page. [[one-shot-c]] One-shot Commands:: Commands that are executed using only a single line of user input. [appendix] == Product Survey *Volant* Author: Team Volant Pros:: * The product is effective in assisting solo travellers to plan and execute their trips. * GUI is very aesthetic looking, pleasing to the eyes. * The available commands are intuitive, and are easy to use and remember. Cons:: * The fremium model proposed can be a bit expensive. * A dark mode can be included. Some users prefer a GUI with dark mode. * More features can be integrated. These features can be included in version 2.0. [appendix] == Instructions for Manual Testing Given below are instructions to test the app manually. [NOTE] These instructions only provide a starting point for testers to work on; testers are expected to do more _exploratory_ testing. === Launch and Shutdown . Initial launch .. Download the jar file and copy into an empty folder. .. Double-click the jar file. + Expected: Shows the GUI with a set of sample contacts. The window size may not be optimum. . Saving window preferences .. Resize the window to an optimum size. Move the window to a different location. Close the window. .. Re-launch the app by double-clicking the jar file. + Expected: The most recent window size and location is retained. === Adding . Adding a `TRIP` to an empty or populated trip list .. Prerequisites: NA .. Test case: `add n/Bali 2020 l/Bali d/02-01-2020 to 02-05-2020` .. Expected: `TRIP` with corresponding details is added to trip list. .. Test case: `add n/Bali 2020 l/Bali d/2020-01-02 to 2020-05-02` .. Expected: No `TRIP` added. Error details shown in status message. === Deleting . Deleting a `TRIP` while all `TRIPS` are listed .. Prerequisites: List all `TRIPS` using the `list` command. Multiple `TRIPS` are present in the list. .. Test case: `delete 1` + Expected: First contact is deleted from the list. Details of the deleted `TRIP` are shown in the status message. Timestamp in the status bar is updated. .. Test case: `delete 0` + Expected: No `TRIP` is deleted. Error details shown in the status message. Status bar remains the same. .. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the list size) + Expected: Similar to previous. . Deleting an `activity` in the `ITINERARY` .. Prerequisites: A `TRIP` has already been created. .. Test case: `delete 1` + Expected: First `activity` is deleted from the `activity` list of the `ITINERARY` of the current `TRIP`. Current `activity` list is updated. .. Test case: `delete 0` + Expected: No `activity` is deleted. Error details shown in the status message. .. Test case: `delete a` + Expected: No `activity` is deleted. Error details shown in the status message. .. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the itinerary size) + Expected: Similar to previous. . Deleting an `entry` in the `JOURNAL` .. Prerequisites: A `TRIP` has already been created. .. Test case: `delete 1` + Expected: First `entry` is deleted from the `JOURNAL` of the current `TRIP`. Current `entry` list is updated. .. Test case: `delete 0` + Expected: No `entry` is deleted. Error details shown in the status message .. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the journal size) + Expected: Similar to previous. === Saving data . Dealing with missing/corrupted data files .. _{explain how to simulate a missing/corrupted file and the expected behavior}_ ",12535,False,2015.6004647753975,median ":doctitle: OpenDataPlane (ODP) Users-Guide :description: This document is intended to guide a new OpenDataPlane + application developer. :imagesdir: ../images :toc: :numbered!: [abstract] Abstract -------- This document is intended to guide a new ODP application developer. Further details about ODP may be found at the http://opendataplane.org[ODP] home page. .Overview of a system running ODP applications image::overview.svg[align=""center""] ODP is an API specification that allows many implementations to provide platform independence, automatic hardware acceleration and CPU scaling to high performance networking applications. This document describes how to write an application that can successfully take advantage of the API. :numbered: == Introduction .OpenDataPlane Components image::odp_components.svg[align=""center""] .The ODP API Specification ODP consists of three separate but related component parts. First, ODP is an abstract API specification that describes a functional model for data plane applications. This specification covers many common data plane application programming needs, such as the ability to receive, manipulate, and transmit packet data, without specifying how these functions are performed. This is quite intentional. It is precisely because ODP APIs do not have a preferred embodiment that they permit innovation in how these functions can be realized on various platforms that offer implementations of ODP. To achieve this goal, ODP APIs are described using abstract data types whose definition is left up to the ODP implementer. For example, in ODP packets are referenced by abstract handles of type `odp_packet_t`, and packet-related APIs take arguments of this type. What an `odp_packet_t` actually is is not part of the ODP API specification--that is the responsibility of each ODP implementation. .Summary: ODP API attributes: * Open Source, open contribution, BSD-3 licensed. * Vendor and platform neutral. * Application-centric. Covers functional needs of data plane applications. * Ensures portability by specifying the functional behavior of ODP. * Defined jointly and openly by application writers and platform implementers. * Architected to be implementable on a wide range of platforms efficiently * Sponsored, governed, and maintained by the Linaro Networking Group (LNG) .ODP Implementations Second, ODP consists of multiple implementations of this API specification, each tailored to a specific target platform. ODP implementations determine how each ODP abstract type is represented on that platform and how each ODP API is realized. On some platforms, ODP APIs will be realized using specialized instructions that accelerate the functional behavior specified by the API. On others, hardware co-processing engines may completely offload the API so that again it can be performed with little or no involvement by a CPU. In all cases, the application sees the same functional behavior independent of how a given platform has chosen to realize it. By allowing each platform the freedom to determine how best to realize each API's specified functional behavior in an optimal manner, ODP permits applications written to its APIs to take full advantage of the unique capabilities of each platform without the application programmer needing to have specialist knowledge of that platform or to be concerned with how best to tune the application to a particular platform. This latter consideration is particularly important in Network Function Virtualization (NFV) environments where the application will run on a target platform chosen by someone else. .Summary: ODP Implementation Characteristics * One size does not fit all--supporting multiple implementations allows ODP to adapt to widely differing internals among platforms. * Anyone can create an ODP implementation tailored to their platform * Distribution and maintenance of each implementation is as owner wishes - Open source or closed source as business needs determine - Have independent release cycles and service streams * Allows HW and SW innovation in how ODP APIs are implemented on each platform. .Reference Implementations To make it easy to get started with implementing ODP on a new platform, ODP supplies a number of _reference implementations_ that can serve as a starting point. The two primary references implementations supplied by ODP are *odp-linux* and *odp-dpdk* .odp-linux The *odp-linux* reference implementation is a pure SW implementation of the ODP API that relies only on the Linux programming API. As a functional model for ODP, it enables ODP to be bootstrapped easily to any platform that supports a Linux kernel. .odp-dpdk The *odp-dpdk* reference implementation is a pure SW implementation of the ODP API that uses http://dpdk.org[DPDK] as a SW accelerator. In particular, *odp-dpdk* offers superior I/O performance for systems that use NICs, allowing ODP applications to take immediate full advantage of the various NIC device drivers supported by DPDK. .Summary: ODP Reference Implementations * Open source, open contribution, BSD-3 licensed. * Provide easy bootstrapping of ODP onto new platforms * Implementers free to borrow or tailor code as needed for their platform * Implementers retain full control over their implementations whether or not they are derived from a reference implementation. .ODP Validation Test Suite Third, to ensure consistency between different ODP implementations, ODP consists of a validation suite that verifies that any given implementation of ODP faithfully provides the specified functional behavior of each ODP API. As a separate open source component, the validation suite may be used by application writers, system integrators, and platform providers alike to confirm that any purported implementation of ODP does indeed conform to the ODP API specification. .Summary: ODP Validation Test Suite * Synchronized with ODP API specification * Maintained and distributed by LNG * Open source, open contribution, BSD-3 licensed. * Key to ensuring application portability across all ODP implementations * Tests that ODP implementations conform to the specified functional behavior of ODP APIs. * Can be run at any time by users and vendors to validate implementations of ODP. === ODP API Specification Versioning As an evolving standard, the ODP API specification is released under an incrementing version number, and corresponding implementations of ODP, as well as the validation suite that verifies API conformance, are linked to this version number. ODP versions are specified using a standard three-level number (major.minor.fixlevel) that are incremented according to the degree of change the level represents. Increments to the fix level represent clarification of the specification or other minor changes that do not affect either the syntax or semantics of the specification. Such changes in the API specification are expected to be rare. Increments to the minor level represent the introduction of new APIs or functional capabilities, or changes to he specified syntax or functional behavior of APIs and thus may require application source code changes. Such changes are well documented in the release notes for each revision of the specification. Finally, increments to the major level represent significant structural changes that most likely require some level of application source code change, again as documented in the release notes for that version. === ODP Implementation Versioning ODP implementations are free to use whatever release naming/numbering conventions they wish, as long as it is clear what level of the ODP API a given release implements. A recommended convention is to use the same three level numbering scheme where the major and minor numbers correspond to the ODP API level and the fix level represents an implementation-defined service level associated with that API level implementation. The LNG-supplied ODP reference implementations follow this convention. === ODP Validation Test Suite Versioning The ODP validation test suite follows these same naming conventions. The major and minor release numbers correspond to the ODP API level that the suite validates and the fix level represents the service level of the validation suite itself for that API level. === ODP Design Goals ODP has three primary goals that follow from its component structure. The first is application portability across a wide range of platforms. These platforms differ in terms of processor instruction set architecture, number and types of application processing cores, memory organization, as well as the number and type of platform specific hardware acceleration and offload features that are available. ODP applications can move from one conforming implementation to another with at most a recompile. Second, ODP is designed to permit data plane applications to avail themselves of platform-specific features, including specialized hardware accelerators, without specialized programming. This is achieved by separating the API specification from their implementation on individual platforms. Since each platform implements each ODP API in a manner optimal to that platform, applications automatically gain the benefit of such optimizations without the need for explicit programming. Third, ODP is designed to allow applications to scale out automatically to support many core architectures. This is done using an event based programming model that permits applications to be written to be independent of the number of processing cores that are available to realize application function. The result is that an application written to this model does not require redesign as it scales from 4, to 40, to 400 cores. == Organization of this Document This document is organized into several sections. The first presents a high level overview of ODP applications, the ODP API component areas, and their associated abstract data types. This section introduces ODP APIs at a conceptual level. The second provides a tutorial on the programming model(s) supported by ODP, paying particular attention to the event model as this represents the preferred structure for most ODP applications. This section builds on the concepts introduced in the first section and shows how ODP applications are structured to best realize the three ODP design goals mentioned earlier. The third section provides a more detailed overview of the major ODP API components and is designed to serve as a companion to the full reference specification for each API. The latter is intended to be used by ODP application programmers, as well as implementers, to understand the precise syntax and semantics of each API. == ODP Applications and Packet Flow Data plane applications are fundamentally concerned with receiving, examining, manipulating, and transmitting packets. The distinguishing feature of the data plane is that these applications are mostly concerned with the lowest layers of the ISO stack (Layers 2 and 3) and they have very high to extreme performance requirements. ODP is designed to provide a portable framework for such applications. At the highest level, an *ODP Application* is a program that uses one or more ODP APIs. Because ODP is a framework rather than a programming environment, applications are free to also use other APIs that may or may not provide the same portability characteristics as ODP APIs. ODP applications vary in terms of what they do and how they operate, but in general all share the following characteristics: . They are organized into one or more _threads_ that execute in parallel. . These threads communicate and coordinate their activities using various _synchronization_ mechanisms. . They receive packets from one or more _packet I/O interfaces_. . They examine, transform, or otherwise process packets. . They transmit packets to one or more _packet I/O interfaces_. At the highest level, an ODP application looks as follows: .ODP Application Packet Flow Overview image::packet_flow.svg[align=""center""] Packets arrive and are received (RX) from a network interface represented by a _PktIO_ abstraction. From here they go either directly to _Queues_ that are polled by ODP _Threads_, or can pass through the _Classifier_ and sorted into Queues that represent individual flows. These queues can then be dispatched to application threads via the _Scheduler_. Threads, in term can invoke various ODP APIs to manipulate packet contents prior to disposing of them. For output processing, packets make by directly queued to a PktIO output queue or else they may be handed to the _Traffic Manager_ for programmatic _Quality of Service (QoS)_ processing before winding up being transmitted (TX). Note that output interfaces may operate in _loopback_ mode, in which case packets sent to them are re-routed back to the input lines for ""second pass"" processing. For example, an incoming IPSec packet cannot be properly classified (beyond being IPSec traffic) until it is decrypted. Once decrypted and its actual contents made visible, it can then be classified into its real flow. What is important to note is that the only part of the above diagram that need be written are the boxes in yellow that contain the application logic. Everything else shown here is provided by the ODP framework and available for use by any ODP application. This represents the ""machinery"" of a data plane application and is structured to allow applications written to the ODP APIs to be both portable and optimized for each platform that offers an ODP implementation without additional programming effort. == ODP API Concepts ODP programs are built around several conceptual structures that every application programmer needs to be familiar with to use ODP effectively. The main ODP concepts are: Thread, Event, Queue, Pool, Shared Memory, Buffer, Packet, PktIO, Time, Timer, and Synchronizer. === Thread The thread is the fundamental programming unit in ODP. ODP applications are organized into a collection of threads that perform the work that the application is designed to do. ODP threads may or may not share memory with other threads--that is up to the implementation. Threads come in two ""flavors"": control and worker, that are represented by the abstract type `odp_thread_type_t`. A control thread is a supervisory thread that organizes the operation of worker threads. Worker threads, by contrast, exist to perform the main processing logic of the application and employ a run to completion model. Worker threads, in particular, are intended to operate on dedicated processing cores, especially in many core processing environments, however a given implementation may multitask multiple threads on a single core if desired (typically on smaller and lower performance target environments). In addition to thread types, threads have associated _attributes_ such as _thread mask_ and _scheduler group_ that determine where they can run and the type of work that they can handle. These will be discussed in greater detail later. === Event Events are what threads process to perform their work. Events can represent new work, such as the arrival of a packet that needs to be processed, or they can represent the completion of requests that have executed asynchronously. Events can also represent notifications of the passage of time, or of status changes in various components of interest to the application. Events have an event type that describes what it represents. Threads can create new events or consume events processed by them, or they can perform some processing on an event and then pass it along to another component for further processing. References to events are via handles of abstract type `odp_event_t`. Cast functions are provided to convert these into specific handles of the appropriate type represented by the event. === Queue A queue is a message passing channel that holds events. Events can be added to a queue via enqueue operations or removed from a queue via dequeue operations. The endpoints of a queue will vary depending on how it is used. Queues come in two major types: polled and scheduled, which will be discussed in more detail when the event model is introduced. Queues may also have an associated context, which represents a persistent state for all events that make use of it. These states are what permit threads to perform stateful processing on events as well as stateless processing. Queues are represented by handles of abstract type `odp_queue_t`. === Pool A pool is a shared memory area from which elements may be drawn. Pools represent the backing store for events, among other things. Pools are typically created and destroyed by the application during initialization and termination, respectively, and then used during processing. Pools may be used by ODP components exclusively, by applications exclusively, or their use may be shared between the two. Pools have an associated type that characterizes the elements that they contain. The two most important pool types are Buffer and Packet. Pools are represented by handles of abstract type `odp_pool_t`. === Shared Memory Shared memory represents raw blocks of storage that are sharable between threads. They are the building blocks of pools but can be used directly by ODP applications if desired. Shared memory is represented by handles of abstract type `odp_shm_t`. === Buffer A buffer is a fixed sized block of shared storage that is used by ODP components and/or applications to realize their function. Buffers contain zero or more bytes of application data as well as system maintained metadata that provide information about the buffer, such as its size or the pool it was allocated from. Metadata is an important ODP concept because it allows for arbitrary amounts of side information to be associated with an ODP object. Most ODP objects have associated metadata and this metadata is manipulated via accessor functions that act as getters and setters for this information. Getter access functions permit an application to read a metadata item, while setter access functions permit an application to write a metadata item. Note that some metadata is inherently read only and thus no setter is provided to manipulate it. When object have multiple metadata items, each has its own associated getter and/or setter access function to inspect or manipulate it. Buffers are represented by handles of abstract type `odp_buffer_t`. === Packet Packets are received and transmitted via I/O interfaces and represent the basic data that data plane applications manipulate. Packets are drawn from pools of type `ODP_POOL_PACKET`. Unlike buffers, which are simple objects, ODP packets have a rich set of semantics that permit their inspection and manipulation in complex ways to be described later. Packets also support a rich set of metadata as well as user metadata. User metadata permits applications to associate an application-determined amount of side information with each packet for its own use. Packets are represented by handles of abstract type `odp_packet_t`. === Packet I/O (PktIO) PktIO is how ODP represents I/O interfaces. A pktio object is a logical port capable of receiving (RX) and/or transmitting (TX) packets. This may be directly supported by the underlying platform as an integrated feature, or may represent a device attached via a PCIE or other bus. PktIOs are represented by handles of abstract type `odp_pktio_t`. === Time The time API is used to measure time intervals and track time flow of an application and presents a convenient way to get access to an implementation-defined time source. The time API consists of two main parts: local time API and global time API. ==== Local time The local time API is designed to be used within one thread and obtaining local time may be more efficient in some implementations than global time. Local time stamps are local to the calling thread and should not be shared with other threads, as local time is not guaranteed to be consistent between threads. Current local time can be read with `odp_time_local()`. ==== Global time The global time API is designed to be used for tracking time between threads. So, global time stamps may safely be shared between threads. Current global time can be read with `odp_time_global()`. Both local and global time is not wrapped during the application life cycle. The time API includes functions to operate with time, such as `odp_time_diff()`, `odp_time_sum()`, `odp_time_cmp()`, conversion functions like `odp_time_to_ns()`, `odp_time_local_from_ns()`, `odp_time_global_from_ns()`. To get rate of time source `odp_time_local_res()`, `odp_time_global_res()` are used. To wait, `odp_time_wait_ns()` and `odp_time_wait_until()` are used, during which a thread potentially busy loops the entire wait time. The `odp_time_t` opaque type represents local or global timestamps. ==== Portability Considerations The ODP Time APIs are designed to permit high-precision relative time measurement within an ODP application. No attempt is made to correlate an `odp_time_t` object with ""wall time"" or any other external time reference. As defined by the ODP specification, `odp_time_t` values are required to be unique over a span of at least 10 years. Most implementations will choose to implement time values using 64-bit values, whose wrap times exceed 500 years, making wrapping concerns not relevant to ODP applications. === Timer Timers are how ODP applications measure and respond to the passage of time. Timers are drawn from specialized pools called timer pools that have their own abstract type (`odp_timer_pool_t`). Applications may have many timers active at the same time and can set them to use either relative or absolute time. When timers expire they create events of type `odp_timeout_t`, which serve as notifications of timer expiration. === Synchronizer Multiple threads operating in parallel typically require various synchronization services to permit them to operate in a reliable and coordinated manner. ODP provides a rich set of locks, barriers, and similar synchronization primitives, as well as abstract types for representing various types of atomic variables. The ODP event model also makes use of queues to avoid the need for explicit locking in many cases. This will be discussed in the next section. == ODP Components == Building on ODP concepts, ODP offers several components that relate to the flow of work through an ODP application. These include the Classifier, Scheduler, and Traffic Manager. These components relate to the three main stages of packet processing: Receive, Process, and Transmit. === Classifier The *Classifier* provides a suite of APIs that control packet receive (RX) processing. .ODP Receive Processing with Classifier image::odp_rx_processing.svg[align=""center""] The classifier provides two logically related services: [horizontal] Packet parsing:: Verifying and extracting structural information from a received packet. Packet classification:: Applying *Pattern Matching Rules (PMRs)* to the parsed results to assign an incoming packet to a *Class of Service (CoS)*. Combined, these permit incoming packets to be sorted into *flows*, which are logically related sequences of packets that share common processing requirements. While many data plane applications perform stateless packet processing (_e.g.,_ for simple forwarding) others perform stateful packet processing. Flows anchor state information relating to these groups of packets. A CoS determines two variables for packets belonging to a flow: [list] * The pool that they will be stored in on receipt * The queue that they will be added to for processing The PMRs supported by ODP permit flow determination based on combinations of packet field values (tuples). The main advantage of classification is that on many platforms these functions are performed in hardware, meaning that classification occurs at line rate as packets are being received without any explicit processing by the ODP application. Note that the use of the classifier is optional. Applications may directly receive packets from a corresponding PktIO input queue via direct polling if they choose. === Scheduler The *Scheduler* provides a suite of APIs that control scalable event processing. .ODP Scheduler and Event Processing image::odp_scheduling.svg[align=""center""] The Scheduler is responsible for selecting and dispatching one or more events to a requesting thread. Event selection is based on several factors involving both the queues containing schedulable events and the thread making an `odp_schedule()` or `odp_schedule_multi()` call. ODP queues have a _scheduling priority_ that determines how urgently events on them should be processed relative to events contained in other queues. Queues also have a _scheduler group id_ associated with them that must match the associated scheduler group _thread mask_ of the thread calling the scheduler. This permits events to be grouped for processing into classes and have threads that are dedicated to processing events from specified classes. Threads can join and leave scheduler groups dynamically, permitting easy application response to increases in demand. When a thread receives an event from the scheduler, it in turn can invoke other processing engines via ODP APIs (_e.g.,_ crypto processing) that can operate asynchronously. When such processing is complete, the result is that a *completion event* is added to a schedulable queue where it can be scheduled back to a thread to continue processing with the results of the requested asynchronous operation. Threads themselves can enqueue events to queues for downstream processing by other threads, permitting flexibility in how applications structure themselves to maximize concurrency. === Traffic Manager The *Traffic Manager* provides a suite of APIs that control traffic shaping and Quality of Service (QoS) processing for packet output. .ODP Transmit processing with Traffic Manager image::odp_traffic_manager.svg[align=""center""] The final stage of packet processing is to transmit it. Here, applications have several choices. As with RX processing, applications may send packets directly to PktIO TX queues for direct transmission. Often, however, applications need to perform traffic shaping and related *Quality of Service (QoS)* processing on the packets comprising a flow as part of transmit processing. To handle this need, ODP provides a suite of *Traffic Manager* APIs that permit programmatic establishment of arbiters, shapers, etc. that control output packet processing to achieve desired QoS goals. Again, the advantage here is that on many platforms traffic management functions are implemented in hardware, permitting transparent offload of this work. == ODP Application Programming Structure === The include structure Applications only include the 'include/odp_api.h' file, which includes the 'platform//include/odp/api' files to provide a complete definition of the API on that platform. The doxygen documentation defining the behavior of the ODP API is all contained in the public API files, and the actual definitions for an implementation will be found in the per platform directories. Per-platform data that might normally be a `#define` can be recovered via the appropriate access function if the #define is not directly visible to the application. .Users include structure ---- ./ ├── include/ │   ├── odp/ │   │   └── api/ │ │ └── spec/ │ │ └── The Public API and the documentation. │ │ │ │ │ ├── odp_api.h This file should be the only file included by the │ │ application. ---- === Initialization IMPORTANT: ODP depends on the application to perform a graceful shutdown, calling the terminate functions should only be done when the application is sure it has closed the ingress and subsequently drained all queues, etc. === Startup The first API that must be called by an ODP application is 'odp_init_global()'. This takes two pointers. The first, `odp_init_t`, contains ODP initialization data that is platform independent and portable, while the second, `odp_platform_init_t`, is passed unparsed to the implementation to be used for platform specific data that is not yet, or may never be suitable for the ODP API. Calling odp_init_global() establishes the ODP API framework and MUST be called before any other ODP API may be called. Note that it is only called once per application. Following global initialization, each thread in turn calls 'odp_init_local()'. This establishes the local ODP thread context for that thread and MUST be called before other ODP APIs may be called by that thread. The sole argument to this call is the _thread type_, which is either `ODP_THREAD_WORKER` or `ODP_THREAD_CONTROL`. === Shutdown Shutdown is the logical reverse of the initialization procedure, with `odp_term_local()` called for each thread before `odp_term_global()` is called to terminate ODP. === Application Initialization/Termination Structure ODP Applications follow the general structure flow shown below: .ODP Application Structure Flow Diagram image::resource_management.svg[align=""center""] == Common Conventions Many ODP APIs share common conventions regarding their arguments and return types. This section highlights some of the more common and frequently used conventions. === Handles and Special Designators ODP resources are represented via _handles_ that have abstract type _odp_resource_t_. So pools are represented by handles of type `odp_pool_t`, queues by handles of type `odp_queue_t`, etc. Each such type has a distinguished type _ODP_RESOURCE_INVALID_ that is used to indicate a handle that does not refer to a valid resource of that type. Resources are typically created via an API named _odp_resource_create()_ that returns a handle of type _odp_resource_t_ that represents the created object. This returned handle is set to _ODP_RESOURCE_INVALID_ if, for example, the resource could not be created due to resource exhaustion. Invalid resources do not necessarily represent error conditions. For example, `ODP_EVENT_INVALID` in response to an `odp_queue_deq()` call to get an event from a queue simply indicates that the queue is empty. === Addressing Scope Unless specifically noted in the API, all ODP resources are global to the ODP application, whether it runs as a single process or multiple processes. ODP handles therefore have common meaning within an ODP application but have no meaning outside the scope of the application. === Resources and Names Many ODP resource objects, such as pools and queues, support an application-specified character string _name_ that is associated with an ODP object at create time. This name serves two purposes: documentation, and lookup. The lookup function is particularly useful to allow an ODP application that is divided into multiple processes to obtain the handle for the common resource. == Application Portability Considerations ODP is designed to support the creation of portable data plane applications that can easily be run on multiple target platforms while at the same time fully exploit hardware acceleration capabilities native to whatever platform it is running on. This section discusses tradeoffs that application writers should consider when using ODP. First, it should be noted that portability is not an absolute good nor is it a single-valued attribute (application is portable or is not portable). While any application can be ported from one platform to another the real question is: _at what cost?_ Costs can be measured in two dimensions: The level of effort needed to port, and the resulting performance differences seen due to the port. Ideally an application should be portable between platforms with minimal effort and equally minimal performance impact. While ODP is designed to support this ideal, each application must assess what its goals are in this area and how best to use ODP to achieve these goals. === Portability and Coexistence Because ODP offers a programming _framework_ rather than a programming _environment_, it is designed to be able to work alongside APIs offered by other frameworks with minimual interference. Therefore when we speak of portability in an ODP context, we of necessity speak of portability of those portions of the application that make use of ODP APIs. If an application uses non-ODP APIs then those must be taken into consideration as well when assessing the portability of the entire application. For many applications, it suffices to isolate certain non-portable code to a few areas of the application with the result that the application is significantly more portable than it would be without using ODP. Especially when dealing with existing applications that run in production environments, ODP may well be introduced in an incremental manner with the result being that the application becomes more portable only over time. === Source vs. Binary Portability ODP has been designed to support both source and binary portability. Source portability is intrinsic to the ODP API specification itself. Any application written to the ODP API specification will be source portable between any conforming ODP implementation with at most a recompile. This is because ODP APIs do not expose implementation details or internal structures that may vary from platform to platform. For platforms that share a common Instruction Set Architecture (ISA), ODP can also offer binary portability via the specification of an Application Binary Interface (ABI). This is especially useful in a Network Function Virtualization (NFV) environment where a data plane application may be developed and compiled on one platform for distribution and then deployed on many different platforms by an NFV Orchestrator function. === ODP Application Profiles To assist in meeting these needs, ODP offers two distinct _application profiles_ that are designed to characterize the needs of different types of data plane applications: the _Embedded Profile_ and the _Cloud Profile_. ==== Embedded Profile The ODP Embedded Profile is designed to support applications that wish to target a specific platform and achieve optimal performance on that platform and where source code portability is sufficient. If such applications need to support more than one platform then they simply need to be recompiled against the ODP implementation for that platform. Embedded applications will typically work with a copy of ODP downloaded from a git repository so that it can be configured for the application's precise needs. To specify that the application wishes to use the embedded profile: `./configure --enable-abi-compat=no ...` should be used as part of the ODP configuration options. This allows applications to use inline forms of ODP APIs to give optimal performance on this platform, and may include additional optimizations that preclude binary portability to other platforms. The result is a binary that will achieve maximum performance on a given target platform and that can be ported to other platforms with a recompile. ==== Cloud Profile By contrast, the ODP Cloud Profile is designed to support applications that wish to be platform-agnostic and be binary compatible across all platforms sharing this ABI. Any ODP implementation included in a Linux distribution will be configured for the cloud profile, so no additional action is required on the part of applications when compiling against a distributed copy of ODP (one that is installed via `sudo apt-get install` or equivalent command). When using a copy of ODP downloaded from a repository, the cloud profile is selected at configure time: `./configure --enable-abi-compat=yes ...` Note that `--enable-abi-compat=yes` is the default, so this need not be specified. Unless `no` is specified for this option, the result will be applications designed to run in the cloud profile. === ABI Characteristics An ABI consists of several conventions that ensure that a program compiled against one ODP implementation can run unchanged on another platform that has a possibly very different ODP implementation without requiring recompilation. These include: * A set of function calling conventions that define how functions call other functions, pass parameters, and receive returned results. These are typically specified by the Operating System (_e.g.,_ Linux) and are independent of ODP. * Avoiding the use of inline expansions for any ODP API. This ensures that differing ODP implementations can maintain their different internals without these differences being visible to the application. * Agreement as to the size and alignment of ODP abstract datatypes used by all ODP implementations sharing this ABI definition. This means that, for example, the size of an `odp_packet_t` handle is the same across all members of the ABI. Since these handles are opaque, it doesn't matter if their structure differs between ODP implementations since applications never reference these possibly different internals. Note that an ABI definition exists within a specific Instruction Set Architecture (ISA), such as x86-64 or AArch64. Binaries cannot directly port between ISAs--that requires a recompilation. Each ODP implementation will identify which ABI definition it supports, if any. When compiling against an ODP implementation in ABI compabitilty mode, the resulting binary is automatically binary compatible with all other ODP implementations that share this ABI. For example, for the x86-64 ISA, both the `odp-linux` and `odp-dpdk` implemtations are a common ABI. == Shared memory === Allocating shared memory Blocks of shared memory can be created using the `odp_shm_reserve()` API call. The call expects a shared memory block name, a block size, an alignment requirement, and optional flags as parameters. It returns a `odp_shm_t` handle. The size and alignment requirement are given in bytes. The provided name does not have to be unique, i.e. a given name can be used multiple times, when reserving different blocks. .creating a block of shared memory [source,c] ---- #define ALIGNMENT 128 #define BLKNAME ""shared_items"" odp_shm_t shm; uint32_t shm_flags = 0; typedef struct { ... } shared_data_t; shm = odp_shm_reserve(BLKNAME, sizeof(shared_data_t), ALIGNMENT, shm_flags); ---- === Getting the shared memory block address The returned odp_shm_t handle can then be used to retrieve the actual address (in the caller's ODP thread virtual address space) of the created shared memory block. .getting the address of a shared memory block [source,c] ---- shared_data_t *shared_data; shared_data = odp_shm_addr(shm); ---- The address returned by `odp_shm_addr()` is valid only in the calling ODP thread space: odp_shm_t handles can be shared between ODP threads and remain valid within any threads, whereas the address returned by `odp_shm_addr(shm)` may differ from ODP threads to ODP threads (for the same 'shm' block), and should therefore not be shared between ODP threads. For instance, it would be correct to send a shm handle using IPC between two ODP threads and let each of these thread do their own `odp_shm_addr()` to get the block address. Directly sending the address returned by `odp_shm_addr()` from one ODP thread to another would however possibly fail (the address may have no sense in the receiver address space). The address returned by `odp_shm_addr()` is nevertheless guaranteed to be aligned according to the alignment requirements provided at block creation time, even if the call to `odp_shm_addr()` is performed by a different ODP thread than the one which originally called `odp_shm_reserve()`. All shared memory blocks are contiguous in any ODP thread addressing space: 'address' to 'address'\\+'size' (where 'size' is the shared memory block size, as provided in the `odp_shm_reserve()` call) is read and writeable and mapping the shared memory block. There is no fragmentation. === Memory behaviour By default ODP threads are assumed to behave as cache coherent systems: Any change performed on a shared memory block is guaranteed to eventually become visible to other ODP threads sharing this memory block. Nevertheless, there is no implicit memory barrier associated with any action on shared memories: *When* a change performed by an ODP thread becomes visible to another ODP thread is not known: An application using shared memory blocks has to use some memory barrier provided by ODP to guarantee shared data validity between ODP threads. The virtual address at which a given memory block is mapped in different ODP threads may differ from ODP thread to ODP thread, if ODP threads have separate virtual spaces (for instance if ODP threads are implemented as processes). However, the ODP_SHM_SINGLE_VA flag can be used at `odp_shm_reserve()` time to guarantee address uniqueness in all ODP threads, regardless of their implementation or creation time. === Lookup by name As mentioned, shared memory handles can be sent from ODP threads to ODP threads using any IPC mechanism, and then the block address retrieved. A simpler approach to get the shared memory block handle of an already created block is to use the `odp_shm_lookup()` API function call. This nevertheless requires the calling ODP thread to provide the name of the shared memory block: `odp_shm_lookup()` will return `ODP_SHM_INVALID` if no shared memory block with the provided name is known by ODP. When multiple blocks were reserved using the same name, the lookup function will return the handle of any of these blocks. .retrieving a block handle and address from another ODP task [source,c] ---- #define BLKNAME ""shared_items"" odp_shm_t shm; shared_data_t *shared_data; shm = odp_shm_lookup(BLKNAME); if (shm != ODP_SHM_INVALID) { shared_data = odp_shm_addr(shm); ... } ---- === Freeing memory Freeing shared memory is performed using the `odp_shm_free()` API call. `odp_shm_free()` takes one single argument, the shared memory block handle. Any ODP thread is allowed to perform a `odp_shm_free()` on a shared memory block (i.e. the thread performing the `odp_shm_free()` may be different from the thread which did the `odp_shm_reserve()`). Shared memory blocks should be freed only once, and once freed, a shared memory block should no longer be referenced by any ODP threads. .freeing a shared memory block [source,c] ---- if (odp_shm_free(shm) != 0) { ...//handle error } ---- === sharing memory with the external world ODP provides ways of sharing memory with entities located outside ODP instances: Sharing a block of memory with an external (non ODP) thread is achieved by setting the ODP_SHM_PROC flag at `odp_shm_reserve()` time. How the memory block is retrieved on the Operating System side is implementation and Operating System dependent. Sharing a block of memory with an external ODP instance (running on the same Operating System) is achieved by setting the ODP_SHM_EXPORT flag at `odp_shm_reserve()` time. A block of memory created with this flag in an ODP instance A, can be ""mapped"" into a remote ODP instance B (on the same OS) by using the `odp_shm_import()`, on ODP instance B: .sharing memory between ODP instances: instance A [source,c] ---- odp_shm_t shmA; shmA = odp_shm_reserve(""memoryA"", size, 0, ODP_SHM_EXPORT); ---- .sharing memory between ODP instances: instance B [source,c] ---- odp_shm_t shmB; odp_instance_t odpA; /* get ODP A instance handle by some OS method */ odpA = ... /* get the shared memory exported by A: shmB = odp_shm_import(""memoryA"", odpA, ""memoryB"", 0, 0); ---- Note that the handles shmA and shmB are scoped by each ODP instance (you can not use them outside the ODP instance they belong to). Also note that both ODP instances have to call `odp_shm_free()` when done. === Memory creation flags The last argument to odp_shm_reserve() is a set of ORed flags. The following flags are supported: ==== ODP_SHM_PROC When this flag is given, the allocated shared memory will become visible outside ODP. Non ODP threads (e.g. usual linux process or linux threads) will be able to access the memory using native (non ODP) OS calls such as 'shm_open()' and 'mmap' (for linux). Each ODP implementation should provide a description on exactly how this mapping should be done on that specific platform. ==== ODP_SHM_EXPORT When this flag is given, the allocated shared memory will become visible to other ODP instances running on the same OS. Other ODP instances willing to see this exported memory should use the `odp_shm_import()` ODP function. ==== ODP_SHM_SW_ONLY This flag tells ODP that the shared memory will be used by the ODP application software only: no HW (such as DMA, or other accelerator) will ever try to access the memory. No other ODP call will be involved on this memory (as ODP calls could implicitly involve HW, depending on the ODP implementation), except for `odp_shm_lookup()` and `odp_shm_free()`. ODP implementations may use this flag as a hint for performance optimization, or may as well ignore this flag. ==== ODP_SHM_SINGLE_VA This flag is used to guarantee the uniqueness of the address at which the shared memory is mapped: without this flag, a given memory block may be mapped at different virtual addresses (assuming the target have virtual addresses) by different ODP threads. This means that the value returned by `odp_shm_addr()` would be different in different threads, in this case. Setting this flag guarantees that all ODP threads sharing this memory block will see it at the same address (`odp_shm_addr()` would return the same value on all ODP threads, for a given memory block, in this case) Note that ODP implementations may have restrictions of the amount of memory which can be allocated with this flag. == Queues Queues are the fundamental event sequencing mechanism provided by ODP and all ODP applications make use of them either explicitly or implicitly. Queues are created via the 'odp_queue_create()' API that returns a handle of type `odp_queue_t` that is used to refer to this queue in all subsequent APIs that reference it. Queues have one of two ODP-defined _types_, POLL, and SCHED that determine how they are used. POLL queues directly managed by the ODP application while SCHED queues make use of the *ODP scheduler* to provide automatic scalable dispatching and synchronization services. .Operations on POLL queues [source,c] ---- odp_queue_t poll_q1 = odp_queue_create(""poll queue 1"", ODP_QUEUE_TYPE_POLL, NULL); odp_queue_t poll_q2 = odp_queue_create(""poll queue 2"", ODP_QUEUE_TYPE_POLL, NULL); ... odp_event_t ev = odp_queue_deq(poll_q1); ...do something int rc = odp_queue_enq(poll_q2, ev); ---- The key distinction is that dequeueing events from POLL queues is an application responsibility while dequeueing events from SCHED queues is the responsibility of the ODP scheduler. .Operations on SCHED queues [source,c] ---- odp_queue_param_t qp; odp_queue_param_init(&qp); odp_schedule_prio_t prio = ...; odp_schedule_group_t sched_group = ...; qp.sched.prio = prio; qp.sched.sync = ODP_SCHED_SYNC_[NONE|ATOMIC|ORDERED]; qp.sched.group = sched_group; qp.lock_count = n; /* Only relevant for ordered queues */ odp_queue_t sched_q1 = odp_queue_create(""sched queue 1"", ODP_QUEUE_TYPE_SCHED, &qp); ...thread init processing while (1) { odp_event_t ev; odp_queue_t which_q; ev = odp_schedule(&which_q, ); ...process the event } ---- With scheduled queues, events are sent to a queue, and the sender chooses a queue based on the service it needs. The sender does not need to know which ODP thread (on which core) or hardware accelerator will process the event, but all the events on a queue are eventually scheduled and processed. As can be seen, SCHED queues have additional attributes that are specified at queue create that control how the scheduler is to process events contained on them. These include group, priority, and synchronization class. === Scheduler Groups The scheduler's dispatching job is to return the next event from the highest priority SCHED queue that the caller is eligible to receive events from. This latter consideration is determined by the queues _scheduler group_, which is set at queue create time, and by the caller's _scheduler group mask_ that indicates which scheduler group(s) it belongs to. Scheduler groups are represented by handles of type `odp_scheduler_group_t` and are created by the *odp_scheduler_group_create()* API. A number of scheduler groups are _predefined_ by ODP. These include `ODP_SCHED_GROUP_ALL` (all threads), `ODP_SCHED_GROUP_WORKER` (all worker threads), and `ODP_SCHED_GROUP_CONTROL` (all control threads). The application is free to create additional scheduler groups for its own purpose and threads can join or leave scheduler groups using the *odp_scheduler_group_join()* and *odp_scheduler_group_leave()* APIs === Scheduler Priority The `prio` field of the `odp_queue_param_t` specifies the queue's scheduling priority, which is how queues within eligible scheduler groups are selected for dispatch. Queues have a default scheduling priority of NORMAL but can be set to HIGHEST or LOWEST according to application needs. === Scheduler Synchronization In addition to its dispatching function, which provide automatic scalability to ODP applications in many core environments, the other main function of the scheduler is to provide event synchronization services that greatly simplify application programming in a parallel processing environment. A queue's SYNC mode determines how the scheduler handles the synchronization processing of multiple events originating from the same queue. Three types of queue scheduler synchronization area supported: Parallel, Atomic, and Ordered. ==== Parallel Queues SCHED queues that specify a sync mode of ODP_SCHED_SYNC_NONE are unrestricted in how events are processed. .Parallel Queue Scheduling image::parallel_queue.svg[align=""center""] All events held on parallel queues are eligible to be scheduled simultaneously and any required synchronization between them is the responsibility of the application. Events originating from parallel queues thus have the highest throughput rate, however they also potentially involve the most work on the part of the application. In the Figure above, four threads are calling *odp_schedule()* to obtain events to process. The scheduler has assigned three events from the first queue to three threads in parallel. The fourth thread is processing a single event from the third queue. The second queue might either be empty, of lower priority, or not in a scheduler group matching any of the threads being serviced by the scheduler. === Atomic Queues Atomic queues simplify event synchronization because only a single thread may process event(s) from a given atomic queue at a time. Events scheduled from atomic queues thus can be processed lock free because the locking is being done implicitly by the scheduler. Note that the caller may receive one or more events from the same atomic queue if *odp_schedule_multi()* is used. In this case these multiple events all share the same atomic scheduling context. .Atomic Queue Scheduling image::atomic_queue.svg[align=""center""] In this example, no matter how many events may be held in an atomic queue, only one calling thread can receive scheduled events from it at a time. Here two threads process events from two different atomic queues. Note that there is no synchronization between different atomic queues, only between events originating from the same atomic queue. The queue context associated with the atomic queue is held until the next call to the scheduler or until the application explicitly releases it via a call to *odp_schedule_release_atomic()*. Note that while atomic queues simplify programming, the serial nature of atomic queues may impair scaling. === Ordered Queues Ordered queues provide the best of both worlds by providing the inherent scalability of parallel queues, with the easy synchronization of atomic queues. .Ordered Queue Scheduling image::ordered_queue.svg[align=""center""] When scheduling events from an ordered queue, the scheduler dispatches multiple events from the queue in parallel to different threads, however the scheduler also ensures that the relative sequence of these events on output queues is identical to their sequence from their originating ordered queue. As with atomic queues, the ordering guarantees associated with ordered queues refer to events originating from the same queue, not for those originating on different queues. Thus in this figure three thread are processing events 5, 3, and 4, respectively from the first ordered queue. Regardless of how these threads complete processing, these events will appear in their original relative order on their output queue. ==== Order Preservation Relative order is preserved independent of whether events are being sent to different output queues. For example, if some events are sent to output queue A while others are sent to output queue B then the events on these output queues will still be in the same relative order as they were on their originating queue. Similarly, if the processing consumes events so that no output is issued for some of them (_e.g.,_ as part of IP fragment reassembly processing) then other events will still be correctly ordered with respect to these sequence gaps. Finally, if multiple events are enqueued for a given order (_e.g.,_ as part of packet segmentation processing for MTU considerations), then each of these events will occupy the originator's sequence in the target output queue(s). In this case the relative order of these events will be in the order that the thread issued *odp_queue_enq()* calls for them. The ordered context associated with the dispatch of an event from an ordered queue lasts until the next scheduler call or until explicitly released by the thread calling *odp_schedule_release_ordered()*. This call may be used as a performance advisory that the thread no longer requires ordering guarantees for the current context. As a result, any subsequent enqueues within the current scheduler context will be treated as if the thread was operating in a parallel queue context. ==== Ordered Locking Another powerful feature of the scheduler's handling of ordered queues is *ordered locks*. Each ordered queue has associated with it a number of ordered locks as specified by the _lock_count_ parameter at queue create time. Ordered locks provide an efficient means to perform in-order sequential processing within an ordered context. For example, supposed events with relative order 5, 6, and 7 are executing in parallel by three different threads. An ordered lock will enable these threads to synchronize such that they can perform some critical section in their originating queue order. The number of ordered locks supported for each ordered queue is implementation dependent (and queryable via the *odp_config_max_ordered_locks_per_queue()* API). If the implementation supports multiple ordered locks then these may be used to protect different ordered critical sections within a given ordered context. ==== Summary: Ordered Queues To see how these considerations fit together, consider the following code: .Processing with Ordered Queues [source,c] ---- void worker_thread() odp_init_local(); ...other initialization processing while (1) { ev = odp_schedule(&which_q, ODP_SCHED_WAIT); ...process events in parallel odp_schedule_order_lock(0); ...critical section processed in order odp_schedule_order_unlock(0); ...continue processing in parallel odp_queue_enq(dest_q, ev); } } ---- This represents a simplified structure for a typical worker thread operating on ordered queues. Multiple events are processed in parallel and the use of ordered queues ensures that they will be placed on `dest_q` in the same order as they originated. While processing in parallel, the use of ordered locks enables critical sections to be processed in order within the overall parallel flow. When a thread arrives at the *odp_schedule_order_lock()* call, it waits until the locking order for this lock for all prior events has been resolved and then enters the critical section. The *odp_schedule_order_unlock()* call releases the critical section and allows the next order to enter it. === Queue Scheduling Summary NOTE: Both ordered and parallel queues improve throughput over atomic queues due to parallel event processing, but require that the application take steps to ensure context data synchronization if needed. include::users-guide-packet.adoc[] include::users-guide-pktio.adoc[] include::users-guide-timer.adoc[] include::users-guide-crypto.adoc[] include::users-guide-tm.adoc[] include::users-guide-cls.adoc[] include::../glossary.adoc[] ",12060,False,1833.2846602404304,median "module StratSigma where data Sigma0 (A : Set0) (B : A -> Set0) : Set0 where _,_ : (x : A) (y : B x) -> Sigma0 A B _*0_ : (A : Set0)(B : Set0) -> Set0 A *0 B = Sigma0 A \\_ -> B fst0 : {A : Set0}{B : A -> Set0} -> Sigma0 A B -> A fst0 (a , _) = a snd0 : {A : Set0}{B : A -> Set0} (p : Sigma0 A B) -> B (fst0 p) snd0 (a , b) = b data Zero0 : Set0 where data Unit0 : Set0 where Void : Unit0 data Sigma1 (A : Set1) (B : A -> Set1) : Set1 where _,_ : (x : A) (y : B x) -> Sigma1 A B _*1_ : (A : Set1)(B : Set1) -> Set1 A *1 B = Sigma1 A \\_ -> B fst1 : {A : Set1}{B : A -> Set1} -> Sigma1 A B -> A fst1 (a , _) = a snd1 : {A : Set1}{B : A -> Set1} (p : Sigma1 A B) -> B (fst1 p) snd1 (a , b) = b data Zero1 : Set1 where data Unit1 : Set1 where Void : Unit1 data Sigma2 (A : Set2) (B : A -> Set2) : Set2 where _,_ : (x : A) (y : B x) -> Sigma2 A B _*2_ : (A : Set2)(B : Set2) -> Set2 A *2 B = Sigma2 A \\_ -> B fst2 : {A : Set2}{B : A -> Set2} -> Sigma2 A B -> A fst2 (a , _) = a snd2 : {A : Set2}{B : A -> Set2} (p : Sigma2 A B) -> B (fst2 p) snd2 (a , b) = b data Zero2 : Set2 where data Unit2 : Set2 where Void : Unit2 data Sigma3 (A : Set3) (B : A -> Set3) : Set3 where _,_ : (x : A) (y : B x) -> Sigma3 A B _*3_ : (A : Set3)(B : Set3) -> Set3 A *3 B = Sigma3 A \\_ -> B fst3 : {A : Set3}{B : A -> Set3} -> Sigma3 A B -> A fst3 (a , _) = a snd3 : {A : Set3}{B : A -> Set3} (p : Sigma3 A B) -> B (fst3 p) snd3 (a , b) = b data Zero3 : Set3 where data Unit3 : Set3 where Void : Unit3 data Sigma4 (A : Set4) (B : A -> Set4) : Set4 where _,_ : (x : A) (y : B x) -> Sigma4 A B _*4_ : (A : Set4)(B : Set4) -> Set4 A *4 B = Sigma4 A \\_ -> B fst4 : {A : Set4}{B : A -> Set4} -> Sigma4 A B -> A fst4 (a , _) = a snd4 : {A : Set4}{B : A -> Set4} (p : Sigma4 A B) -> B (fst4 p) snd4 (a , b) = b data Zero4 : Set4 where data Unit4 : Set4 where Void : Unit4 data Sigma5 (A : Set5) (B : A -> Set5) : Set5 where _,_ : (x : A) (y : B x) -> Sigma5 A B _*5_ : (A : Set5)(B : Set5) -> Set5 A *5 B = Sigma5 A \\_ -> B fst5 : {A : Set5}{B : A -> Set5} -> Sigma5 A B -> A fst5 (a , _) = a snd5 : {A : Set5}{B : A -> Set5} (p : Sigma5 A B) -> B (fst5 p) snd5 (a , b) = b data Zero5 : Set5 where data Unit5 : Set5 where Void : Unit5 data Sigma6 (A : Set6) (B : A -> Set6) : Set6 where _,_ : (x : A) (y : B x) -> Sigma6 A B _*6_ : (A : Set6)(B : Set6) -> Set6 A *6 B = Sigma6 A \\_ -> B fst6 : {A : Set6}{B : A -> Set6} -> Sigma6 A B -> A fst6 (a , _) = a snd6 : {A : Set6}{B : A -> Set6} (p : Sigma6 A B) -> B (fst6 p) snd6 (a , b) = b data Zero6 : Set6 where data Unit6 : Set6 where Void : Unit6 data Sigma7 (A : Set7) (B : A -> Set7) : Set7 where _,_ : (x : A) (y : B x) -> Sigma7 A B _*7_ : (A : Set7)(B : Set7) -> Set7 A *7 B = Sigma7 A \\_ -> B fst7 : {A : Set7}{B : A -> Set7} -> Sigma7 A B -> A fst7 (a , _) = a snd7 : {A : Set7}{B : A -> Set7} (p : Sigma7 A B) -> B (fst7 p) snd7 (a , b) = b data Zero7 : Set7 where data Unit7 : Set7 where Void : Unit7 data Sigma8 (A : Set8) (B : A -> Set8) : Set8 where _,_ : (x : A) (y : B x) -> Sigma8 A B _*8_ : (A : Set8)(B : Set8) -> Set8 A *8 B = Sigma8 A \\_ -> B fst8 : {A : Set8}{B : A -> Set8} -> Sigma8 A B -> A fst8 (a , _) = a snd8 : {A : Set8}{B : A -> Set8} (p : Sigma8 A B) -> B (fst8 p) snd8 (a , b) = b data Zero8 : Set8 where data Unit8 : Set8 where Void : Unit8 data Sigma9 (A : Set9) (B : A -> Set9) : Set9 where _,_ : (x : A) (y : B x) -> Sigma9 A B _*9_ : (A : Set9)(B : Set9) -> Set9 A *9 B = Sigma9 A \\_ -> B fst9 : {A : Set9}{B : A -> Set9} -> Sigma9 A B -> A fst9 (a , _) = a snd9 : {A : Set9}{B : A -> Set9} (p : Sigma9 A B) -> B (fst9 p) snd9 (a , b) = b data Zero9 : Set9 where data Unit9 : Set9 where Void : Unit9 data Sigma10 (A : Set10) (B : A -> Set10) : Set10 where _,_ : (x : A) (y : B x) -> Sigma10 A B _*10_ : (A : Set10)(B : Set10) -> Set10 A *10 B = Sigma10 A \\_ -> B fst10 : {A : Set10}{B : A -> Set10} -> Sigma10 A B -> A fst10 (a , _) = a snd10 : {A : Set10}{B : A -> Set10} (p : Sigma10 A B) -> B (fst10 p) snd10 (a , b) = b data Zero10 : Set10 where data Unit10 : Set10 where Void : Unit10 data Sigma11 (A : Set11) (B : A -> Set11) : Set11 where _,_ : (x : A) (y : B x) -> Sigma11 A B _*11_ : (A : Set11)(B : Set11) -> Set11 A *11 B = Sigma11 A \\_ -> B fst11 : {A : Set11}{B : A -> Set11} -> Sigma11 A B -> A fst11 (a , _) = a snd11 : {A : Set11}{B : A -> Set11} (p : Sigma11 A B) -> B (fst11 p) snd11 (a , b) = b data Zero11 : Set11 where data Unit11 : Set11 where Void : Unit11 data Sigma12 (A : Set12) (B : A -> Set12) : Set12 where _,_ : (x : A) (y : B x) -> Sigma12 A B _*12_ : (A : Set12)(B : Set12) -> Set12 A *12 B = Sigma12 A \\_ -> B fst12 : {A : Set12}{B : A -> Set12} -> Sigma12 A B -> A fst12 (a , _) = a snd12 : {A : Set12}{B : A -> Set12} (p : Sigma12 A B) -> B (fst12 p) snd12 (a , b) = b data Zero12 : Set12 where data Unit12 : Set12 where Void : Unit12 data Sigma13 (A : Set13) (B : A -> Set13) : Set13 where _,_ : (x : A) (y : B x) -> Sigma13 A B _*13_ : (A : Set13)(B : Set13) -> Set13 A *13 B = Sigma13 A \\_ -> B fst13 : {A : Set13}{B : A -> Set13} -> Sigma13 A B -> A fst13 (a , _) = a snd13 : {A : Set13}{B : A -> Set13} (p : Sigma13 A B) -> B (fst13 p) snd13 (a , b) = b data Zero13 : Set13 where data Unit13 : Set13 where Void : Unit13 data Sigma14 (A : Set14) (B : A -> Set14) : Set14 where _,_ : (x : A) (y : B x) -> Sigma14 A B _*14_ : (A : Set14)(B : Set14) -> Set14 A *14 B = Sigma14 A \\_ -> B fst14 : {A : Set14}{B : A -> Set14} -> Sigma14 A B -> A fst14 (a , _) = a snd14 : {A : Set14}{B : A -> Set14} (p : Sigma14 A B) -> B (fst14 p) snd14 (a , b) = b data Zero14 : Set14 where data Unit14 : Set14 where Void : Unit14 data Sigma15 (A : Set15) (B : A -> Set15) : Set15 where _,_ : (x : A) (y : B x) -> Sigma15 A B _*15_ : (A : Set15)(B : Set15) -> Set15 A *15 B = Sigma15 A \\_ -> B fst15 : {A : Set15}{B : A -> Set15} -> Sigma15 A B -> A fst15 (a , _) = a snd15 : {A : Set15}{B : A -> Set15} (p : Sigma15 A B) -> B (fst15 p) snd15 (a , b) = b data Zero15 : Set15 where data Unit15 : Set15 where Void : Unit15 data Sigma16 (A : Set16) (B : A -> Set16) : Set16 where _,_ : (x : A) (y : B x) -> Sigma16 A B _*16_ : (A : Set16)(B : Set16) -> Set16 A *16 B = Sigma16 A \\_ -> B fst16 : {A : Set16}{B : A -> Set16} -> Sigma16 A B -> A fst16 (a , _) = a snd16 : {A : Set16}{B : A -> Set16} (p : Sigma16 A B) -> B (fst16 p) snd16 (a , b) = b data Zero16 : Set16 where data Unit16 : Set16 where Void : Unit16 data Sigma17 (A : Set17) (B : A -> Set17) : Set17 where _,_ : (x : A) (y : B x) -> Sigma17 A B _*17_ : (A : Set17)(B : Set17) -> Set17 A *17 B = Sigma17 A \\_ -> B fst17 : {A : Set17}{B : A -> Set17} -> Sigma17 A B -> A fst17 (a , _) = a snd17 : {A : Set17}{B : A -> Set17} (p : Sigma17 A B) -> B (fst17 p) snd17 (a , b) = b data Zero17 : Set17 where data Unit17 : Set17 where Void : Unit17 data Sigma18 (A : Set18) (B : A -> Set18) : Set18 where _,_ : (x : A) (y : B x) -> Sigma18 A B _*18_ : (A : Set18)(B : Set18) -> Set18 A *18 B = Sigma18 A \\_ -> B fst18 : {A : Set18}{B : A -> Set18} -> Sigma18 A B -> A fst18 (a , _) = a snd18 : {A : Set18}{B : A -> Set18} (p : Sigma18 A B) -> B (fst18 p) snd18 (a , b) = b data Zero18 : Set18 where data Unit18 : Set18 where Void : Unit18 data Sigma19 (A : Set19) (B : A -> Set19) : Set19 where _,_ : (x : A) (y : B x) -> Sigma19 A B _*19_ : (A : Set19)(B : Set19) -> Set19 A *19 B = Sigma19 A \\_ -> B fst19 : {A : Set19}{B : A -> Set19} -> Sigma19 A B -> A fst19 (a , _) = a snd19 : {A : Set19}{B : A -> Set19} (p : Sigma19 A B) -> B (fst19 p) snd19 (a , b) = b data Zero19 : Set19 where data Unit19 : Set19 where Void : Unit19 data Sigma20 (A : Set20) (B : A -> Set20) : Set20 where _,_ : (x : A) (y : B x) -> Sigma20 A B _*20_ : (A : Set20)(B : Set20) -> Set20 A *20 B = Sigma20 A \\_ -> B fst20 : {A : Set20}{B : A -> Set20} -> Sigma20 A B -> A fst20 (a , _) = a snd20 : {A : Set20}{B : A -> Set20} (p : Sigma20 A B) -> B (fst20 p) snd20 (a , b) = b data Zero20 : Set20 where data Unit20 : Set20 where Void : Unit20 data Sigma21 (A : Set21) (B : A -> Set21) : Set21 where _,_ : (x : A) (y : B x) -> Sigma21 A B _*21_ : (A : Set21)(B : Set21) -> Set21 A *21 B = Sigma21 A \\_ -> B fst21 : {A : Set21}{B : A -> Set21} -> Sigma21 A B -> A fst21 (a , _) = a snd21 : {A : Set21}{B : A -> Set21} (p : Sigma21 A B) -> B (fst21 p) snd21 (a , b) = b data Zero21 : Set21 where data Unit21 : Set21 where Void : Unit21 data Sigma22 (A : Set22) (B : A -> Set22) : Set22 where _,_ : (x : A) (y : B x) -> Sigma22 A B _*22_ : (A : Set22)(B : Set22) -> Set22 A *22 B = Sigma22 A \\_ -> B fst22 : {A : Set22}{B : A -> Set22} -> Sigma22 A B -> A fst22 (a , _) = a snd22 : {A : Set22}{B : A -> Set22} (p : Sigma22 A B) -> B (fst22 p) snd22 (a , b) = b data Zero22 : Set22 where data Unit22 : Set22 where Void : Unit22 data Sigma23 (A : Set23) (B : A -> Set23) : Set23 where _,_ : (x : A) (y : B x) -> Sigma23 A B _*23_ : (A : Set23)(B : Set23) -> Set23 A *23 B = Sigma23 A \\_ -> B fst23 : {A : Set23}{B : A -> Set23} -> Sigma23 A B -> A fst23 (a , _) = a snd23 : {A : Set23}{B : A -> Set23} (p : Sigma23 A B) -> B (fst23 p) snd23 (a , b) = b data Zero23 : Set23 where data Unit23 : Set23 where Void : Unit23 data Sigma24 (A : Set24) (B : A -> Set24) : Set24 where _,_ : (x : A) (y : B x) -> Sigma24 A B _*24_ : (A : Set24)(B : Set24) -> Set24 A *24 B = Sigma24 A \\_ -> B fst24 : {A : Set24}{B : A -> Set24} -> Sigma24 A B -> A fst24 (a , _) = a snd24 : {A : Set24}{B : A -> Set24} (p : Sigma24 A B) -> B (fst24 p) snd24 (a , b) = b data Zero24 : Set24 where data Unit24 : Set24 where Void : Unit24 data Sigma25 (A : Set25) (B : A -> Set25) : Set25 where _,_ : (x : A) (y : B x) -> Sigma25 A B _*25_ : (A : Set25)(B : Set25) -> Set25 A *25 B = Sigma25 A \\_ -> B fst25 : {A : Set25}{B : A -> Set25} -> Sigma25 A B -> A fst25 (a , _) = a snd25 : {A : Set25}{B : A -> Set25} (p : Sigma25 A B) -> B (fst25 p) snd25 (a , b) = b data Zero25 : Set25 where data Unit25 : Set25 where Void : Unit25 data Sigma26 (A : Set26) (B : A -> Set26) : Set26 where _,_ : (x : A) (y : B x) -> Sigma26 A B _*26_ : (A : Set26)(B : Set26) -> Set26 A *26 B = Sigma26 A \\_ -> B fst26 : {A : Set26}{B : A -> Set26} -> Sigma26 A B -> A fst26 (a , _) = a snd26 : {A : Set26}{B : A -> Set26} (p : Sigma26 A B) -> B (fst26 p) snd26 (a , b) = b data Zero26 : Set26 where data Unit26 : Set26 where Void : Unit26 data Sigma27 (A : Set27) (B : A -> Set27) : Set27 where _,_ : (x : A) (y : B x) -> Sigma27 A B _*27_ : (A : Set27)(B : Set27) -> Set27 A *27 B = Sigma27 A \\_ -> B fst27 : {A : Set27}{B : A -> Set27} -> Sigma27 A B -> A fst27 (a , _) = a snd27 : {A : Set27}{B : A -> Set27} (p : Sigma27 A B) -> B (fst27 p) snd27 (a , b) = b data Zero27 : Set27 where data Unit27 : Set27 where Void : Unit27 data Sigma28 (A : Set28) (B : A -> Set28) : Set28 where _,_ : (x : A) (y : B x) -> Sigma28 A B _*28_ : (A : Set28)(B : Set28) -> Set28 A *28 B = Sigma28 A \\_ -> B fst28 : {A : Set28}{B : A -> Set28} -> Sigma28 A B -> A fst28 (a , _) = a snd28 : {A : Set28}{B : A -> Set28} (p : Sigma28 A B) -> B (fst28 p) snd28 (a , b) = b data Zero28 : Set28 where data Unit28 : Set28 where Void : Unit28 data Sigma29 (A : Set29) (B : A -> Set29) : Set29 where _,_ : (x : A) (y : B x) -> Sigma29 A B _*29_ : (A : Set29)(B : Set29) -> Set29 A *29 B = Sigma29 A \\_ -> B fst29 : {A : Set29}{B : A -> Set29} -> Sigma29 A B -> A fst29 (a , _) = a snd29 : {A : Set29}{B : A -> Set29} (p : Sigma29 A B) -> B (fst29 p) snd29 (a , b) = b data Zero29 : Set29 where data Unit29 : Set29 where Void : Unit29 data Sigma30 (A : Set30) (B : A -> Set30) : Set30 where _,_ : (x : A) (y : B x) -> Sigma30 A B _*30_ : (A : Set30)(B : Set30) -> Set30 A *30 B = Sigma30 A \\_ -> B fst30 : {A : Set30}{B : A -> Set30} -> Sigma30 A B -> A fst30 (a , _) = a snd30 : {A : Set30}{B : A -> Set30} (p : Sigma30 A B) -> B (fst30 p) snd30 (a , b) = b data Zero30 : Set30 where data Unit30 : Set30 where Void : Unit30 data Sigma31 (A : Set31) (B : A -> Set31) : Set31 where _,_ : (x : A) (y : B x) -> Sigma31 A B _*31_ : (A : Set31)(B : Set31) -> Set31 A *31 B = Sigma31 A \\_ -> B fst31 : {A : Set31}{B : A -> Set31} -> Sigma31 A B -> A fst31 (a , _) = a snd31 : {A : Set31}{B : A -> Set31} (p : Sigma31 A B) -> B (fst31 p) snd31 (a , b) = b data Zero31 : Set31 where data Unit31 : Set31 where Void : Unit31 data Sigma32 (A : Set32) (B : A -> Set32) : Set32 where _,_ : (x : A) (y : B x) -> Sigma32 A B _*32_ : (A : Set32)(B : Set32) -> Set32 A *32 B = Sigma32 A \\_ -> B fst32 : {A : Set32}{B : A -> Set32} -> Sigma32 A B -> A fst32 (a , _) = a snd32 : {A : Set32}{B : A -> Set32} (p : Sigma32 A B) -> B (fst32 p) snd32 (a , b) = b data Zero32 : Set32 where data Unit32 : Set32 where Void : Unit32 data Sigma33 (A : Set33) (B : A -> Set33) : Set33 where _,_ : (x : A) (y : B x) -> Sigma33 A B _*33_ : (A : Set33)(B : Set33) -> Set33 A *33 B = Sigma33 A \\_ -> B fst33 : {A : Set33}{B : A -> Set33} -> Sigma33 A B -> A fst33 (a , _) = a snd33 : {A : Set33}{B : A -> Set33} (p : Sigma33 A B) -> B (fst33 p) snd33 (a , b) = b data Zero33 : Set33 where data Unit33 : Set33 where Void : Unit33 data Sigma34 (A : Set34) (B : A -> Set34) : Set34 where _,_ : (x : A) (y : B x) -> Sigma34 A B _*34_ : (A : Set34)(B : Set34) -> Set34 A *34 B = Sigma34 A \\_ -> B fst34 : {A : Set34}{B : A -> Set34} -> Sigma34 A B -> A fst34 (a , _) = a snd34 : {A : Set34}{B : A -> Set34} (p : Sigma34 A B) -> B (fst34 p) snd34 (a , b) = b data Zero34 : Set34 where data Unit34 : Set34 where Void : Unit34 data Sigma35 (A : Set35) (B : A -> Set35) : Set35 where _,_ : (x : A) (y : B x) -> Sigma35 A B _*35_ : (A : Set35)(B : Set35) -> Set35 A *35 B = Sigma35 A \\_ -> B fst35 : {A : Set35}{B : A -> Set35} -> Sigma35 A B -> A fst35 (a , _) = a snd35 : {A : Set35}{B : A -> Set35} (p : Sigma35 A B) -> B (fst35 p) snd35 (a , b) = b data Zero35 : Set35 where data Unit35 : Set35 where Void : Unit35 data Sigma36 (A : Set36) (B : A -> Set36) : Set36 where _,_ : (x : A) (y : B x) -> Sigma36 A B _*36_ : (A : Set36)(B : Set36) -> Set36 A *36 B = Sigma36 A \\_ -> B fst36 : {A : Set36}{B : A -> Set36} -> Sigma36 A B -> A fst36 (a , _) = a snd36 : {A : Set36}{B : A -> Set36} (p : Sigma36 A B) -> B (fst36 p) snd36 (a , b) = b data Zero36 : Set36 where data Unit36 : Set36 where Void : Unit36 data Sigma37 (A : Set37) (B : A -> Set37) : Set37 where _,_ : (x : A) (y : B x) -> Sigma37 A B _*37_ : (A : Set37)(B : Set37) -> Set37 A *37 B = Sigma37 A \\_ -> B fst37 : {A : Set37}{B : A -> Set37} -> Sigma37 A B -> A fst37 (a , _) = a snd37 : {A : Set37}{B : A -> Set37} (p : Sigma37 A B) -> B (fst37 p) snd37 (a , b) = b data Zero37 : Set37 where data Unit37 : Set37 where Void : Unit37 data Sigma38 (A : Set38) (B : A -> Set38) : Set38 where _,_ : (x : A) (y : B x) -> Sigma38 A B _*38_ : (A : Set38)(B : Set38) -> Set38 A *38 B = Sigma38 A \\_ -> B fst38 : {A : Set38}{B : A -> Set38} -> Sigma38 A B -> A fst38 (a , _) = a snd38 : {A : Set38}{B : A -> Set38} (p : Sigma38 A B) -> B (fst38 p) snd38 (a , b) = b data Zero38 : Set38 where data Unit38 : Set38 where Void : Unit38 data Sigma39 (A : Set39) (B : A -> Set39) : Set39 where _,_ : (x : A) (y : B x) -> Sigma39 A B _*39_ : (A : Set39)(B : Set39) -> Set39 A *39 B = Sigma39 A \\_ -> B fst39 : {A : Set39}{B : A -> Set39} -> Sigma39 A B -> A fst39 (a , _) = a snd39 : {A : Set39}{B : A -> Set39} (p : Sigma39 A B) -> B (fst39 p) snd39 (a , b) = b data Zero39 : Set39 where data Unit39 : Set39 where Void : Unit39 data Sigma40 (A : Set40) (B : A -> Set40) : Set40 where _,_ : (x : A) (y : B x) -> Sigma40 A B _*40_ : (A : Set40)(B : Set40) -> Set40 A *40 B = Sigma40 A \\_ -> B fst40 : {A : Set40}{B : A -> Set40} -> Sigma40 A B -> A fst40 (a , _) = a snd40 : {A : Set40}{B : A -> Set40} (p : Sigma40 A B) -> B (fst40 p) snd40 (a , b) = b data Zero40 : Set40 where data Unit40 : Set40 where Void : Unit40 data Sigma41 (A : Set41) (B : A -> Set41) : Set41 where _,_ : (x : A) (y : B x) -> Sigma41 A B _*41_ : (A : Set41)(B : Set41) -> Set41 A *41 B = Sigma41 A \\_ -> B fst41 : {A : Set41}{B : A -> Set41} -> Sigma41 A B -> A fst41 (a , _) = a snd41 : {A : Set41}{B : A -> Set41} (p : Sigma41 A B) -> B (fst41 p) snd41 (a , b) = b data Zero41 : Set41 where data Unit41 : Set41 where Void : Unit41 data Sigma42 (A : Set42) (B : A -> Set42) : Set42 where _,_ : (x : A) (y : B x) -> Sigma42 A B _*42_ : (A : Set42)(B : Set42) -> Set42 A *42 B = Sigma42 A \\_ -> B fst42 : {A : Set42}{B : A -> Set42} -> Sigma42 A B -> A fst42 (a , _) = a snd42 : {A : Set42}{B : A -> Set42} (p : Sigma42 A B) -> B (fst42 p) snd42 (a , b) = b data Zero42 : Set42 where data Unit42 : Set42 where Void : Unit42 ",8249,True,3571.334991536969,median "/* * Copyright (C) 2001-2003 Peter J Jones (pjones@pmade.org) * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the Author 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 THE AUTHOR AND CONTRIBUTORS ``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 THE AUTHOR * OR CONTRIBUTORS 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. */ /* * $Id: test_attributes.cpp 478660 2015-09-11 14:34:37Z satskyse $ * NOTE: This file was modified from its original version 0.6.0 * to fit the NCBI C++ Toolkit build framework and * API and functionality requirements. */ #include #include #include #include #include #include USING_NCBI_SCOPE; // A helper function which compares a content of a stream in memory // with a file content on a disk bool compareStreamAndFile( CNcbiOstrstream & stream, const std::string & fileName ) { ifstream ifs( fileName.c_str() ); string fileContent; NcbiStreamToString(&fileContent, ifs); ifs.close(); return string(CNcbiOstrstreamToString(stream)) == fileContent; } // A helper function to save the stream content into a file void saveStreamToFile( CNcbiOstrstream & stream, const std::string & fileName ) { std::ofstream f( fileName.c_str() ); f << string(CNcbiOstrstreamToString(stream)); f.close(); return; } BOOST_AUTO_TEST_CASE( AttributeTest01a ) { try { xml::document doc( ""data/01a.xml"", NULL ); CNcbiOstrstream ostr; const xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i=attrs.begin(), end=attrs.end(); for (; i!=end; ++i) { ostr << i->get_name() << ""="" << i->get_value() << ""\\n""; } saveStreamToFile( ostr, ""data/01a.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/01a.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Reading attribute test (01a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest01b ) { try { xml::document doc( ""data/01b.xml"", NULL ); CNcbiOstrstream ostr; const xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i=attrs.begin(), end=attrs.end(); for (; i!=end; ++i) { ostr << i->get_name() << ""="" << i->get_value() << ""\\n""; } saveStreamToFile( ostr, ""data/01b.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/01b.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Reading attribute test (01b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest01c ) { try { xml::document doc( ""data/01c.xml"", NULL ); CNcbiOstrstream ostr; const xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i=attrs.begin(), end=attrs.end(); for (; i!=end; ++i) { ostr << i->get_name() << ""="" << i->get_value() << ""\\n""; } saveStreamToFile( ostr, ""data/01c.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/01c.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Reading attribute test (01c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest02 ) { try { xml::document doc( ""data/02.xml"", NULL ); CNcbiOstrstream ostr; xml::attributes & attrs = doc.get_root_node().get_attributes(); attrs.insert(""b"", ""b""); ostr << doc; saveStreamToFile( ostr, ""data/02.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/02.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Insert attribute test (02) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest03 ) { try { xml::document doc( ""data/03.xml"", NULL ); const xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i; i = attrs.find( ""one"" ); BOOST_CHECK( i != attrs.end() ); i = attrs.find( ""two"" ); BOOST_CHECK( i != attrs.end() ); i = attrs.find( ""three"" ); BOOST_CHECK( i != attrs.end() ); i = attrs.find( ""missing"" ); BOOST_CHECK( i == attrs.end() ); i = attrs.find( ""also_missing"" ); BOOST_CHECK( i == attrs.end() ); } catch ( ... ) { BOOST_FAIL( ""Find attribute test (03) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest04a ) { try { xml::document doc( ""data/04.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::iterator i = attrs.find( ""attr_one"" ); BOOST_CHECK( i != attrs.end() ); attrs.erase(i); CNcbiOstrstream ostr; ostr << doc; saveStreamToFile( ostr, ""data/04a.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/04a.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Removing attribute test (04a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest04b ) { try { xml::document doc( ""data/04.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::iterator i = attrs.find( ""attr_two"" ); BOOST_CHECK( i != attrs.end() ); attrs.erase(i); CNcbiOstrstream ostr; ostr << doc; saveStreamToFile( ostr, ""data/04b.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/04b.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Removing attribute test (04b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest04c ) { try { xml::document doc( ""data/04.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::iterator i = attrs.find( ""attr_three"" ); BOOST_CHECK( i != attrs.end() ); attrs.erase(i); CNcbiOstrstream ostr; ostr << doc; saveStreamToFile( ostr, ""data/04c.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/04c.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Removing attribute test (04c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest04d ) { try { xml::document doc( ""data/04.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::iterator i = attrs.find( ""attr_four"" ); BOOST_CHECK( i != attrs.end() ); attrs.erase(i); CNcbiOstrstream ostr; ostr << doc; saveStreamToFile( ostr, ""data/04d.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/04d.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Removing attribute test (04d) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest05a ) { try { xml::document doc( ""data/05.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); attrs.erase( ""attr_one"" ); CNcbiOstrstream ostr; ostr << doc; saveStreamToFile( ostr, ""data/05a.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/05a.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Removing attribute test (05a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest05b ) { try { xml::document doc( ""data/05.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); attrs.erase( ""attr_two"" ); CNcbiOstrstream ostr; ostr << doc; saveStreamToFile( ostr, ""data/05b.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/05b.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Removing attribute test (05b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest05c ) { try { xml::document doc( ""data/05.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); attrs.erase( ""attr_three"" ); CNcbiOstrstream ostr; ostr << doc; saveStreamToFile( ostr, ""data/05c.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/05c.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Removing attribute test (05c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest05d ) { try { xml::document doc( ""data/05.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); attrs.erase( ""attr_four"" ); CNcbiOstrstream ostr; ostr << doc; saveStreamToFile( ostr, ""data/05d.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/05d.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Removing attribute test (05d) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest06a ) { try { xml::document doc( ""data/06a.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); CNcbiOstrstream ostr; ostr << attrs.empty() << ""\\n""; saveStreamToFile( ostr, ""data/06a.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/06a.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Empty attribute test (06a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest06b ) { try { xml::document doc( ""data/06b.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); CNcbiOstrstream ostr; ostr << attrs.empty() << ""\\n""; saveStreamToFile( ostr, ""data/06b.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/06b.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Empty attribute test (06b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest07a ) { try { xml::document doc( ""data/07a.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); CNcbiOstrstream ostr; ostr << attrs.size() << ""\\n""; saveStreamToFile( ostr, ""data/07a.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/07a.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Size of attributes test (07a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest07b ) { try { xml::document doc( ""data/07b.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); CNcbiOstrstream ostr; ostr << attrs.size() << ""\\n""; saveStreamToFile( ostr, ""data/07b.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/07b.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Size of attributes test (07b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest07c ) { try { xml::document doc( ""data/07c.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); CNcbiOstrstream ostr; ostr << attrs.size() << ""\\n""; saveStreamToFile( ostr, ""data/07c.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/07c.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Size of attributes test (07c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest07d ) { try { xml::document doc( ""data/07d.xml"", NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); CNcbiOstrstream ostr; ostr << attrs.size() << ""\\n""; saveStreamToFile( ostr, ""data/07d.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/07d.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Size of attributes test (07d) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest08 ) { try { xml::document doc( ""data/08.xml"", NULL ); /* MAKE A COPY! */ xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i = attrs.begin(), end=attrs.end(); CNcbiOstrstream ostr; for (; i!=end; ++i) { ostr << i->get_name() << ""="" << i->get_value() << ""\\n""; } saveStreamToFile( ostr, ""data/08.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/08.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""Attributes copy constructor test (08) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest09a ) { try { xml::document doc( ""data/09.xml"", NULL ); if ( doc.has_internal_subset() && !doc.validate() ) { BOOST_FAIL( ""DTD attributes test (09a) failed"" ); } CNcbiOstrstream ostr; xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i = attrs.find( ""one"" ); ostr << i->get_value() << ""\\n""; ostr << (i == attrs.end() ? ""end"" : ""notend"") << ""\\n""; saveStreamToFile( ostr, ""data/09a.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/09a.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""DTD attributes test (09a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest09b ) { try { xml::document doc( ""data/09.xml"", NULL ); if ( doc.has_internal_subset() && !doc.validate() ) { BOOST_FAIL( ""DTD attributes test (09b) failed"" ); } CNcbiOstrstream ostr; xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i = attrs.find( ""two"" ); ostr << i->get_value() << ""\\n""; ostr << (i == attrs.end() ? ""end"" : ""notend"") << ""\\n""; saveStreamToFile( ostr, ""data/09b.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/09b.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""DTD attributes test (09b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest09c ) { try { xml::document doc( ""data/09.xml"", NULL ); if ( doc.has_internal_subset() && !doc.validate() ) { BOOST_FAIL( ""DTD attributes test (09c) failed"" ); } CNcbiOstrstream ostr; xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i = attrs.find( ""three"" ); ostr << i->get_value() << ""\\n""; ostr << (i == attrs.end() ? ""end"" : ""notend"") << ""\\n""; saveStreamToFile( ostr, ""data/09c.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/09c.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""DTD attributes test (09c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest10 ) { try { xml::document doc( ""data/10.xml"", NULL ); if ( doc.has_internal_subset() && !doc.validate() ) { BOOST_FAIL( ""DTD attributes test (10) failed"" ); } CNcbiOstrstream ostr; xml::attributes & attrs = doc.get_root_node().get_attributes(); xml::attributes::const_iterator i = attrs.find( ""optional"" ); if ( i == attrs.end() ) { ostr << ""****END****\\n""; } else { ostr << i->get_value() << ""\\n""; } saveStreamToFile( ostr, ""data/10.out.real"" ); BOOST_CHECK( compareStreamAndFile( ostr, ""data/10.out"" ) ); } catch ( ... ) { BOOST_FAIL( ""DTD attributes test (10) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest11 ) { try { xml::document doc( ""data/11.xml"", NULL ); xml::node root = doc.get_root_node(); xml::node nested_node( *root.find( ""nested"" ) ); xml::attributes & attrs = nested_node.get_attributes(); xml::ns matched_ns( ""bar"", ""bar_ns"" ); xml::ns not_matched_ns( ""bar"", ""non_existed_uri"" ); xml::ns void_ns( xml::ns::type_void ); { // const iterator xml::attributes::const_iterator i = attrs.find( ""attr"", &matched_ns ); BOOST_CHECK( i != attrs.end() ); i = attrs.find( ""attr"", ¬_matched_ns ); BOOST_CHECK( i == attrs.end() ); i = attrs.find( ""attr"", &void_ns ); BOOST_CHECK( i == attrs.end() ); i = attrs.find( ""attr"", NULL ); BOOST_CHECK( i != attrs.end() ); } { // non-const iterator xml::attributes::iterator i = attrs.find( ""attr"", &matched_ns ); BOOST_CHECK( i != attrs.end() ); i = attrs.find( ""attr"", ¬_matched_ns ); BOOST_CHECK( i == attrs.end() ); i = attrs.find( ""attr"", &void_ns ); BOOST_CHECK( i == attrs.end() ); i = attrs.find( ""attr"", NULL ); BOOST_CHECK( i != attrs.end() ); } } catch ( ... ) { BOOST_FAIL( ""attributes search with namespaces test (11) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest12 ) { try { xml::document doc( ""data/12.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::const_iterator i = attrs.find( ""explicitAttr"" ); BOOST_CHECK( i != attrs.end() ); BOOST_CHECK( i->is_default() == false ); BOOST_CHECK( i->get_value() == std::string( ""explicitVal"" ) ); i = attrs.find( ""defaultAttr"" ); BOOST_CHECK( i != attrs.end() ); BOOST_CHECK( i->is_default() == true ); BOOST_CHECK( i->get_value() == std::string( ""defaultVal"" ) ); } catch ( ... ) { BOOST_FAIL( ""default attributes search test (12) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest13 ) { try { // xml::document doc( ""data/13.xml"", NULL ); // xml::node & root = doc.get_root_node(); // xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k; ++k; BOOST_FAIL( ""Advancing non initialised attributes iterator test (13) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest13a ) { try { xml::document doc( ""data/13.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.end(); ++k; BOOST_FAIL( ""Advancing end() attributes iterator test (13a) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest13b ) { try { xml::document doc( ""data/13.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.end(); xml::attributes::iterator j; BOOST_CHECK( k != j ); } catch ( ... ) { BOOST_FAIL( ""Comparing non-initialized and end() attributes iterators test (13b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest13c ) { try { xml::document doc( ""data/13.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.end(); xml::document doc1( ""data/13.xml"", NULL ); xml::node & root1 = doc1.get_root_node(); xml::attributes & attrs1 = root1.get_attributes(); xml::attributes::iterator k1 = attrs1.end(); BOOST_CHECK( k != k1 ); } catch ( ... ) { BOOST_FAIL( ""Comparing end() attributes iterators from different nodes test (13c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest14 ) { try { xml::document doc( ""data/14.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.find( ""explicitAttr"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == false ); BOOST_CHECK( k->get_value() == std::string( ""explicitVal"" ) ); // It's forbidden to advance find iterators k++; BOOST_FAIL( ""Advancing find(...) iterators test (14) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest14a ) { try { xml::document doc( ""data/14.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.find( ""defaultAttr"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == true ); BOOST_CHECK( k->get_value() == std::string( ""defaultVal"" ) ); // It's forbidden to advance find iterators ++k; BOOST_FAIL( ""Advancing find(...) iterators test (14) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest15 ) { try { xml::document doc( ""data/15.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.find( ""explicitAttr"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == false ); BOOST_CHECK( k->get_value() == std::string( ""explicitVal"" ) ); k->set_value( ""newVal"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == false ); BOOST_CHECK( k->get_value() == std::string( ""newVal"" ) ); xml::attributes::iterator j = attrs.find( ""explicitAttr"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->is_default() == false ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j == k ); } catch ( ... ) { BOOST_FAIL( ""Setting an attribute value test (15) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest15a ) { try { xml::document doc( ""data/15.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.find( ""defaultAttr"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == true ); BOOST_CHECK( k->get_value() == std::string( ""defaultVal"" ) ); k->set_value( ""newVal"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == false ); BOOST_CHECK( k->get_value() == std::string( ""newVal"" ) ); xml::attributes::iterator j = attrs.find( ""defaultAttr"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->is_default() == false ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j == k ); } catch ( ... ) { BOOST_FAIL( ""Setting an attribute value test (15a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest15b ) { try { xml::document doc( ""data/15.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.find( ""defaultAttr"" ); xml::attributes::iterator j = attrs.find( ""defaultAttr"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == true ); BOOST_CHECK( k->get_value() == std::string( ""defaultVal"" ) ); BOOST_CHECK( k == j ); k->set_value( ""newVal"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == false ); BOOST_CHECK( k->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->is_default() == false ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j == k ); } catch ( ... ) { BOOST_FAIL( ""Setting an attribute value test (15b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest16 ) { try { xml::document doc( ""data/16.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.find( ""defaultAttr"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == true ); BOOST_CHECK( k->get_value() == std::string( ""defaultVal"" ) ); BOOST_CHECK( k->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( k->get_namespace().get_uri() == std::string( ""http://some.thing"" ) ); k->set_namespace( ""foo"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == false ); BOOST_CHECK( k->get_value() == std::string( ""defaultVal"" ) ); BOOST_CHECK( k->get_namespace().get_prefix() == std::string( ""foo"" ) ); BOOST_CHECK( k->get_namespace().get_uri() == std::string( ""http://foo.com"" ) ); xml::attributes::iterator j = attrs.find( ""defaultAttr"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->is_default() == false ); BOOST_CHECK( j->get_value() == std::string( ""defaultVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://foo.com"" ) ); BOOST_CHECK( j == k ); } catch ( ... ) { BOOST_FAIL( ""Setting an attribute namespace test (16) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest17 ) { try { xml::document doc( ""data/17.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator k = attrs.find( ""foo:defaultAttr"" ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == true ); BOOST_CHECK( k->get_value() == std::string( ""defaultVal"" ) ); BOOST_CHECK( k->get_namespace().get_prefix() == std::string( ""foo"" ) ); BOOST_CHECK( k->get_namespace().get_uri() == std::string( ""http://foo.com"" ) ); k->erase_namespace(); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == false ); BOOST_CHECK( k->get_value() == std::string( ""defaultVal"" ) ); BOOST_CHECK( k->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( k->get_namespace().get_uri() == std::string( """" ) ); BOOST_CHECK( k->get_namespace().is_void() ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute namespace test (17) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest18 ) { try { xml::document doc( ""data/18.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator end = attrs.end(); xml::attributes::iterator k = attrs.find( ""defaultAttr"" ); xml::attributes::iterator j; BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->is_default() == true ); j = attrs.erase( k ); BOOST_CHECK( j == attrs.end() ); BOOST_CHECK( k->get_name() == std::string( ""defaultAttr"" ) ); BOOST_CHECK( k->get_value() == std::string( ""defaultVal"" ) ); j = attrs.find( ""defaultAttr"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->is_default() == true ); BOOST_CHECK( j->get_name() == std::string( ""defaultAttr"" ) ); BOOST_CHECK( j->get_value() == std::string( ""defaultVal"" ) ); j = attrs.erase( end ); BOOST_CHECK( j == attrs.end() ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (18) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest18a ) { try { xml::document doc( ""data/18.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator j; attrs.erase( j ); BOOST_FAIL( ""Erasing an attribute test - non-initialized iterator (18a) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest18b ) { try { xml::document doc( ""data/18.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::document doc1( ""data/18.xml"", NULL ); xml::node & root1 = doc1.get_root_node(); xml::attributes & attrs1 = root1.get_attributes(); xml::attributes::iterator j = attrs1.find( ""defaultAttr"" ); BOOST_CHECK( j != attrs1.end() ); attrs.erase( j ); BOOST_FAIL( ""Erasing an attribute test - foreign iterator (18b) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest19 ) { try { xml::document doc( ""data/19.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator j = attrs.find( ""foo"" ); xml::attributes::iterator k; BOOST_CHECK( j != attrs.end() ); k = attrs.erase( j ); BOOST_CHECK( k != attrs.end() ); BOOST_CHECK( k->get_name() == std::string( ""bar"" ) ); BOOST_CHECK( k->get_value() == std::string( ""barVal"" ) ); k = attrs.find( ""foo"" ); BOOST_CHECK( k == attrs.end() ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test - foreign iterator (19) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest20 ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); attrs.insert( NULL, ""newVal"", NULL ); BOOST_FAIL( ""Inserting an attribute test - NULL name (20) failed"" ); } catch ( ... ) { // exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest20a ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); attrs.insert( ""foo"", NULL, NULL ); BOOST_FAIL( ""Inserting an attribute test - NULL value (20a) failed"" ); } catch ( ... ) { // exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest20b ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); attrs.insert( "":foo"", ""newVal"", NULL ); BOOST_FAIL( ""Inserting an attribute test - bad attribute name (20b) failed"" ); } catch ( ... ) { // exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest20c ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""prefix"", ""http://uri"" ); attrs.insert( ""some:foo"", ""newVal"", &nspace ); BOOST_FAIL( ""Inserting an attribute test [both qualified name and namespace] (20c) failed"" ); } catch ( ... ) { // exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest20d ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( """", ""http://uri"" ); attrs.insert( ""foo"", ""newVal"", &nspace ); BOOST_FAIL( ""Inserting an attribute test [default namespace] (20d) failed"" ); } catch ( ... ) { // exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest20e ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns void_ns( xml::ns::type_void ); xml::attributes::iterator j = attrs.find( ""foo"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""fooVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( """" ) ); attrs.insert( ""foo"", ""newVal"", & void_ns ); j = attrs.find( ""foo"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( """" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (20e) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest20f ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns void_ns( xml::ns::type_void ); xml::attributes::iterator j = attrs.find( ""fred"" ); BOOST_CHECK( j == attrs.end() ); attrs.insert( ""fred"", ""newVal"", & void_ns ); j = attrs.find( ""fred"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""fred"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( """" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (20f) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest20g ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator j = attrs.find( ""foo"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""fooVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( """" ) ); attrs.insert( ""foo"", ""newVal"", NULL ); j = attrs.find( ""foo"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( """" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (20g) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest20h ) { try { xml::document doc( ""data/20.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator j = attrs.find( ""fred"" ); BOOST_CHECK( j == attrs.end() ); attrs.insert( ""fred"", ""newVal"", NULL ); j = attrs.find( ""fred"" ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""fred"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( """" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (20h) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest21 ) { try { xml::document doc( ""data/21.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""some_ns"", ""http://the.com"" ); xml::attributes::iterator j = attrs.find( ""foo"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""fooVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); attrs.insert( ""some_ns:foo"", ""newVal"", NULL ); j = attrs.find( ""foo"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (21) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest21a ) { try { xml::document doc( ""data/21.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""some_ns"", ""http://the.com"" ); xml::attributes::iterator j = attrs.find( ""fred"", & nspace ); BOOST_CHECK( j == attrs.end() ); attrs.insert( ""some_ns:fred"", ""newVal"", NULL ); j = attrs.find( ""fred"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""fred"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (21a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest22 ) { try { xml::document doc( ""data/22.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns_list_type ns_list = root.get_namespace_definitions( xml::ns::type_unsafe_ns ); BOOST_CHECK( ns_list.size() == 1 ); attrs.insert( ""newName"", ""newVal"", & ns_list[ 0 ] ); BOOST_FAIL( ""Inserting an attribute test (unsafe default namespace) (22) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest23 ) { try { xml::document doc( ""data/23.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns_list_type ns_list = root.get_namespace_definitions( xml::ns::type_unsafe_ns ); BOOST_CHECK( ns_list.size() == 1 ); xml::attributes::iterator j = attrs.find( ""fred"", & ns_list[ 0 ] ); BOOST_CHECK( j == attrs.end() ); attrs.insert( ""fred"", ""newVal"", & ns_list[ 0 ] ); j = attrs.find( ""fred"", & ns_list[ 0 ] ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""fred"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (unsafe namespace) (23) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest23a ) { try { xml::document doc( ""data/23.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns_list_type ns_list = root.get_namespace_definitions( xml::ns::type_unsafe_ns ); BOOST_CHECK( ns_list.size() == 1 ); xml::attributes::iterator j = attrs.find( ""foo"", & ns_list[ 0 ] ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""fooVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); attrs.insert( ""foo"", ""newVal"", & ns_list[ 0 ] ); j = attrs.find( ""foo"", & ns_list[ 0 ] ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (unsafe namespace) (23a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest24 ) { try { xml::document doc( ""data/24.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""some_ns"", ""http://the.com"" ); xml::attributes::iterator j = attrs.find( ""foo"", & nspace ); BOOST_CHECK( j == attrs.end() ); attrs.insert( ""foo"", ""newVal"", & nspace ); j = attrs.find( ""foo"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""foo"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (24) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest24a ) { try { xml::document doc( ""data/24.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""some_ns"", ""http://the.com"" ); xml::attributes::iterator j = attrs.find( ""bar"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""bar"" ) ); BOOST_CHECK( j->get_value() == std::string( ""barVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); attrs.insert( ""bar"", ""newVal"", & nspace ); j = attrs.find( ""bar"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""bar"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (24a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest24b ) { try { xml::document doc( ""data/24.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""not_existing"", ""http://safe.namespace"" ); attrs.insert( ""bar"", ""newVal"", & nspace ); BOOST_FAIL( ""Inserting an attribute test (24b) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest24c ) { try { xml::document doc( ""data/24.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""some_ns"", ""http://the.com"" ); xml::ns void_ns( xml::ns::type_void ); xml::attributes::iterator j = attrs.find( ""bar"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""bar"" ) ); BOOST_CHECK( j->get_value() == std::string( ""barVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); attrs.insert( ""bar"", ""newVal"", & void_ns ); j = attrs.find( ""bar"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""bar"" ) ); BOOST_CHECK( j->get_value() == std::string( ""barVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); j = attrs.find( ""bar"", & void_ns ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_name() == std::string( ""bar"" ) ); BOOST_CHECK( j->get_value() == std::string( ""newVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( """" ) ); } catch ( ... ) { BOOST_FAIL( ""Inserting an attribute test (24c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest24d ) { try { xml::document doc( ""data/24.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); attrs.insert( ""not_existing:newName"", ""newVal"" ); BOOST_FAIL( ""Inserting an attribute test (24d) failed"" ); } catch ( ... ) { // Exception is expected } return; } BOOST_AUTO_TEST_CASE( AttributeTest25 ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); BOOST_CHECK( attrs.erase( NULL, NULL ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25a ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); BOOST_CHECK( attrs.erase( ""non_existing"", NULL ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25b ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); BOOST_CHECK( attrs.erase( ""bar"", NULL ) == 2 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25c ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns default_ns( """", ""http://the.com.not.matched"" ); BOOST_CHECK( attrs.erase( ""bar"", &default_ns ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25d ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns default_ns( """", ""http://the.com"" ); // Matched basing on URI, so some_ns:bar is deleted BOOST_CHECK( attrs.erase( ""bar"", &default_ns ) == 1 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25d) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25e ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""non_existing"", ""http://the.com.space"" ); BOOST_CHECK( attrs.erase( ""bar"", & nspace ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25e) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25f ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns void_ns( xml::ns::type_void ); BOOST_CHECK( attrs.erase( ""bar"", & void_ns ) == 1 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25f) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25g ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns void_ns( xml::ns::type_void ); BOOST_CHECK( attrs.erase( ""kika"", & void_ns ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25g) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25h ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns_list_type ns_list = root.get_namespace_definitions( xml::ns::type_unsafe_ns ); BOOST_CHECK( ns_list.size() == 1 ); BOOST_CHECK( attrs.erase( ""bar"", & ns_list[ 0 ] ) == 1 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25h) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25i ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns_list_type ns_list = root.get_namespace_definitions( xml::ns::type_unsafe_ns ); BOOST_CHECK( ns_list.size() == 1 ); BOOST_CHECK( attrs.erase( ""foo"", & ns_list[ 0 ] ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25i) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25j ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); BOOST_CHECK( attrs.erase( "":foo"", NULL ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25j) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25k ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""some_ns"", ""http://the.com"" ); BOOST_CHECK( attrs.erase( ""whatever:foo"", &nspace ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25k) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25l ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); BOOST_CHECK( attrs.erase( ""some_ns:bar"", NULL ) == 1 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25l) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest25m ) { try { xml::document doc( ""data/25.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); BOOST_CHECK( attrs.erase( ""some_ns:foo"", NULL ) == 0 ); } catch ( ... ) { BOOST_FAIL( ""Erasing an attribute test (25m) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest26 ) { try { xml::document doc( ""data/26.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator j = attrs.find( NULL, NULL ); BOOST_CHECK( j == attrs.end() ); j = attrs.find( NULL ); BOOST_CHECK( j == attrs.end() ); j = attrs.find( "":foo"", NULL ); BOOST_CHECK( j == attrs.end() ); j = attrs.find( "":foo"" ); BOOST_CHECK( j == attrs.end() ); j = attrs.find( ""foo:"", NULL ); BOOST_CHECK( j == attrs.end() ); j = attrs.find( ""foo:"" ); BOOST_CHECK( j == attrs.end() ); } catch ( ... ) { BOOST_FAIL( ""Searching an attribute test (26) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest26a ) { try { xml::document doc( ""data/26.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator j = attrs.find( ""bar"", NULL ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_value() == std::string( ""barVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); xml::ns void_ns( xml::ns::type_void ); j = attrs.find( ""bar"", & void_ns ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_value() == std::string( ""otherBar"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( """" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( """" ) ); } catch ( ... ) { BOOST_FAIL( ""Searching an attribute test (26a) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest26b ) { try { xml::document doc( ""data/26.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::attributes::iterator j = attrs.find( ""some_ns:kika"", NULL ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_value() == std::string( ""zz"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); } catch ( ... ) { BOOST_FAIL( ""Searching an attribute test (26b) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest26c ) { try { xml::document doc( ""data/26.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""some_ns"", ""http://the.com"" ); xml::attributes::iterator j = attrs.find( ""bar"", & nspace ); BOOST_CHECK( j != attrs.end() ); BOOST_CHECK( j->get_value() == std::string( ""barVal"" ) ); BOOST_CHECK( j->get_namespace().get_prefix() == std::string( ""some_ns"" ) ); BOOST_CHECK( j->get_namespace().get_uri() == std::string( ""http://the.com"" ) ); j = attrs.find( ""foo"", & nspace ); BOOST_CHECK( j == attrs.end() ); } catch ( ... ) { BOOST_FAIL( ""Searching an attribute test (26c) failed"" ); } return; } BOOST_AUTO_TEST_CASE( AttributeTest26d ) { try { xml::document doc( ""data/26.xml"", NULL ); xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); xml::ns nspace( ""some_ns"", ""http://the.wrong.com"" ); xml::attributes::iterator j = attrs.find( ""non-existing:bar"" ); BOOST_CHECK( j == attrs.end() ); j = attrs.find( ""bar"", & nspace ); BOOST_CHECK( j == attrs.end() ); } catch ( ... ) { BOOST_FAIL( ""Searching an attribute test (26d) failed"" ); } return; } // The AttributeTest27 test must not produce core dump xml::attributes::attr & insert_attr(xml::document & doc) { xml::node & root = doc.get_root_node(); xml::attributes & attrs = root.get_attributes(); attrs.insert(""name"", ""value""); xml::attributes::iterator new_attr = attrs.find( ""name"" ); if (new_attr == attrs.end()) throw ""Unexpected behavior""; return *new_attr; } BOOST_AUTO_TEST_CASE( AttributeTest27 ) { std::string xmldata( """" ); xml::document doc( xmldata.c_str(), xmldata.size(), NULL ); xml::attributes::attr & a = insert_attr( doc ); BOOST_CHECK( string( a.get_value() ) == string( ""value"" ) ); BOOST_CHECK( string( a.get_name() ) == string( ""name"" ) ); xml::attributes::iterator found = doc.get_root_node().get_attributes().find( ""name"" ); BOOST_CHECK( string( found->get_value() ) == string( ""value"" ) ); BOOST_CHECK( string( found->get_name() ) == string( ""name"" ) ); xml::attributes::const_iterator c_found = doc.get_root_node().get_attributes().find( ""name"" ); BOOST_CHECK( string( c_found->get_value() ) == string( ""value"" ) ); BOOST_CHECK( string( c_found->get_name() ) == string( ""name"" ) ); found->set_value( ""bla"" ); BOOST_CHECK( string( found->get_value() ) == string( ""bla"" ) ); BOOST_CHECK( string( found->get_name() ) == string( ""name"" ) ); BOOST_CHECK( string( c_found->get_value() ) == string( ""bla"" ) ); BOOST_CHECK( string( c_found->get_name() ) == string( ""name"" ) ); BOOST_CHECK( string( a.get_value() ) == string( ""bla"" ) ); BOOST_CHECK( string( a.get_name() ) == string( ""name"" ) ); } BOOST_AUTO_TEST_CASE( AttributeTest28 ) { std::string xmldata( """" ); xml::document doc( xmldata.c_str(), xmldata.size(), NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); try { attrs.insert("""", ""b""); BOOST_FAIL( ""Insert attribute test (28) failed"" ); } catch ( ... ) { // Exception is expected ; } } BOOST_AUTO_TEST_CASE( AttributeTest29 ) { std::string xmldata( """" ); xml::document doc( xmldata.c_str(), xmldata.size(), NULL ); xml::attributes & attrs = doc.get_root_node().get_attributes(); try { attrs.insert("" \\r \\n \\t "", ""b""); BOOST_FAIL( ""Insert attribute test (29) failed"" ); } catch ( ... ) { // Exception is expected ; } } ",16345,True,4342.330407384743,median "= Payment Plugin Overview Payment plugins integrate Kill Bill with a specific gateway (i.e. payment processor), such as Stripe or Braintree. We already have many open-source payment plugins available on GitHub as follows: . https://github.com/killbill/killbill-stripe-plugin[_killbill-stripe-plugin_] - Plugin to use https://stripe.com/[_Stripe_] as the payment gateway . https://github.com/killbill/killbill-adyen-plugin[_killbill-adyen-plugin_] - Plugin to use https://www.adyen.com/[_Adyen_] as the payment gateway . https://github.com/killbill/killbill-qualpay-plugin[_killbill-qualpay-plugin_] - Plugin to use https://www.qualpay.com/[_QualPay_] as the payment gateway This guide will give you pointers in case you need to develop your own payment plugin. Before reading this guide, make sure to familiarize yourself with https://docs.killbill.io/latest/userguide_subscription.html#components-payment[payment components] and the https://docs.killbill.io/latest/userguide_payment.html[payment userguide]. == Developing a Payment Plugin We provide an interface called https://github.com/killbill/killbill-plugin-api/blob/master/payment/src/main/java/org/killbill/billing/payment/plugin/api/PaymentPluginApi.java[PaymentPluginApi]. This is the interface between Kill Bill and payment plugins. In order to create your own payment plugin, you need to create a class that implements this interface and implement the methods in this interface. We provide a https://github.com/killbill/killbill-plugin-framework-java[plugin framework] which has many classes that can be used out of the box for plugin development. We strongly encourage you to use this library. == Getting Started We provide a simple https://github.com/killbill/killbill-hello-world-java-plugin[_Hello World Plugin_] that can be used as the starting point to develop your payment plugin. The *Hello World Plugin* already includes the plugin framework. In order to get started with your own payment plugin, you need to do the following: . Set up the *Hello World Plugin* as per our https://docs.killbill.io/latest/plugin_development.html#_development[__Plugin Development__] document. . Create a new Maven project similar to *Hello World Plugin*. . Create a class similar to https://github.com/killbill/killbill-hello-world-java-plugin/blob/719779b1ea25c14928e92996b6aa21cc9bf8d4fe/src/main/java/org/killbill/billing/plugin/helloworld/HelloWorldPaymentPluginApi.java[HelloWorldPaymentPluginApi.java]. This is a reference class that is included in the *Hello World Plugin*. It implements the `PaymentPluginApi` interface. . Implement the desired methods from the `PaymentPluginApi` interface within your class. These methods are explained in the <> table below. . Create a class similar to https://github.com/killbill/killbill-hello-world-java-plugin/blob/719779b1ea25c14928e92996b6aa21cc9bf8d4fe/src/main/java/org/killbill/billing/plugin/helloworld/HelloWorldActivator.java[HelloWorldActivator]. This class will be responsible for starting the plugin. [[paymentpluginapi_methods]] == PaymentPluginApi Methods The following table lists the methods in https://github.com/killbill/killbill-plugin-api/blob/master/payment/src/main/java/org/killbill/billing/payment/plugin/api/PaymentPluginApi.java[PaymentPluginApi] interface. You can implement the desired methods in your plugin class. |=== |Method Name | Method Description |authorizePayment/ capturePayment |Should trigger an https://en.wikipedia.org/wiki/Authorization_hold[_authorization_] and capture respectfully (applies to credit cards only) |purchasePayment |Should trigger a generic payment (authorization with auto-capture for credit cards, ACH/SEPA, etc.) |voidPayment |Should void an authorization (credit cards only) |creditPayment |Should fund the payment method from your merchant account (similar to a refund, but no prior payment is required: this can be used to initiate an ACH for disbursement for instance) |refundPayment |Should reverse an existing (settled) charge |getPaymentInfo |Should return detailed information on the transactions for that payment (arbitrary properties can be populated in PaymentTransactionInfoPlugin#getProperties) |searchPayments |Should return payment transactions matching the specified searchKey (the implementation is up to the plugin) |addPaymentMethod |Should create the payment method in the gateway (e.g. store a token) |deletePaymentMethod |Should delete the payment method in the gateway (e.g. revoke a token) |getPaymentMethodDetail |Should return detailed information about the payment method (e.g. billing address) |setDefaultPaymentMethod |Should mark the payment method as the default one in the gateway (if the associated account in the gateway has several payment methods) |getPaymentMethods |Should list the payment methods in the gateway for that account (used by the refresh endpoint, when payment methods are added directly in the gateway, bypassing addPaymentMethod) |searchPaymentMethods |Should return payment methods matching the specified searchKey (the implementation is up to the plugin) |resetPaymentMethods |Called at the end of a refresh call, should associate to that account the payment methods specified (this is useful if Kill Bill knows payment methods that are not yet in the gateway) |buildFormDescriptor |Should return enough metadata for the front-end to build a form or a redirect to a hosted payment page |processNotification |Should process payloads from the gateway to transition payments states |=== A few pointers for implementing these methods: * Almost all the `PaymentPluginApi` methods accept parameters like *Kill Bill account Id*, *Kill Bill payment id*, *Kill Bill transaction id*, etc. which are self-explanatory. These may or may not be used by your plugin code. But you may need some of these values to populate the <> object which is returned by most of the methods. * All the methods listed in the `PaymentPluginApi` also accept `Iterable properties` as a parameter. A https://github.com/killbill/killbill-api/blob/4ae1c343a593de937415e21feecb9f5405037fa3/src/main/java/org/killbill/billing/payment/api/PluginProperty.java[PluginProperty] consists of a *key-value* pair. It can be used to pass plugin specific properties to the plugin. For example, if your plugin requires properties like *city=San Francisco* and *billing_address=abc*, a client application can create two `PluginProperty` objects and pass a `List` of these objects. * All the methods listed in the `PaymentPluginApi` also accept as parameter either a `TenantContext` or a `CallContext`. Read only operations (operations which retrieve some data from Kill Bill) like the `getPaymentInfo` accept a `TenantContext`. Read/write operations like `authorizePayment` accept a `CallContext`. Both these values can be used for auditing purposes. * It is quite possible that your plugin might not support some of the operations listed above. In such a case, the plugin can do one of the following: ** Return an *empty list* when the return type is a list ** Return a transaction with status *CANCELED* if the return type is a `PaymentTransactionInfoPlugin` ** Return empty objects otherwise [[PaymentTransactionInfoPlugin]] == PaymentTransactionInfoPlugin Most of the methods in the `PaymentPluginApi` return a https://github.com/killbill/killbill-api/blob/4ae1c343a593de937415e21feecb9f5405037fa3/src/main/java/org/killbill/billing/payment/plugin/api/PaymentTransactionInfoPlugin.java[PaymentTransactionInfoPlugin] object. Again, the Kill Bill Plugin framework includes a class called https://github.com/killbill/killbill-plugin-framework-java/blob/46d94fbeb1cf089aa04e62cfecf751ca47032023/src/main/java/org/killbill/billing/plugin/api/payment/PluginPaymentTransactionInfoPlugin.java[ PluginPaymentTransactionInfoPlugin] which implements the `PaymentTransactionInfoPlugin`. You can create a class that extends this class and have the plugin methods return this object. The `PaymentTransactionInfoPlugin` has the following methods (Your plugin code needs to populate this information in the `PaymentTransactionInfoPlugin` object and a client application can then invoke these methods to retrieve this information): |=== |Method Name | Method Description |getKbPaymentId |Returns Payment Id in Kill Bill |getKbTransactionPaymentId |Returns Transaction Payment Id in Kill Bill |getTransactionType |Returns the transaction type (https://github.com/killbill/killbill-api/blob/4ae1c343a593de937415e21feecb9f5405037fa3/src/main/java/org/killbill/billing/payment/api/TransactionType.java[TransactionType] object) |getAmount |Returns the processed amount |getCurrency |Returns the processed currency |getCreatedDate |Returns the date when the payment was created |getEffectiveDate |Returns the date when the payment is effective |getStatus | Returns the payment status (https://github.com/killbill/killbill-api/blob/4ae1c343a593de937415e21feecb9f5405037fa3/src/main/java/org/killbill/billing/payment/plugin/api/PaymentPluginStatus.java[PaymentPluginStatus] object) |getGatewayError |Returns the gateway error if any |getGatewayErrorCode |Returns the gateway error code if any |getFirstPaymentReferenceId |Returns gateway specific first payment id if any |getSecondPaymentReferenceId |Returns gateway specific second payment id if any |getProperties |Returns a `PluginProperty` List. This can be used to return plugin specific properties to the client API |=== It is very important to correctly populate the https://github.com/killbill/killbill-api/blob/4ae1c343a593de937415e21feecb9f5405037fa3/src/main/java/org/killbill/billing/payment/plugin/api/PaymentPluginStatus.java[PaymentPluginStatus] in the `PaymentTransactionInfoPlugin` object. The following table elaborates how the status should be populated: |=== |Status | Status Description |PROCESSED |Indicates that the payment is successful |ERROR |Indicates that the payment is rejected by the gateway (insufficient funds, fails AVS check, fraud detected, etc.) |PENDING |Indicates that the payment requires a completion step (3D-S verification, HPP, etc.) |CANCELED |Indicates that the gateway wasn't contacted (DNS error, SSL handshake error, socket connect timeout, etc.) |UNDEFINED |Should be used for all other cases (socket read timeout, 500 returned, etc.) |=== Kill Bill has a https://docs.killbill.io/latest/userguide_payment.html#_janitor[_Janitor_] system in place that attempts to fix *PENDING* and *UNKNOWN* states . It polls the plugin via `PaymentPluginApi#getPaymentInfo` method. If the plugin subsequently returns *PROCESSED*, the Janitor updates the internal payment state as well as invoice balance, etc.) accordingly. The Janitor matches the internal transactions against plugin transactions via the *transaction id*, so make sure `PaymentTransactionInfoPlugin#getKbTransactionPaymentId` is correctly implemented. You should try to avoid *UNDEFINED* as much as possible, because it is the only case where Kill Bill cannot retry payments (since the payment may or may not have happened). == GoCardless Plugin Tutorial In order to demonstrate creating a payment plugin, we will be creating a Kill Bill payment plugin for https://gocardless.com/[_GoCardless_]. GoCardless allows direct debit from customer's bank accounts. It requires a customer to set up a *mandate* the first time. A *mandate* is an *authorisation* from a customer to take payments from their bank account. Once a mandate is set up, it directly collects payments against the mandate. GoCardless provides a https://developer.gocardless.com/getting-started/api/making-your-first-request/#setting-up-your-client-library[_client library_]. We will be using this library to integrate GoCardless with Kill Bill. For the sake of simplicity, we will be creating a very basic plugin that can only process payments. Refunds, credits and other plugin functionality will currently not be implemented. The complete code for this tutorial is available on https://github.com/killbill/killbill-gocardless-example-plugin[_Github_]. === How GoCardless Works The first step in GoCardless would be adding a customer and setting up a payment mandate. GoCardless supports three ways to do this as explained https://developer.gocardless.com/getting-started/api/adding-your-first-customer/[here]. In this tutorial, we will be using the *hosted payment page* approach which is explained https://developer.gocardless.com/getting-started/api/adding-your-first-customer/#setting-up-direct-debit-mandates-using-hosted-payment-pages[here]. The diagram below explains the steps involved. We consider the following actors: *Browser*: user sitting behind a browser and initiating the payment flow *Merchant Site*: customer facing web site which receives the order *GoCardless*: The GoCardless payment system *Bank* - Customer's bank which processes the payments image:https://github.com/killbill/killbill-docs/raw/v3/userguide/assets/img/payment-plugin/How-Go-Cardless-Works.png[align=center] . A user enters his/her payment details on a merchant site. . The merchant site *initiates* the *GoCardless Redirect flow* with the *customer details* (optional) and a *success page URL*. . *GoCardless* returns a *redirect URL*. . The merchant site redirects the user to this URL. . The user *manually* enters bank details at this page. . If successful, GoCardless redirects the user to the *success page URL* sent to it in step 1. . The merchant site *completes* the *GoCardless Redirect flow* . . GoCardless then actually sets up the mandate with the customer's bank. . If successful, it returns a *mandate Id* to the merchant site. . The merchant site then charges the customer against the *mandate Id* as required. [[using_gocardless_from_killbill]] === Using GoCardless from Kill Bill In order to use GoCardless from Kill Bill, we will need to create a payment plugin corresponding to GoCardless. Since we are developing a very basic plugin that can only process payments, we only need to do the following: . Set up the mandate. This is a two step process as explained above where: .. Step 1 involves redirecting the user to a page to manually confirm setting up the mandate. This can be implemented via the `PaymentPluginApi#buildFormDescriptor` method .. Step 2 involves completing the GoCardless flow and retrieving the mandate Id. This can be implemented via the `PaymentPluginApi#addPaymentMethod` method . Implement the `PaymentPluginApi#purchasePayment` method to charge the customer The diagram below explains the end-to-end flow. We consider the following actors: *Browser*: user sitting behind a browser and initiating the payment flow *Merchant Site*: customer facing web site which receives the order *Kill Bill* - The Kill Bill system *Checkout Servlet* - Servlet that initiates setting up the payment method. This is explained https://docs.killbill.io/latest/payment_plugin.html#_step_9_creating_gocardlesscheckoutservlet[further] in detail *GoCardless Plugin*: Payment plugin corresponding to GoCardless that can process payments using the GoCardless system *GoCardless*: The GoCardless payment system image:https://github.com/killbill/killbill-docs/raw/v3/userguide/assets/img/payment-plugin/Using-GoCardless-From-KillBill.png[align=center] . A user enters his/her payment details on a merchant site. . The merchant site invokes the `Checkout Servlet`. . The `Checkout Servlet` invokes the `GoCarldessPlugin#buildFormDescriptor`. . The `GoCarldessPlugin#buildFormDescriptor` method invokes the `redirectFlows().create()`. This *initiates* the *GoCardless redirect flow* and returns the *redirect URL* . . The merchant site redirects the user to this URL. . The user manually enters bank details on this page. . GoCardless redirects the user to the *success page*. . The merchant site invokes the `KillBill#addPaymentMethod` which in turn invokes `GoCardlessPlugin#addPaymentMethod`. . The `GoCarldessPlugin#addPaymentMethod` invokes `redirectFlows().complete`. This *completes* the *redirect flow* and returns the *mandate id* which is saved in the Kill Bill database. . The merchant site can then invoke `KillBill#purchasePayment` as required. This in turn invokes `GoCardlessPlugin#purchasePayment`. . The `GoCardlessPlugin#purchasePayment` invokes the `payments().create()` to charge the customer against the saved *mandate id* as explained https://developer.gocardless.com/getting-started/api/taking-your-first-payment/[here]. === Creating the GoCardless Plugin Let us now understand how we can create a payment plugin for GoCardless. ==== Step 1 - Initial Setup The first step in creating a payment plugin would be to create a new Maven project. For this we need to do the following: . Create a new Maven project. . Copy the https://github.com/killbill/killbill-hello-world-java-plugin/blob/719779b1ea25c14928e92996b6aa21cc9bf8d4fe/pom.xml[Hello World Plugin pom.xml]. . Generate a GoCardless access token (https://manage-sandbox.gocardless.com/developers) and create an environment variable *GC_ACCESS_TOKEN* with this token. ==== Step 2 - Creating GoCardlessPluginApi We will first need to create a class similar to `HelloWorldPaymentPluginApi` that implements the `PaymentPluginApi` interface. We can create this class as follows (See https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessPaymentPluginApi.java[_GoCardlessPaymentPluginApi.java_]): [source,java,linenums] public class GoCardlessPaymentPluginApi implements PaymentPluginApi { private static final Logger logger = LoggerFactory.getLogger(GoCardlessPaymentPluginApi.class); private OSGIKillbillAPI killbillAPI; private Clock clock; private static String GC_ACCESS_TOKEN_PROPERTY = ""GC_ACCESS_TOKEN""; private GoCardlessClient client; public GoCardlessPaymentPluginApi(final OSGIKillbillAPI killbillAPI,final Clock clock) { this.killbillAPI = killbillAPI; this.clock = clock; client = GoCardlessClient.newBuilder(System.getenv(GC_ACCESS_TOKEN_PROPERTY)).withEnvironment(GoCardlessClient.Environment.SANDBOX).build(); } //other methods } * The `GoCardlessPaymentPluginApi` implements the `PaymentPluginApi` interface. * It declares the following fields: ** `killbillAPI` - This is of type https://github.com/killbill/killbill-platform/blob/617d4b626ddd7c081d2927355c6f8cfe2cbd4bd5/osgi-bundles/libs/killbill/src/main/java/org/killbill/billing/osgi/libs/killbill/OSGIKillbillAPI.java[OSGIKillbillAPI]. The `OSGIKillBillAPI` is a Kill Bill class which exposes all of Kill Bill’s internal APIs. ** `GC_ACCESS_TOKEN_PROPERTY` - This is a String field that is required for accessing the GoCardless access token ** `clock` - This is of type https://github.com/killbill/killbill-commons/blob/aa83708f56377aabff8391c3ddc197817ad19ec2/clock/src/main/java/org/killbill/clock/Clock.java[Clock]. This is part of Kill Bill's clock library. ** `client` This is of type http://gocardless.github.io/gocardless-pro-java/com/gocardless/GoCardlessClient.html[GoCardlessClient]. This is a GoCardless specific class that can be used to access the GoCardless API * The constructor simply initializes the fields with the values passed in. In addition, it also creates a GoCardless client and initializes the `client` field Within this class, we need to implement the `buildFormDescriptor`, `addPaymentMethod` and `purchasePayment` as explained in the <> section above. ==== Step 3 - Creating GoCardlessPaymentTransactionInfoPlugin As explained earlier, most of the `PaymentPluginApi` methods return a <> object. Thus, we need to create a class corresponding to this as follows (See https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessPaymentTransactionInfoPlugin.java[_GoCardlessPaymentTransactionInfoPlugin.java_]): [source,java,linenums] public class GoCardlessPaymentTransactionInfoPlugin extends PluginPaymentTransactionInfoPlugin{ public GoCardlessPaymentTransactionInfoPlugin(UUID kbPaymentId, UUID kbTransactionPaymentPaymentId, TransactionType transactionType, BigDecimal amount, Currency currency, PaymentPluginStatus pluginStatus, String gatewayError, String gatewayErrorCode, String firstPaymentReferenceId, String secondPaymentReferenceId, DateTime createdDate, DateTime effectiveDate, List properties) { super(kbPaymentId, kbTransactionPaymentPaymentId, transactionType, amount, currency, pluginStatus, gatewayError, gatewayErrorCode, firstPaymentReferenceId, secondPaymentReferenceId, createdDate, effectiveDate, properties); } } * The `GoCardlessPaymentTransactionInfoPlugin` extends the https://github.com/killbill/killbill-plugin-framework-java/blob/46d94fbeb1cf089aa04e62cfecf751ca47032023/src/main/java/org/killbill/billing/plugin/api/payment/PluginPaymentTransactionInfoPlugin.java[PluginPaymentTransactionInfoPlugin] from the https://github.com/killbill/killbill-plugin-framework-java[Kill Bill plugin framework]. This class in turn implements the <> interface * The `GoCardlessPaymentTransactionInfoPlugin` constructor accepts parameters corresponding to the data to be returned by <>. It simply invokes the superclass constructor with these parameters ==== Step 4 - Implementing GoCardlessPaymentPluginApi#buildFormDescriptor The `buildFormDesciptor` is typically used for https://docs.killbill.io/latest/userguide_payment.html#_hosted_payment_page_flow[hosted payment flows] to display a form where a user can enter his/her payment details. In the case of GoCardless, we will be using it to *initiate* the *Gocardless redirect flow* in GoCardless and obtain the *redirect URL*. This method can be implemented as follows (See https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessPaymentPluginApi.java#L293[_GoCardlessPaymentPluginApi.buildFormDescriptor_]): [source,java,linenums] public HostedPaymentPageFormDescriptor buildFormDescriptor(UUID kbAccountId, Iterable customFields, Iterable properties, CallContext context) throws PaymentPluginApiException { logger.info(""buildFormDescriptor, kbAccountId="" + kbAccountId); // retrieve properties String successRedirectUrl = PluginProperties.findPluginPropertyValue(""success_redirect_url"", properties); // ""https://developer.gocardless.com/example-redirect-uri/""; - this is the URL to which GoCardless will redirect after users set up the mandate String redirectFlowDescription = PluginProperties.findPluginPropertyValue(""redirect_flow_description"",properties); String sessionToken = PluginProperties.findPluginPropertyValue(""session_token"", properties); PrefilledCustomer customer = buildCustomer(customFields);// build a PrefilledCuctomer object from custom fields if present RedirectFlow redirectFlow = client.redirectFlows().create().withDescription(redirectFlowDescription) .withSessionToken(sessionToken) .withSuccessRedirectUrl(successRedirectUrl).withPrefilledCustomer(customer).execute(); logger.info(""RedirectFlow Id"", redirectFlow.getId()); logger.info(""RedirectFlow URL"", redirectFlow.getRedirectUrl()); PluginHostedPaymentPageFormDescriptor pluginHostedPaymentPageFormDescriptor = new PluginHostedPaymentPageFormDescriptor( kbAccountId, redirectFlow.getRedirectUrl()); return pluginHostedPaymentPageFormDescriptor; } * The `buildFormDescriptor` method accepts `Iterable properties` as a parameter. As explained above, a `PluginProperty` can be used to pass a plugin specific key-value pair to a plugin. * The code first retrieves the `successRedirectUrl`, `redirectFlowDescription` and `sessionToken` sent by the client application from the `properties` passed in. These are required by GoCardless and are as explained below: ** `successRedirectUrl` - Indicates the page to which the user should be redirected after setting up the mandate successfully. ** `redirectFlowDescription` - is a description that is displayed on the payment page (page where the user is redirected to set up the mandate) ** `sessionToken` - is something that identifies the user’s session on the client application. GoCardless requires this to be supplied while *creating the redirect flow* (now, while invoking the `buildFormDescriptor` method), and while *completing the redirect flow* (when the `addPaymentMethod` is invoked) it at the end. Supplying this token twice makes sure that the person who completed the redirect flow is the person who initiated it. * Next, the `client.redirectFlows().create()` is invoked with the `successRedirectUrl`, `redirectFlowDescription` and `sessionToken`. This returns a `RedirectFlow` object. The `RedirectFlow` object contains the *redirect URL*. * Finally, a `HostedPaymentPageFormDescriptor` object is created using the *redirect URL* and the *Kill Bill Account Id*. This is then returned to the client application. ==== Step 5 - Implementing GoCardlessPaymentPluginApi#addPaymentMethod The `addPaymentMethod` is typically used to add a payment method in Kill Bill corresponding to a customer/account. In the case of GoCardless, we will be using it to *complete* the *redirect flow*. So, this method can be implemented as follows (See https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessPaymentPluginApi.java#L223[_GoCardlessPaymentPluginApi#addPaymentMethod_]): [source,java,linenums] public void addPaymentMethod(UUID kbAccountId, UUID kbPaymentMethodId, PaymentMethodPlugin paymentMethodProps, boolean setDefault, Iterable properties, CallContext context) throws PaymentPluginApiException { logger.info(""addPaymentMethod, kbAccountId="" + kbAccountId); final Iterable allProperties = PluginProperties.merge(paymentMethodProps.getProperties(), properties); String redirectFlowId = PluginProperties.findPluginPropertyValue(""redirect_flow_id"", allProperties); //retrieve the redirect flow id String sessionToken = PluginProperties.findPluginPropertyValue(""session_token"", allProperties); try { //Use the redirect flow id to ""complete"" the GoCardless flow RedirectFlow redirectFlow = client.redirectFlows().complete(redirectFlowId).withSessionToken(sessionToken).execute(); String mandateId = redirectFlow.getLinks().getMandate(); //obtain mandate id from the redirect flow logger.info(""MandateId:"", mandateId); try { //save Mandate id in the Kill Bill database killbillAPI.getCustomFieldUserApi().addCustomFields(ImmutableList.of(new PluginCustomField(kbAccountId, ObjectType.ACCOUNT, ""GOCARDLESS_MANDATE_ID"", mandateId, clock.getUTCNow())), context); } catch (CustomFieldApiException e) { logger.warn(""Error occured while saving mandate id"", e); throw new PaymentPluginApiException(""Error occured while saving mandate id"", e); } } catch (GoCardlessApiException e) { logger.warn(""Error occured while completing the GoCardless flow"", e.getType(), e); throw new PaymentPluginApiException(""Error occured while completing the GoCardless flow"", e); } } * Like other methods, the `addPaymentMethod` method also accepts `Iterable properties` as a parameter. * In addition, it also accepts `PaymentMethodPlugin paymentMethodProps` as a parameter. * `PaymentMethodPlugin` is a generic object that represents a payment method (creditcard, bank account, etc.). It has a `getProperties` method that returns a `List`. * The `properties` parameter is typically used to pass properties which are related to the specific method call (`addPaymentMethod` in this case) while the `PaymentMethodPlugin#getProperties` typically refers to non-standard generic information about the payment method itself. * A client application can use either of these to pass in the GoCardless properties. The code above (like other plugins) is lenient and accepts both ways. So, it first invokes `PluginProperties.merge` to merge both properties and stores them into a merged `allProperties` list * It then retrieves the `redirectFlowId` and `sessionToken` from `allProperties`. These are required by GoCardless and are as explained below: ** `redirectFlowId` - If you recall, the `redirectFlowId` is sent to a client application after the `buildFormDescriptor` method call. A client application needs to send this back. ** `sessionToken` - As explained earlier, a client application needs to send the same `sessionToken` that was sent at the time of *creating the redirect flow* (when the `buildFormDescriptor` method was invoked) to ensure that the person who *completes the redirect flow* is the person who initiated it. * Next, the `client.redirectFlows().complete` is invoked with the `redirectFlowId` and the `sessionToken`. This returns a `RedirectFlow` object which contains the *mandate Id*. * Finally, the *mandateId* is stored in the Kill Bill database. Normally, each plugin has its own plugin specific tables. However, since we are not creating a full-fledged GoCardless plugin, we are storing the *mandateId* in the *custom_fields* table. The *custom_fields* table can be used to store arbitrary key/value pairs in the Kill Bill database. * In case an error occurs in any of the steps, the code throws a https://github.com/killbill/killbill-plugin-api/blob/d9eca5af0e37541069b1c608f95e100dbe13b301/payment/src/main/java/org/killbill/billing/payment/plugin/api/PaymentPluginApiException.java[PaymentPluginApiException] ==== Step 6 - Implementing GoCardlessPaymentPluginApi#purchasePayment The `purchasePayment` is used to charge a customer against a payment method. So, once a user sets up a payment method as done above, the `purchasePayment` method can be used by a client application to trigger payments against a *mandateId*. So, this method can be implemented as follows (See https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessPaymentPluginApi.java#L94[_GoCardlessPaymentPluginApi#purchasePayment_]): [source,java,linenums] public PaymentTransactionInfoPlugin purchasePayment(UUID kbAccountId, UUID kbPaymentId, UUID kbTransactionId, UUID kbPaymentMethodId, BigDecimal amount, Currency currency, Iterable properties, CallContext context) throws PaymentPluginApiException { logger.info(""purchasePayment, kbAccountId="" + kbAccountId); PaymentTransactionInfoPlugin paymentTransactionInfoPlugin; String mandate = getMandateId(kbAccountId, context); // retrieve mandateId from Kill Bill tables logger.info(""MandateId=""+mandate); if (mandate != null) { logger.info(""Processing payment""); try { String idempotencyKey = PluginProperties.findPluginPropertyValue(""idempotencykey"", properties); com.gocardless.services.PaymentService.PaymentCreateRequest.Currency goCardlessCurrency = convertKillBillCurrencyToGoCardlessCurrency( currency); Payment payment = client.payments().create() .withAmount(Math.toIntExact(KillBillMoney.toMinorUnits(currency.toString(), amount))) .withCurrency(goCardlessCurrency).withLinksMandate(mandate).withIdempotencyKey(idempotencyKey) .withMetadata(""kbPaymentId"", kbPaymentId.toString()).withMetadata(""kbTransactionId"", kbTransactionId.toString()) //added for getPaymentInfo .execute(); List outputProperties = new ArrayList(); outputProperties.add(new PluginProperty(""paymentId"", payment.getId(), false)); paymentTransactionInfoPlugin = new GoCardlessPaymentTransactionInfoPlugin(kbPaymentId, kbTransactionId, TransactionType.PURCHASE, amount, currency, PaymentPluginStatus.PROCESSED, null, null, String.valueOf(payment.getId()), null, new DateTime(), new DateTime(payment.getCreatedAt()), outputProperties); logger.info(""Payment processed, PaymentId=""+payment.getId()); } catch (GoCardlessApiException e) { paymentTransactionInfoPlugin = new GoCardlessPaymentTransactionInfoPlugin(kbPaymentId, kbTransactionId, TransactionType.PURCHASE, amount, currency, PaymentPluginStatus.ERROR, e.getErrorMessage(), String.valueOf(e.getCode()), null, null, new DateTime(), null, null); logger.warn(""Error occured in purchasePayment"", e.getType(), e); } } else { logger.warn(""Unable to fetch mandate, so cannot process payment""); paymentTransactionInfoPlugin = new GoCardlessPaymentTransactionInfoPlugin(kbPaymentId, kbTransactionId, TransactionType.PURCHASE, amount, currency, PaymentPluginStatus.CANCELED, null, null, null, null, new DateTime(), null, null); } return paymentTransactionInfoPlugin; } * Like the other methods, the `purchasePayment` method accepts `Iterable properties` as a parameter. * In addition, it also accepts parameters corresponding to `amount` (specifies the amount to charge the customer) and `currency` (specifies the currency to be used) * If you recall, the `addPaymentMethod` stores the *mandate id* in the Kill Bill database. This is first retrieved and assigned to `mandate` * Next, the `idempotencyKey` is retrieved from the `properties` passed in. The `idempotencyKey` is a GoCardless specific value. As per the GoCardless documentation, their API will ensure this payment is only ever created once per `idempotencyKey`. So a client application could specify `kbPaymentId` as the `idempotencyKey` to ensure at most a single payment is created per `kbPaymentId`. * The `currency` object passed in is of type `org.killbill.billing.catalog.api.Currency`. This is then converted to a *GoCardless Currency object* (of type `com.gocardless.services.PaymentService.PaymentCreateRequest.Currency`). Most payment plugins have code similar to this to convert Kill Bill objects to compatible objects in the plugin's client library. * Finally, the `client.payments().create()` is invoked with the `idempotencyKey`,`amount` and `currency` values. This returns a `Payment` object which contains a `paymentId`. Additionally, the `kbPaymentId` and `kbTransactionId` are sent as *metadata* to GoCardless in this call. GoCardless *metadata* allows an application to send custom key value pairs to GoCardless. These can then be retrieved later on as required. In our case, the `kbPaymentId` and `kbTransactionId` are required for the `getPaymentInfo` call which will be explained further. * The `purchasePayment` method returns a `PaymentTransactionInfoPlugin` object. The <> section above explains this interface in detail. We have already created a https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessPaymentTransactionInfoPlugin.java[GoCardlessPaymentTransactionInfoPlugin] class above. * If the payment is successful, the `GoCardlessPaymentTransactionInfoPlugin` object is created with the following values: ** *kbPaymentId* - Set to `kbPaymentId`. It corresponds to the Kill Bill payment id. ** *kbTransactionId* - Set to `kbTransactionId`. It corresponds to the Kill Bill transaction id. ** *TransactionType* - Set to `TransactionType.PURCHASE` since this is a purchase transaction ** *amount* - Set to `amount`. It corresponds to the amount with which the customer is charged ** *currency* - Set to `currency`. It corresponds to the currency in which the customer is charged ** *PaymentPluginStatus* - Set to `PaymentPluginStatus.PROCESSED` since the payment is processed successfully ** *gatewayError* - Set to `null` since there is no error ** *gatewayErrorCode* - set to `null` since there is no error ** *firstPaymentReferenceId* - Set to the *payment Id* returned by GoCardless ** *secondPaymentReferenceId* - set to `null` since GoCardless does not have a secondPaymentReferenceId. Other payment plugins might use this parameter if required. ** *createdDate* - Set to the current date ** *effectiveDate* - Set to the date when the payment was created. This is retrieved from the `payment` object returned by GoCardless ** *properties* - Set to a `List` called `outputProperties` which contains the GoCardless *payment Id*. The client API can use the `properties` as desired. * If there is an exception while processing the payment, the `GoCardlessPaymentTransactionInfoPlugin` object is created with the following values : ** *PaymentPluginStatus* - Set to `PaymentPluginStatus.ERROR` since there is an error in the payment ** *gatewayError* - Set to the *error message* from the exception ** *gatewayErrorCode* - Set to the *error code* from the exception ** *firstPaymentReferenceId* - Set to `null` since the payment failed ** *effectiveDate* - Set to `null` since the payment failed ** *properties* - Set to `null` since the payment failed * If the code is unable to retrieve the `mandateId` from the Kill Bill database, the `GoCardlessPaymentTransactionInfoPlugin` object is created with the following values: ** *PaymentPluginStatus* - Set to `PaymentPluginStatus.CANCELED` since the gateway was not contacted as the plugin was unable to retrieve the `mandateId` ** *gatewayError* - Set to `null` since there is no error ** *gatewayErrorCode* - set to `null` since there is no error ** *firstPaymentReferenceId* - Set to `null` since the payment was not processed ** *effectiveDate* - Set to `null` since the payment was not processed ** *properties* - Set to `null` since the payment was not processed ==== Step 7 - Implementing GoCardlessPaymentPluginApi#getPaymentInfo As explained earlier, the Kill Bill Janitor system attempts to fix *PENDING* and *UNKNOWN* states by polling the plugin via `PaymentPluginApi#getPaymentInfo` method. So, this method can be implemented as follows (See https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessPaymentPluginApi.java#L211[_GoCardlessPaymentPluginApi#getPaymentInfo_]): [source,java,linenums] public List getPaymentInfo(UUID kbAccountId, UUID kbPaymentId, Iterable properties, TenantContext context) throws PaymentPluginApiException { logger.info(""getPaymentInfo""); List paymentTransactionInfoPluginList = new ArrayList<>(); String mandateId = getMandateId(kbAccountId, context) ; logger.info(""Mandate=""+mandateId); Mandate mandate = client.mandates().get(mandateId).execute(); //get GoCardless Mandate object String customerId = mandate.getLinks().getCustomer(); //retrieve customer id from mandate logger.info(""CustomerId=""+customerId); Iterable payments = client.payments().all().withCustomer(customerId).execute(); //get all payments related to customer for (Payment payment : payments) { String kbPaymentIdFromPayment = payment.getMetadata().get(""kbPaymentId""); //get kbPaymentId from metadata in payment logger.info(""kbPaymentIdFromPayment=""+kbPaymentIdFromPayment); if(kbPaymentIdFromPayment != null && kbPaymentId.toString().equals(kbPaymentIdFromPayment)) { logger.info(""Found matching payment""); Currency killBillCurrency = convertGoCardlessCurrencyToKillBillCurrency(payment.getCurrency()); logger.info(""payment_status=""+payment.getStatus()); PaymentPluginStatus status = convertGoCardlessToKillBillStatus(payment.getStatus()); String kbTransactionPaymentIdStr = payment.getMetadata().get(""kbTransactionId""); UUID kbTransactionPaymentId = kbTransactionPaymentIdStr !=null?UUID.fromString(kbTransactionPaymentIdStr):null; logger.info(""kbTransactionPaymentId=""+kbTransactionPaymentId); List outputProperties = new ArrayList(); outputProperties.add(new PluginProperty(""mandateId"",mandateId,false)); //arbitrary data to be returned to the caller outputProperties.add(new PluginProperty(""customerId"",customerId,false)); //arbitrary data to be returned to the caller GoCardlessPaymentTransactionInfoPlugin paymentTransactionInfoPlugin = new GoCardlessPaymentTransactionInfoPlugin( kbPaymentId, kbTransactionPaymentId, TransactionType.PURCHASE, new BigDecimal(payment.getAmount()), killBillCurrency, status, null, null, String.valueOf(payment.getId()), null, new DateTime(), new DateTime(payment.getCreatedAt()), outputProperties); paymentTransactionInfoPluginList.add(paymentTransactionInfoPlugin); } } return paymentTransactionInfoPluginList; } * If you recall, the `addPaymentMethod` stores the *mandate id* in the Kill Bill database in the *custom_fields* table. This is first retrieved and assigned to `mandateId`. * Next, the GoCardless Mandate object is retrieved via `client.mandates().get(mandateId)` as explained https://developer.gocardless.com/api-reference/#mandates-get-a-single-mandate[here]. * Next, the `customerId` associated with the mandate is retrieved and all the `payments` associated with the customer are retrieved via `client.payments().all().withCustomer(customerId)` as explained https://developer.gocardless.com/api-reference/#payments-list-payments[here]. * The code then iterates through the `payment` objects and obtains the `Payment` object corresponding to the `kbPaymentId` passed in. If you recall, the `purchasePayment` method sends `kbPaymentId` and `kbTransactionId` to GoCardless as metadata fields. Thus, the `kbPaymentId` is retrieved from the metadata of each `Payment` object and compared with the `kbPaymentId` passed in. * The code then creates a `GoCardlessPaymentTransactionInfoPlugin` corresponding to a matching `Payment`using the following: ** *killBillCurrency* - The *GoCardless currency* (`com.gocardless.resources.Payment.Currency`) is retrieved from the `payment` object and converted to *Kill Bill currency* (`org.killbill.billing.catalog.api.Currency`). ** *status* - The *GoCardless status* (`com.gocardless.resources.Payment.Status`) is retrieved from the `payment` object and converted to *Kill Bill status* (`org.killbill.billing.payment.plugin.api.PaymentPluginStatus`). ** *kbTransactionId* - This is retrieved from the payment metadata. This step is very important because, the Janitor uses the *transaction id* to match the internal transactions with the plugin transactions as explained earlier. ** *outputProperties* - This is a List of `PluginProperty` objects. Some `PluginProperty` objects are created and added to the `outputProperties` List. Any arbitrary key-value pairs which need to be returned to the caller can be specified here. * The List of `GoCardlessPaymentTransactionInfoPlugin` object is returned back. * The Janitor then updates the internal payment state as well as invoice balance, etc. based on the information in the `GoCardlessPaymentTransactionInfoPlugin` object. * In addition to the Janitor, the `getPaymentInfo` can also be used used on the merchant website (or in Kaui) to display the payment details to the customer. In such cases, it is invoked via an API call as specified https://killbill.github.io/slate/#payment-retrieve-a-payment-using-paymentid[here]. An important point to note is that the actual plugin method (`GoCardlessPluginApi#getPaymentInfo`) is invoked only when the `withPluginInfo=true` is specified in the API call. If `withPluginInfo=false` is specified, the plugin method is not invoked and Kill Bill just returns the payment information from the Kill Bill database. ==== Step 8 - Creating GoCardlessCheckoutServlet In the case of GoCardless, we need to create an additional servlet that invokes the `GoCardlessPluginApi#buildFormDescriptor` method. Normally, a client API invokes `buildFormDescriptor` via the https://github.com/killbill/killbill-api/blob/4ae1c343a593de937415e21feecb9f5405037fa3/src/main/java/org/killbill/billing/payment/api/PaymentGatewayApi.java[PaymentGatewayApi] interface. If you take a look at the https://github.com/killbill/killbill-api/blob/4ae1c343a593de937415e21feecb9f5405037fa3/src/main/java/org/killbill/billing/payment/api/PaymentGatewayApi.java#L43[PaymentGatewayApi#buildFormDescriptor] method, you will notice that it accepts a `UUID paymentMethodId` as a parameter. Thus, this method assumes that a *payment method* already exists. (You can read the https://docs.killbill.io/latest/userguide_payment.html#_payment_methods[payment user guide] to know more about payment methods). However, in the case of GoCardless, we are using `GoCardlessPluginApi#buildFormDescriptor` to create a form where a user sets up a mandate. Thus, the *payment method* will not exist in Kill Bill at the time of invoking the `PaymentGatewayApi#buildFormDescriptor` method. So, this method cannot directly invoke the `GoCardlessPlugin#buildFormDescriptor` method. To work around this, we need to create a servlet and invoke the `GoCardlessPlugin#buildFormDescriptor` method from this servlet. The client application can invoke this servlet and not the `PaymentGatewayApi#buildFormDescriptor` method This servlet can be created as follows (See https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessCheckoutServlet.java[_GoCardlessCheckoutServlet_]): [source,java,linenums] @Singleton // Handle /plugins/killbill-gocardless/checkout @Path(""/checkout"") public class GoCardlessCheckoutServlet { private final OSGIKillbillClock clock; private final GoCardlessPaymentPluginApi goCardlessPaymentPluginApi; private static final Logger logger = LoggerFactory.getLogger(GoCardlessCheckoutServlet.class); @Inject public GoCardlessCheckoutServlet(final OSGIKillbillClock clock, final GoCardlessPaymentPluginApi goCardlessPaymentPluginApi) { this.clock = clock; this.goCardlessPaymentPluginApi = goCardlessPaymentPluginApi; } // Setting up Direct Debit mandates using Hosted Payment Pages, before a payment method has been added to the account @POST public Result createSession(@Named(""kbAccountId"") final UUID kbAccountId, @Named(""success_redirect_url"") final Optional successUrl, @Named(""redirect_flow_description"") final Optional description, @Named(""lineItemName"") final Optional token, @Local @Named(""killbill_tenant"") final Tenant tenant) throws PaymentPluginApiException { logger.info(""Inside createSession""); final CallContext context = new PluginCallContext(GoCardlessActivator.PLUGIN_NAME, clock.getClock().getUTCNow(), kbAccountId, tenant.getId()); final ImmutableList properties = ImmutableList.of( new PluginProperty(""success_redirect_url"", successUrl.orElse(""https://developer.gocardless.com/example-redirect-uri/""), false), new PluginProperty(""redirect_flow_description"", description.orElse(""Kill Bill payment""), false), new PluginProperty(""session_token"", token.orElse(""killbill_token""), false)); final HostedPaymentPageFormDescriptor hostedPaymentPageFormDescriptor = goCardlessPaymentPluginApi.buildFormDescriptor(kbAccountId, ImmutableList.of(), properties, context); return Results.with(hostedPaymentPageFormDescriptor, Status.CREATED) .type(MediaType.json); } } * The servlet is mapped to the `/checkout` path. Thus, a client application needs to make a request to this path to invoke the servlet * The `createSession` accepts properties corresponding to `clock` and `goCardlessPaymentPluginApi`. These are injected via the `GoCardlessActivator` class as explained below * It then creates `PluginProperty` objects corresponding to the values passed in as parameters * Finally, it invokes the `GoCardlessPlugin#buildFormDescriptor` method ==== Step 9 - Creating GoCardlessActivator We also need to create a class similar to `HelloWorldActivator` that starts the plugin. We can create this class as follows (See https://github.com/killbill/killbill-gocardless-example-plugin/blob/9522498ecde5849c940574c598ceb5ce088d32a7/src/main/java/org/killbill/billing/plugin/gocardless/GoCardlessActivator.java[_GoCardlessActivator_]): [source,java,linenums] public class GoCardlessActivator extends KillbillActivatorBase{ //This is the plugin name and is used by Kill Bill to route payment to the appropriate payment plugin public static final String PLUGIN_NAME = ""killbill-gocardless""; @Override public void start(final BundleContext context) throws Exception { super.start(context); final GoCardlessPaymentPluginApi pluginApi = new GoCardlessPaymentPluginApi(killbillAPI,clock.getClock()); registerPaymentPluginApi(context, pluginApi); // Register the servlet, which is used as the entry point to generate the Hosted Payment Pages redirect url final PluginApp pluginApp = new PluginAppBuilder(PLUGIN_NAME, killbillAPI, dataSource, super.clock, configProperties) .withRouteClass(GoCardlessCheckoutServlet.class) .withService(pluginApi) .withService(clock) .build(); final HttpServlet goCardlessServlet = PluginApp.createServlet(pluginApp); registerServlet(context, goCardlessServlet); } private void registerPaymentPluginApi(final BundleContext context, final PaymentPluginApi api) { final Hashtable props = new Hashtable(); props.put(OSGIPluginProperties.PLUGIN_NAME_PROP, PLUGIN_NAME); registrar.registerService(context, PaymentPluginApi.class, api, props); } private void registerServlet(final BundleContext context, final HttpServlet servlet) { final Hashtable props = new Hashtable(); props.put(OSGIPluginProperties.PLUGIN_NAME_PROP, PLUGIN_NAME); registrar.registerService(context, Servlet.class, servlet, props); } } * The `GoCardlessActivator` class defines a static field called `PLUGIN_NAME` with the value `killbill-gocardless`. This is the name of the plugin and will be used by Kill Bill to route payment to the appropriate plugin as explained in our https://docs.killbill.io/latest/userguide_payment.html#_payment_methods_and_plugin_names[Payment User Guide] * The `start` method creates a new `GoCardlessPaymentPluginApi` object * It then invokes the `registerPaymentPluginApi` method which registers the plugin with the `PLUGIN_NAME`. This code is pretty standard across all plugins and can be used as it is * In the case of GoCardless, we need to create a checkout servlet as explained above. The `start` method creates this servlet via `PluginAppBuilder` as follows: ** `withRouteClass` specifies the name of the servlet, in this case `GoCardlessCheckoutServlet` ** `withService` specifies `pluginApi`. Since the `GoCardlessCheckoutServlet` accepts a parameter corresponding to `GoCardlessPaymentPluginApi`, this is injected via `withService` ** Similarly, since `GoCardlessPaymentPluginApi` accepts a parameter corresponding to `OSGIKillbillClock`, a `clock` object is injected via `withService` ** Any other values that need to be passed to the servlet can be injected similarly ** The `build` method is invoked which creates `pluginApp` ** Finally, the servlet is created via `PluginApp.createServlet` * The `registerServlet` method is then invoked which registers the servlet ==== Step 10 - Build and Deployment The GoCardless plugin can be built and deployed as per the build and deployment instructions specified in our https://docs.killbill.io/latest/plugin_development.html#_build[__Plugin Development Document__]. ==== Step 11 - Testing Once the plugin is deployed successfully, it can be tested using `curl` commands as specified https://github.com/killbill/killbill-gocardless-example-plugin/[_here_].",12340,True,2517.7327678569445,median "#include ""pause.h"" #include ""player.h"" #include ""options.h"" #include ""quest.h"" #include ""skill.h"" #include ""equip.h"" #include ""help.h"" #include ""glasses.h"" #include ""title.h"" #include ""alchemy.h"" #include ""madcap.h"" #include ""music.h"" #include ""achieve.h"" #include ""leveldef.h"" #include ""appdata.h"" char pauseOption[PAUSE_CHOICES][32]={ ""Resume"", ""Items"", ""Skills"", ""Talents"", ""Quests"", ""Message Log"", ""Madcap Items"", ""Tips"", ""Options"", ""Save & Quit"", }; byte cursor=0; static byte subcursor=0,skillPage=0,questPage=0,talentPage=0,yesno=0,asking,tipPage=0; static char lastKey=0; byte subMode; static byte darkness; static int offX; static byte oldc; static byte skillPtr[10]; static char helpTxt[4][64]; static char askingTxt[64]; static char statText[6][32],statNum[6]; static byte statClock[3]; void NewStatText(byte n) { int i,j; byte b; while(1) { b=rand()%25; j=0; for(i=0;i<6;i++) if(i!=n && statNum[i]==b) j=1; if(j!=1) break; } statNum[n]=b; switch(b) { case 0: sprintf(statText[n],""%d Loonies lost."",player.var[VAR_DEATHS]); break; case 1: sprintf(statText[n],""%d Bodzhas beaten."",player.var[VAR_KILLCOUNTS+KC_BODZHA]+player.var[VAR_KILLCOUNTS+KC_BODZHA+1]*256); break; case 2: sprintf(statText[n],""%d Ghosts busted."",player.var[VAR_KILLCOUNTS+KC_GHOST]+player.var[VAR_KILLCOUNTS+KC_GHOST+1]*256); break; case 3: sprintf(statText[n],""%d Ice beasts iced."",player.var[VAR_KILLCOUNTS+KC_ICE]+player.var[VAR_KILLCOUNTS+KC_ICE+1]*256); break; case 4: sprintf(statText[n],""%d Bears bonked."",player.var[VAR_KILLCOUNTS+KC_BEAR]+player.var[VAR_KILLCOUNTS+KC_BEAR+1]*256); break; case 5: sprintf(statText[n],""%d Mice mashed."",player.var[VAR_KILLCOUNTS+KC_MICE]+player.var[VAR_KILLCOUNTS+KC_MICE+1]*256); break; case 6: sprintf(statText[n],""%d Puppets popped."",player.var[VAR_KILLCOUNTS+KC_PUPPET]+player.var[VAR_KILLCOUNTS+KC_PUPPET+1]*256); break; case 7: sprintf(statText[n],""%d Monkeys socked."",player.var[VAR_KILLCOUNTS+KC_MONKEY]+player.var[VAR_KILLCOUNTS+KC_MONKEY+1]*256); break; case 8: sprintf(statText[n],""%d Stone beasts stomped."",player.var[VAR_KILLCOUNTS+KC_STONE]+player.var[VAR_KILLCOUNTS+KC_STONE+1]*256); break; case 9: sprintf(statText[n],""%d Shrooms shattered."",player.var[VAR_KILLCOUNTS+KC_SHROOM]+player.var[VAR_KILLCOUNTS+KC_SHROOM+1]*256); break; case 10: sprintf(statText[n],""%d Soldiers sorted."",player.var[VAR_KILLCOUNTS+KC_SOLDIER]+player.var[VAR_KILLCOUNTS+KC_SOLDIER+1]*256); break; case 11: sprintf(statText[n],""%d Plants placated."",player.var[VAR_KILLCOUNTS+KC_PLANT]+player.var[VAR_KILLCOUNTS+KC_PLANT+1]*256); break; case 12: sprintf(statText[n],""%d Gangsters ganked."",player.var[VAR_KILLCOUNTS+KC_ONION]+player.var[VAR_KILLCOUNTS+KC_ONION+1]*256); break; case 13: sprintf(statText[n],""%d Knights knifed."",player.var[VAR_KILLCOUNTS+KC_BUNNY]+player.var[VAR_KILLCOUNTS+KC_BUNNY+1]*256); break; case 14: j=0; for(i=0;i<50;i++) if(player.var[VAR_CHEST+i]) j++; sprintf(statText[n],""%d Chests churned."",j); break; case 15: sprintf(statText[n],""%d Arena victories."",player.var[VAR_ARENAWINS]); break; case 16: sprintf(statText[n],""%d Axes thrown/swung."",player.shotsFired); break; case 17: sprintf(statText[n],""%d Spells cast."",player.specialShotsFired); break; case 18: sprintf(statText[n],""%d Damage taken."",player.hitsTaken); break; case 19: sprintf(statText[n],""%d Damage dealt."",player.damageDone); break; case 20: sprintf(statText[n],""$%d collected."",player.gemsGotten); break; case 21: sprintf(statText[n],""%d Herbs collected."",player.herbsPicked); break; case 22: sprintf(statText[n],""%d Holes dug."",player.holesDug); break; case 23: sprintf(statText[n],""%d Monsters slain."",player.kills); break; case 24: sprintf(statText[n],""%d Potions poured."",player.potionsDrunk); break; } } void SwapStatText(byte b) { strcpy(statText[b],statText[b+1]); statNum[b]=statNum[b+1]; NewStatText(b+1); } void BuildStatText(void) { int i; for(i=0;i<6;i++) statNum[i]=(byte)255; NewStatText(1); SwapStatText(0); NewStatText(3); SwapStatText(2); NewStatText(5); SwapStatText(4); } void SetHelpText(void) { if(subMode==0) { strcpy(helpTxt[0],""Up & Down to choose options. Press Fire to select,""); strcpy(helpTxt[1],""Jump or ESC to resume play.""); strcpy(helpTxt[2],""""); strcpy(helpTxt[3],""""); } if(subMode==SUBMODE_SKILL) { strcpy(helpTxt[0],""Up & Down to choose skills. Press Fire to add a point""); strcpy(helpTxt[1],""to a skill if you have any. Left & Right will take you""); strcpy(helpTxt[2],""to more pages of skills. Jump or ESC exits.""); strcpy(helpTxt[3],""WARNING: Skill points are permanent once placed!""); } if(subMode==SUBMODE_TALENT) { strcpy(helpTxt[0],""Up & Down to choose talents. Left and Right flip to""); strcpy(helpTxt[1],""to different pages. Jump or ESC exits.""); strcpy(helpTxt[2],""The meter indicates how close the current talent is""); strcpy(helpTxt[3],""to gaining a level.""); } if(subMode==SUBMODE_EQUIP) { strcpy(helpTxt[0],""Browse with arrow keys. Press Fire to equip the selected""); strcpy(helpTxt[1],""item. Press Magic to PERMANENTLY discard the selected""); strcpy(helpTxt[2],""item. Press Jump or ESC to exit this menu.""); strcpy(helpTxt[3],""""); } if(subMode==SUBMODE_EQUIPYESNO) { strcpy(helpTxt[0],""Left and Right to choose. Fire to accept, Jump to""); strcpy(helpTxt[1],""cancel.""); strcpy(helpTxt[2],""""); strcpy(helpTxt[3],""""); } if(subMode==SUBMODE_QUEST) { strcpy(helpTxt[0],""Up & Down to flip through your quests. Left & Right""); strcpy(helpTxt[1],""change pages. Handy info on the quest is displayed""); strcpy(helpTxt[2],""at the bottom. Press Fire or Jump to exit.""); strcpy(helpTxt[3],""""); } if(subMode==SUBMODE_MADCAP) { strcpy(helpTxt[0],""Up & Down to choose Crystals. Fire to buy a Crystal,""); strcpy(helpTxt[1],""Jump to exit.""); strcpy(helpTxt[2],""""); strcpy(helpTxt[3],""""); } if(subMode==SUBMODE_TIPS) { strcpy(helpTxt[0],""Up & Down to flip through tips. Left & Right change""); strcpy(helpTxt[1],""pages. Press Fire or Jump to exit.""); strcpy(helpTxt[2],""""); strcpy(helpTxt[3],""""); } if(subMode==SUBMODE_OPTIONS) { strcpy(helpTxt[0],""Up, Down, Left and Right to select. Fire to adjust""); strcpy(helpTxt[1],""an option. Jump to exit. Changes made here affect""); strcpy(helpTxt[2],""only this profile. To change newly-made profiles and""); strcpy(helpTxt[3],""the title screen, use the title options menu.""); } } void SetSubCursor(byte s) { subcursor=s; } void PauseBox(int x,int y,int x2,int y2,byte c) { byte c2; c2=(31-(c&31))/2+(c&31); c2+=(c&(~31)); // grey outline DrawFillBox(x+2,y,x2-2,y,26); DrawFillBox(x+2,y2,x2-2,y2,26); DrawFillBox(x,y+2,x,y2-2,26); DrawFillBox(x2,y+2,x2,y2-2,26); // grey outline dots DrawFillBox(x+1,y+1,x+1,y+1,26); DrawFillBox(x2-1,y+1,x2-1,y+1,26); DrawFillBox(x+1,y2-1,x+1,y2-1,26); DrawFillBox(x2-1,y2-1,x2-1,y2-1,26); // white outline DrawFillBox(x+1,y+2,x+1,y2-2,31); DrawFillBox(x2-1,y+2,x2-1,y2-2,31); DrawFillBox(x+2,y+1,x2-2,y+1,31); DrawFillBox(x+2,y2-1,x2-2,y2-1,31); // white outline dots DrawFillBox(x+2,y+2,x+2,y+2,31); DrawFillBox(x2-2,y+2,x2-2,y+2,31); DrawFillBox(x+2,y2-2,x+2,y2-2,31); DrawFillBox(x2-2,y2-2,x2-2,y2-2,31); // bright outline DrawFillBox(x+2,y+3,x+2,y2-3,c2); DrawFillBox(x2-2,y+3,x2-2,y2-3,c2); DrawFillBox(x+3,y+2,x2-3,y+2,c2); DrawFillBox(x+3,y2-2,x2-3,y2-2,c2); // and finally dark/normal interior DrawFillBox(x+3,y+3,x2-3,y2-3,c); } void RenderMadcapMenu(int x,int y) { int i; byte c; char s[8]; PauseBox(x+202,y+5,x+638,y+377,234); PauseBox(x+202,y+379,x+638,y+428,234); PrintMadcapInfo(x,y,subcursor); PrintGlow(x+251,y+8,""Madcap Crystals"",0,0); x+=206; y+=34; for(i=0;i<11;i++) { if(subcursor!=i || subMode!=SUBMODE_MADCAP) PauseBox(x,y,x+105,y+28,240); else if(subMode==SUBMODE_MADCAP) PauseBox(x,y,x+105,y+28,32*5+16); PrintDark(x+12,y+2,MadcapName(i),0); c=234+(21*player.var[VAR_MADGEM+i]/100); PauseBox(x+108,y+1,x+108+(310*player.var[VAR_MADGEM+i]/100)+10,y+27,c); sprintf(s,""%d"",player.var[VAR_MADGEM+i]); CenterPrint(x+108+320/2-1,y+3-1,s,-32,0); CenterPrint(x+108+320/2+1,y+3-1,s,-32,0); CenterPrint(x+108+320/2+1,y+3+1,s,-32,0); CenterPrint(x+108+320/2-1,y+3+1,s,-32,0); CenterPrintColor(x+108+320/2,y+3,s,0,0,0); y+=31; } } void OptionButton(int x,int y,int wid,const char *txt,byte spot) { if(subcursor!=spot || subMode!=SUBMODE_OPTIONS) PauseBox(x,y,x+wid,y+28,240); else if(subMode==SUBMODE_OPTIONS) PauseBox(x,y,x+wid,y+28,32*5+16); CenterPrintDark(x+wid/2,y+2,txt,0); } void RenderOptionsMenu(int x,int y) { int i,j; char s[64]; PauseBox(x+202,y+5,x+638,y+377,234); PauseBox(x+202,y+379,x+638,y+428,234); PrintGlow(x+251,y+8,""Game Options"",0,0); x+=206; y+=34; // player stats sprintf(s,""Profile: %s"",player.profile); Print(x+2,y+350,s,0,1); sprintf(s,""Hours Played: %d:%02d"",player.playClock/(30*60*60),(player.playClock/(30*60))%60); RightPrint(x+428,y+350,s,0,1); i=0; strcpy(s,""Modifiers: ""); if(player.var[VAR_MODIFIER+0]) { i++; strcat(s,ModifierName(player.var[VAR_MODIFIER+0])); } if(player.var[VAR_MODIFIER+1]) { if(i>0) strcat(s,"", ""); i++; strcat(s,ModifierName(player.var[VAR_MODIFIER+1])); } if(player.var[VAR_MODIFIER+2]) { if(i>0) strcat(s,"", ""); i++; strcat(s,ModifierName(player.var[VAR_MODIFIER+2])); } if(player.var[VAR_MADCAP]) { if(i>0) strcat(s,"", ""); i++; strcat(s,""MADCAP!""); } if(i==0) strcat(s,""None""); Print(x+2,y+364,s,0,1); for(j=0;j<3;j++) { if(statClock[j]<30*2) i=0; else if(statClock[j]<30*3) i=-(statClock[j]-30*2); if(j==0) PrintGlow(x+2,y+378,statText[j*2+0],i,1); else if(j==1) RightPrintGlow(x+428,y+378,statText[j*2+0],i,1); if(statClock[j]>=30*2) { i=-(30*3-statClock[j]); if(j==0) PrintGlow(x+2,y+378,statText[j*2+1],i,1); else if(j==1) RightPrintGlow(x+428,y+378,statText[j*2+1],i,1); } } OptionButton(x,y,180,""Sound"",0); PauseBox(x+185,y+4,x+185+133,y+24,234); DrawFillBox(x+188,y+8,x+188+player.var[VAR_SOUND],y+20,31); y+=31; OptionButton(x,y,180,""Music"",1); PauseBox(x+185,y+4,x+185+133,y+24,234); DrawFillBox(x+188,y+8,x+188+player.var[VAR_MUSIC],y+20,31); y+=31; #ifdef DIRECTORS if(opt.modifier[29]) { OptionButton(x,y,180,""Commentary"",2); if(player.var[VAR_COMMENTARY]) PrintGlow(x+190,y+4,""On"",0,0); else PrintGlow(x+190,y+4,""Off"",0,0); } #else CenterPrintDark(x+78+1*116+112/2,y+2,""Controls"",0); #endif y+=31; CenterPrintDark(x+78+0*116+112/2,y+2,""Key 1"",0); CenterPrintDark(x+78+1*116+112/2,y+2,""Key 2"",0); CenterPrintDark(x+78+2*116+112/2,y+2,""Gamepad"",0); y+=31; PrintDark(x+2,y+0*31+2,""Up"",0); PrintDark(x+2,y+1*31+2,""Down"",0); PrintDark(x+2,y+2*31+2,""Left"",0); PrintDark(x+2,y+3*31+2,""Right"",0); PrintDark(x+2,y+4*31+2,""Fire"",0); PrintDark(x+2,y+5*31+2,""Jump"",0); PrintDark(x+2,y+6*31+2,""Spell"",0); CenterPrintDark(x+78+2*116+112/2,y+0*31+2,""Up"",0); CenterPrintDark(x+78+2*116+112/2,y+1*31+2,""Down"",0); CenterPrintDark(x+78+2*116+112/2,y+2*31+2,""Left"",0); CenterPrintDark(x+78+2*116+112/2,y+3*31+2,""Right"",0); for(i=0;i<3;i++) for(j=0;j<7;j++) { if(i<2) OptionButton(x+78+i*116,y+j*31,112,ScanCodeText(player.var[VAR_CONTROLS+i*8+j]),3+i+j*3); else if(j>3) { sprintf(s,""Btn %d"",player.var[VAR_CONTROLS+16+j-4]); OptionButton(x+78+i*116,y+j*31,112,s,3+i+j*3); } } } void RenderSetKey(int x,int y,byte t) { char actName[7][16]={ ""Up"", ""Down"", ""Left"", ""Right"", ""Fire"", ""Jump"", ""Spell"", }; PauseBox(x+130,y+80,x+630,y+240,234); if(t==0) CenterPrintGlow(x+380,y+100,""Press a key to assign to"",0,0); if(t==1) CenterPrintGlow(x+380,y+100,""Press a gamepad button to assign to"",0,0); CenterPrintGlow(x+380,y+150,actName[((subcursor-3)/3)],0,0); CenterPrintGlow(x+380,y+204,""Or ESC to cancel"",0,0); } void RenderSkillMenu(int x,int y) { int i,j; byte c,bigLvl; PauseBox(x+202,y+5,x+638,y+345,234); PauseBox(x+202,y+347,x+638,y+428,234); if(skillPtr[subcursor]!=255 && player.skillHave[skillPtr[subcursor]]) { Print(x+208,y+352,GetSkill(player.skillHave[skillPtr[subcursor]])->desc[0],0,1); Print(x+208,y+352+12,GetSkill(player.skillHave[skillPtr[subcursor]])->desc[1],0,1); Print(x+208,y+352+24,GetSkill(player.skillHave[skillPtr[subcursor]])->desc[2],0,1); Print(x+208,y+352+36,GetSkill(player.skillHave[skillPtr[subcursor]])->desc[3],0,1); Print(x+208,y+352+48,GetSkill(player.skillHave[skillPtr[subcursor]])->desc[4],0,1); if(player.skillHave[skillPtr[subcursor]]>=SKILL_SHROOM && player.skillHave[skillPtr[subcursor]]<=SKILL_LIFEBERRY) PrintColor(x+208,y+352+60,""This is a Nature Spell."",1,-8,1); else if(player.skillHave[skillPtr[subcursor]]>=SKILL_BURNINATE && player.skillHave[skillPtr[subcursor]]<=SKILL_HEATSHIELD) PrintColor(x+208,y+352+60,""This is a Fire Spell."",4,-8,1); else if(player.skillHave[skillPtr[subcursor]]>=SKILL_SHOCK && player.skillHave[skillPtr[subcursor]]<=SKILL_TORNADO) PrintColor(x+208,y+352+60,""This is a Wind Spell."",7,-8,1); else if(player.skillHave[skillPtr[subcursor]]>=SKILL_RESTORE && player.skillHave[skillPtr[subcursor]]<=SKILL_ICECUBE) PrintColor(x+208,y+352+60,""This is an Ice Spell."",3,0,1); else if(player.skillHave[skillPtr[subcursor]]>=SKILL_DRAIN && player.skillHave[skillPtr[subcursor]]<=SKILL_PLAGUE) PrintColor(x+208,y+352+60,""This is a Death Spell."",6,-8,1); } // list skills switch(skillPage) { case 0: PrintGlow(x+251,y+8,""Passive Skills 1/5"",0,0); break; case 10: PrintGlow(x+251,y+8,""Attack Skills 2/5"",0,0); break; case 20: PrintGlow(x+251,y+8,""Throwing Skills 3/5"",0,0); break; case 30: PrintGlow(x+251,y+8,""Magic Skills 4/5"",0,0); break; case 40: PrintGlow(x+251,y+8,""More Magic Skills 5/5"",0,0); break; } x+=206; y+=34; for(i=0;i<10;i++) { if(skillPtr[i]!=255) { if(subcursor!=i || subMode!=SUBMODE_SKILL) PauseBox(x,y,x+305,y+28,240); else if(subMode==SUBMODE_SKILL) PauseBox(x,y,x+305,y+28,32*5+16); PrintDark(x+12,y+2,GetSkill(player.skillHave[skillPtr[i]])->name,0); bigLvl=player.skillLvl[skillPtr[i]]+EquipSkillBoost(player.skillHave[skillPtr[i]]); if(player.potionType==POT_SPARKLING) bigLvl+=PotionEffect(player.potionType,player.potionPower); if(bigLvl>18) bigLvl=18; for(j=0;j<10;j++) { if(j10) { char s[8]; sprintf(s,""%d"",bigLvl); CenterPrint(x+308+5*12-1,y+3-1,s,-32,0); CenterPrint(x+308+5*12+1,y+3-1,s,-32,0); CenterPrint(x+308+5*12+1,y+3+1,s,-32,0); CenterPrint(x+308+5*12-1,y+3+1,s,-32,0); CenterPrintColor(x+308+5*12,y+3,s,5,-8,0); } } else // don't have a skill in this slot { if(subcursor!=i || subMode!=SUBMODE_SKILL) PauseBox(x+2,y+2,x+305-2,y+28-2,230); else PauseBox(x+2,y+2,x+305-2,y+28-2,32*5+6); PrintDark(x+12,y+2,""- - - - - -"",0); } y+=31; } } void RenderTalentMenu(int x,int y) { int i,j; byte c,bigLvl; PauseBox(x+202,y+5,x+638,y+345,234); PauseBox(x+202,y+347,x+638,y+428,234); if(player.talentLevel[subcursor+talentPage]!=255) { Print(x+208,y+352 ,GetTalent(subcursor+talentPage)->desc[0],0,1); Print(x+208,y+352+12,GetTalent(subcursor+talentPage)->desc[1],0,1); Print(x+208,y+352+24,GetTalent(subcursor+talentPage)->desc[2],0,1); Print(x+208,y+352+36,GetTalent(subcursor+talentPage)->desc[3],0,1); PauseBox(x+208,y+352+58,x+628,y+352+58+12,234); DrawFillBox(x+212,y+352+58+4,x+212+(player.talentPts[subcursor+talentPage]*(628-212-4)/TalentPointsNeeded(subcursor+talentPage)), y+352+58+12-4,31); } // list talents switch(talentPage) { case 0: PrintGlow(x+251,y+8,""Combat Talents 1/3"",0,0); break; case 10: PrintGlow(x+251,y+8,""Magic Talents 2/3"",0,0); break; case 20: PrintGlow(x+251,y+8,""Craft Talents 3/3"",0,0); break; } x+=206; y+=34; for(i=0;i<10;i++) { if(player.talentLevel[i+talentPage]!=255) { if(subcursor!=i || subMode!=SUBMODE_TALENT) PauseBox(x,y,x+305,y+28,240); else if(subMode==SUBMODE_TALENT) PauseBox(x,y,x+305,y+28,32*5+16); PrintDark(x+12,y+2,TalentName(i+talentPage),0); for(j=0;j<10;j++) { bigLvl=player.talentLevel[i+talentPage]; if(GlassEffect()==GE_TALENT) { if(GlassAmount()==3) bigLvl++; else if(GlassAmount()==0 && (i+talentPage)>=TLT_CHOPPING && (i+talentPage)<=TLT_GLADIATOR) bigLvl++; else if(GlassAmount()==1 && (i+talentPage)>=TLT_FOCUS && (i+talentPage)<=TLT_WINDBAG) bigLvl++; else if(GlassAmount()==2 && (i+talentPage)>=TLT_MOBILITY && (i+talentPage)<=TLT_HERBALISM) bigLvl++; } if(j1) { char s[4]; sprintf(s,""%d"",count); RightPrintDark(x+39,y+25,s,1); RightPrintDark(x+37,y+23,s,1); RightPrint(x+38,y+24,s,0,1); } } } void RenderUnusableInvItem(int x,int y,byte type,byte count,byte on) { PauseBox(x,y,x+39,y+39,225*(on==0)+166*(on==1)); if(type!=IT_NONE) { InstaRenderItem2(x+20,y+20,type,0,-20+(on==1)*4,GetDisplayMGL()); if(count>1) { char s[4]; sprintf(s,""%d"",count); RightPrintDark(x+39,y+25,s,1); RightPrintDark(x+37,y+23,s,1); RightPrint(x+38,y+24,s,0,1); } } } void RenderEquipMenu(int x,int y) { int i,j; PauseBox(x+202,y+5,x+638,y+345,234); PauseBox(x+202,y+347,x+638,y+428,234); if(subMode==SUBMODE_EQUIP) { switch(subcursor) { case 252: DescribeItem(x,y,&player.axe); break; case 253: DescribeItem(x,y,&player.amulet); break; case 254: DescribeItem(x,y,&player.parka); break; case 255: // glasses DescribeGlasses(x,y); break; default: if(player.items[subcursor].type!=IT_NONE) DescribeItem(x,y,&player.items[subcursor]); break; } } PrintGlow(x+251,y+8,""Items"",0,0); PrintGlow(x+251+139,y+43,""<- Equipped"",0,0); x+=206; y+=36; ConvertEquipmentForShow(1); RenderInvItem(x,y,player.axe.type,player.axe.count,(subcursor==252)); RenderInvItem(x+43,y,player.amulet.type,player.amulet.count,(subcursor==253)); RenderInvItem(x+43*2,y,player.parka.type,player.parka.count,(subcursor==254)); RenderInvItem(x+43*3,y,IT_LAMEGLASSES+(player.var[VAR_GLASSES]),1,(subcursor==255)); for(i=0;i<10;i++) for(j=0;j<6;j++) { RenderInvItem(x+i*43,y+48+j*43,player.items[i+j*10].type,player.items[i+j*10].count,(subcursor==i+j*10)); } ConvertEquipmentForShow(0); } void RenderYesNo(int x,int y) { PauseBox(x+130,y+80,x+630,y+240,234); CenterPrintGlow(x+380,y+100,askingTxt,0,0); if(yesno==0) PauseBox(x+240,y+200,x+370,y+235,32*5+16); else PauseBox(x+240,y+200,x+370,y+235,240); CenterPrintDark(x+305,y+204,""Yes"",0); if(yesno==1) PauseBox(x+390,y+200,x+520,y+235,32*5+16); else PauseBox(x+390,y+200,x+520,y+235,240); CenterPrintDark(x+455,y+204,""No"",0); } void PlayerStat(const char *txt,int val,int y) { char s[32]; int x1,x2,wid,i; sprintf(s,""%d"",val); x1=((8+GetStrLength(txt,1)+4)/6)*6; x2=((196-GetStrLength(s,1))/6)*6; wid=6; PrintGlow(8,y,txt,0,1); RightPrintGlow(196,y,s,0,1); for(i=x1;ipoison) d+=5; d=(word)(((float)d*(100.0f+TalentBonus(TLT_STONESKIN))/100.0f)+0.5f); PlayerStat(""Defense"",d,52+6); PlayerStat(""Axe Speed"",player.axeSpeed,64+6); PlayerStat(""Attack Cost"",StaminaCost(),76+6); PlayerSlashStat(""Life"",player.hearts,player.maxHearts,88+6*2); PlayerSlashStat(""Stamina"",player.stamina,player.maxStamina,100+6*2); PlayerSlashStat(""Magic"",player.magic,player.maxMagic,112+6*2); PlayerStat(""Money"",player.money,124+6*3); if(player.var[VAR_MADCAP]) PlayerStat(""Crystal Pts"",player.var[VAR_CPOINTS],136+6*3); } void RenderPauseMenu(MGLDraw *mgl) { int i; DarkenScreen(darkness); RenderPlayerStats(mgl); PauseBox(0,175,200,478,234); for(i=0;iLastKeyPressed(); if(k) lastKey=k; } void LoadGame(void) { FILE *f; char txt[64]; sprintf(txt,""profiles/char%02d.loony"",gameToLoad+1); f=AppdataOpen(txt,""rb""); if(!f) { InitPlayer(INIT_GAME,0,0); } else { fread(&player,sizeof(player_t),1,f); if(player.addonName[0]=='\\0') { ResetLevelDefs(); LoadWorld(&curWorld,""winter.llw""); } else { sprintf(txt,""addons/%s.llw"",player.addonName); LoadLevelDefs(player.addonName); LoadWorld(&curWorld,txt); } LoadGuys(f); LoadBullets(f); if(!curMap) curMap=new Map(20,20,""hi""); curMap->LoadFromProgress(f); fclose(f); ResetInterface(); PlayerCalcStats(); if(player.invinc<30) player.invinc=30; // and make you invincible briefly } } void SaveGame(void) { FILE *f; char txt[64]; sprintf(txt,""profiles/char%02d.loony"",gameToLoad+1); f=AppdataOpen(txt,""wb""); if(!f) { return; } else { player.destx=goodguy->mapx; player.desty=goodguy->mapy; fwrite(&player,sizeof(player_t),1,f); player.destx=0; player.desty=0; SaveGuys(f); SaveBullets(f); curMap->SaveProgress(f); fclose(f); AppdataSync(); } } void SetupSkillPage(void) { int i; byte p; for(i=0;i<10;i++) { skillPtr[i]=255; // empty all slots for(p=0;p0) { offX-=32; if(offX<0) offX=0; } for(i=0;i<3;i++) { statClock[i]++; if(statClock[i]==30*3) { SwapStatText(i*2); statClock[i]=0; } } c=GetControls()|GetArrows(); reptCounter++; if((!oldc) || (reptCounter>10)) reptCounter=0; if(subMode==SUBMODE_NONE) // not in any submenu { if((c&CONTROL_UP) && (!reptCounter)) { cursor--; subcursor=0; if(cursor==255) cursor=PAUSE_CHOICES-1; if(cursor==PAUSE_MADCAP && player.var[VAR_MADCAP]==0) cursor--; offX=400; SetHelpText(); } if((c&CONTROL_DN) && (!reptCounter)) { cursor++; subcursor=0; if(cursor==PAUSE_CHOICES) cursor=0; if(cursor==PAUSE_MADCAP && player.var[VAR_MADCAP]==0) cursor++; offX=400; SetHelpText(); } if(((c&CONTROL_B1) && (!(oldc&CONTROL_B1)))) { switch(cursor) { case PAUSE_RESUME: // cancel return PAUSE_RESUME; break; case PAUSE_SKILLS: subMode=SUBMODE_SKILL; subcursor=0; SetHelpText(); break; case PAUSE_TALENTS: subMode=SUBMODE_TALENT; subcursor=0; SetHelpText(); break; case PAUSE_ITEMS: subMode=SUBMODE_EQUIP; subcursor=0; SetHelpText(); break; case PAUSE_QUESTS: subMode=SUBMODE_QUEST; subcursor=0; SetHelpText(); break; case PAUSE_TIPS: subMode=SUBMODE_TIPS; subcursor=0; SetHelpText(); break; case PAUSE_MADCAP: if(player.var[VAR_MADCAP]) { subMode=SUBMODE_MADCAP; subcursor=0; SetHelpText(); } break; case PAUSE_OPTIONS: subMode=SUBMODE_OPTIONS; subcursor=0; SetHelpText(); break; case PAUSE_QUIT: // quit game SaveGame(); return PAUSE_QUIT; } } if(((c&CONTROL_B2) && (!(oldc&CONTROL_B2)))) { return PAUSE_RESUME; } } else if(subMode==SUBMODE_SKILL) { if((c&CONTROL_UP) && (!reptCounter)) { subcursor--; if(subcursor==255) subcursor=9; } if((c&CONTROL_DN) && (!reptCounter)) { subcursor++; if(subcursor==10) subcursor=0; } if((c&CONTROL_LF) && (!reptCounter)) { skillPage-=10; if(skillPage>PLAYER_SKILLS) skillPage=PLAYER_SKILLS-10; SetupSkillPage(); } if((c&CONTROL_RT) && (!reptCounter)) { skillPage+=10; if(skillPage>=PLAYER_SKILLS) skillPage=0; SetupSkillPage(); } if((c&CONTROL_B1) && (!(oldc&CONTROL_B1))) { // add a point to a skill if(skillPtr[subcursor]!=255 && player.skillHave[skillPtr[subcursor]] && player.skillPts>0 && player.skillLvl[skillPtr[subcursor]]<10) { player.skillClock[skillPtr[subcursor]]=0; player.skillLvl[skillPtr[subcursor]]++; player.skillPts--; if(skillPtr[subcursor]==SKILL_THROWING) TipEvent(TIP_THROWING); if(skillPtr[subcursor]>=SKILL_SHROOM && skillPtr[subcursor]<=SKILL_BONEBOMB) TipEvent(TIP_SPELL); MakeNormalSound(SND_MENUSELECT); PlayerCalcStats(); } else MakeNormalSound(SND_MENUCANCEL); } if((c&CONTROL_B2) && (!(oldc&CONTROL_B2))) { // exit the skill menu subMode=SUBMODE_NONE; SetHelpText(); } } else if(subMode==SUBMODE_OPTIONS) { if((c&CONTROL_UP) && (!reptCounter)) { subcursor--; #ifdef DIRECTORS if(opt.modifier[29]==0 && subcursor==2) subcursor--; #else if(subcursor==2) subcursor--; #endif if(subcursor>2) subcursor-=2; if(subcursor==5 || subcursor==8 || subcursor==11 || subcursor==14) // invalid spots subcursor--; if(subcursor>23) subcursor=21; } if((c&CONTROL_DN) && (!reptCounter)) { subcursor++; #ifdef DIRECTORS if(opt.modifier[29]==0 && subcursor==2) subcursor++; #else if(subcursor==2) subcursor++; #endif if(subcursor>3) subcursor+=2; if(subcursor>23) subcursor=0; } if((c&CONTROL_LF) && (!reptCounter)) { if(subcursor>2 && subcursor<15) // in the arrow key area { if(subcursor%3) subcursor--; else subcursor++; } else if(subcursor>14) { if(!(subcursor%3)) subcursor+=2; else subcursor--; } } if((c&CONTROL_RT) && (!reptCounter)) { if(subcursor>2 && subcursor<15) // in the arrow key area { if(subcursor%3) subcursor--; else subcursor++; } else if(subcursor>14) { if((subcursor%3)==2) subcursor-=2; else subcursor++; } } if((c&CONTROL_B1) && (!(oldc&CONTROL_B1))) { switch(subcursor) { case 0: // sound if(player.var[VAR_SOUND]>=127) player.var[VAR_SOUND]=0; else { player.var[VAR_SOUND]+=26; if(player.var[VAR_SOUND]>127) player.var[VAR_SOUND]=127; } JamulSoundVolume(player.var[VAR_SOUND]*2); MakeNormalSound(SND_MENUSELECT); break; case 1: // music if(player.var[VAR_MUSIC]>=127) player.var[VAR_MUSIC]=0; else { player.var[VAR_MUSIC]+=26; if(player.var[VAR_MUSIC]>127) player.var[VAR_MUSIC]=127; } SetMusicVolume(player.var[VAR_MUSIC]*2); MakeNormalSound(SND_MENUSELECT); break; case 2: // commentary #ifdef DIRECTORS if(opt.modifier[29]) { player.var[VAR_COMMENTARY]=1-player.var[VAR_COMMENTARY]; MakeNormalSound(SND_MENUSELECT); StopSong(); Song(levelDef[player.levelNum].song); } #endif break; default: // key setting if((subcursor%3)==2) // joystick { subMode=SUBMODE_SETBTN; mgl->ClearKeys(); i=0; while(i<10000 && GetJoyButtons()) { i++; SDL_Delay(1); } MakeNormalSound(SND_MENUSELECT); } else { subMode=SUBMODE_SETKEY; mgl->ClearKeys(); mgl->LastKeyPressed(); LastScanCode(); lastKey=0; MakeNormalSound(SND_MENUSELECT); } break; } } if((c&CONTROL_B2) && (!(oldc&CONTROL_B2))) { // exit the options menu subMode=SUBMODE_NONE; SetHelpText(); } } else if(subMode==SUBMODE_SETKEY) { byte r; r=LastScanCode(); if(r==59) { subMode=SUBMODE_OPTIONS; // escape MakeNormalSound(SND_MENUCANCEL); mgl->LastKeyPressed(); } else if(r!=0) { for(i=0;i<7;i++) for(j=0;j<2;j++) if(player.var[VAR_CONTROLS+j*8+i]==r) player.var[VAR_CONTROLS+j*8+i]=0; player.var[VAR_CONTROLS+(subcursor%3)*8+((subcursor-3)/3)]=r; subMode=SUBMODE_OPTIONS; MakeNormalSound(SND_MENUSELECT); ApplyControlSettingsMem(&player.var[VAR_CONTROLS]); SaveOptions(); } } else if(subMode==SUBMODE_SETBTN) { dword btn; btn=GetJoyButtons(); j=1; for(i=0;i<16;i++) { if((btn&j)) { player.var[VAR_CONTROLS+16+(subcursor-17)/3]=i; subMode=SUBMODE_OPTIONS; MakeNormalSound(SND_MENUSELECT); ApplyControlSettingsMem(&player.var[VAR_CONTROLS]); SaveOptions(); } j*=2; } } else if(subMode==SUBMODE_MADCAP) { if((c&CONTROL_UP) && (!reptCounter)) { subcursor--; if(subcursor==255) subcursor=10; } if((c&CONTROL_DN) && (!reptCounter)) { subcursor++; if(subcursor==11) subcursor=0; } if((c&CONTROL_B1) && (!(oldc&CONTROL_B1))) { // add a madcap crystal if(player.money>=MADCAP_PRICE*(player.var[VAR_MADGEM+subcursor]+1) && player.var[VAR_CPOINTS]>=CrystalCost(subcursor) && player.var[VAR_MADGEM+subcursor]<100) { player.var[VAR_CPOINTS]-=CrystalCost(subcursor); player.money-=(MADCAP_PRICE*(player.var[VAR_MADGEM+subcursor]+1)); player.var[VAR_MADGEM+subcursor]++; MakeNormalSound(SND_MENUSELECT); PlayerCalcStats(); j=0; for(i=0;i<11;i++) { if(player.var[VAR_MADGEM+i]==100) j++; } if(j==11) AchieveNow(99); } else MakeNormalSound(SND_MENUCANCEL); } if((c&CONTROL_B2) && (!(oldc&CONTROL_B2))) { // exit the madcap menu subMode=SUBMODE_NONE; SetHelpText(); } } else if(subMode==SUBMODE_TALENT) { if((c&CONTROL_UP) && (!reptCounter)) { subcursor--; if(subcursor==255) subcursor=9; } if((c&CONTROL_DN) && (!reptCounter)) { subcursor++; if(subcursor==10) subcursor=0; } if((c&CONTROL_LF) && (!reptCounter)) { talentPage-=10; if(talentPage>20) talentPage=20; } if((c&CONTROL_RT) && (!reptCounter)) { talentPage+=10; if(talentPage>20) talentPage=0; } if((c&CONTROL_B2) && (!(oldc&CONTROL_B2))) { // exit the talent menu subMode=SUBMODE_NONE; SetHelpText(); } } else if(subMode==SUBMODE_EQUIP) { if((c&CONTROL_UP) && (!reptCounter)) { if(subcursor<10) { if(subcursor>=3) subcursor=255; else subcursor=252+subcursor; } else if(subcursor>=252) subcursor=50+subcursor-252; else subcursor-=10; } if((c&CONTROL_DN) && (!reptCounter)) { if(subcursor>=252) subcursor=subcursor-252; else if(subcursor>=50) { if(subcursor>=53) subcursor=255; else subcursor=252+subcursor-50; } else subcursor+=10; } if((c&CONTROL_LF) && (!reptCounter)) { if(subcursor>=252) { subcursor--; if(subcursor==251) subcursor=255; } else if((subcursor%10)==0) subcursor=subcursor+9; else subcursor--; } if((c&CONTROL_RT) && (!reptCounter)) { if(subcursor>=252) { subcursor++; if(subcursor==0) subcursor=252; } else if((subcursor%10)==9) subcursor=subcursor-9; else subcursor++; } if((c&CONTROL_B1) && (!(oldc&CONTROL_B1))) { equip_t e; if(subcursor<60) { if(player.items[subcursor].type==IT_AXE || player.items[subcursor].type==IT_MAGICAXE || player.items[subcursor].type==IT_GOLDENAXE) { e=player.items[subcursor]; player.items[subcursor].count--; if(player.items[subcursor].count==0) player.items[subcursor].type=IT_NONE; if(!SimpleEquipAdd(&player.axe)) { // no room to unequip! player.items[subcursor]=e; MakeNormalSound(SND_MENUCANCEL); } else { player.axe=e; player.axe.count=1; MakeNormalSound(SND_MENUSELECT); } MakeNormalSound(SND_EQUIP); subcursor=252; SortEquipment(); PlayerCalcStats(); } else if(player.items[subcursor].type==IT_AMULET || player.items[subcursor].type==IT_MAGICAMULET || player.items[subcursor].type==IT_GOLDENAMULET) { e=player.items[subcursor]; player.items[subcursor].count--; if(player.items[subcursor].count==0) player.items[subcursor].type=IT_NONE; if(!SimpleEquipAdd(&player.amulet)) { // no room to unequip! player.items[subcursor]=e; MakeNormalSound(SND_MENUCANCEL); } else { player.amulet=e; player.amulet.count=1; MakeNormalSound(SND_MENUSELECT); } MakeNormalSound(SND_EQUIP); subcursor=253; SortEquipment(); PlayerCalcStats(); } else if(player.items[subcursor].type==IT_PARKA || player.items[subcursor].type==IT_MAGICPARKA || player.items[subcursor].type==IT_GOLDENPARKA) { e=player.items[subcursor]; player.items[subcursor].count--; if(player.items[subcursor].count==0) player.items[subcursor].type=IT_NONE; if(!SimpleEquipAdd(&player.parka)) { // no room to unequip! player.items[subcursor]=e; MakeNormalSound(SND_MENUCANCEL); } else { player.parka=e; player.parka.count=1; MakeNormalSound(SND_MENUSELECT); } MakeNormalSound(SND_EQUIP); subcursor=254; SortEquipment(); PlayerCalcStats(); } else if(player.items[subcursor].type>=IT_LENSA && player.items[subcursor].type<=IT_LENSM && player.var[VAR_GLASSES]) { MakeNormalSound(SND_MENUSELECT); if(AddLens(player.items[subcursor].type-IT_LENSA)) { DropItem(subcursor); SortEquipment(); MakeNormalSound(SND_EQUIP); if(player.lens[0]!=255 && player.lens[1]!=255) subcursor=255; // move cursor to the glasses to see what you've wrought PlayerCalcStats(); } else // can't add it { subMode=SUBMODE_EQUIPYESNO; SetHelpText(); sprintf(askingTxt,""Break equipped lenses for new ones?""); asking=1; yesno=1; } } else MakeNormalSound(SND_MENUCANCEL); if(player.axe.magic>=EM_ARTSTART && player.axe.magic<=EM_ARTEND && player.amulet.magic>=EM_ARTSTART && player.amulet.magic<=EM_ARTEND && player.parka.magic>=EM_ARTSTART && player.parka.magic<=EM_ARTEND) AchieveNow(55); if(player.lens[0]==7 && player.lens[1]==12) AchieveNow(77); } } if((c&CONTROL_B2) && (!(oldc&CONTROL_B2))) { // exit the equip menu subMode=SUBMODE_NONE; SetHelpText(); } if((c&CONTROL_B3) && (!(oldc&CONTROL_B3))) { if(subcursor4) questPage=4; } if((c&CONTROL_RT) && (!reptCounter)) { questPage++; if(questPage>4) questPage=0; } if(((c&CONTROL_B1) && (!(oldc&CONTROL_B1))) || ((c&CONTROL_B2) && (!(oldc&CONTROL_B2)))) { // exit the quest menu subMode=SUBMODE_NONE; SetHelpText(); } } else if(subMode==SUBMODE_TIPS) { if((c&CONTROL_UP) && (!reptCounter)) { subcursor--; if(subcursor==255) subcursor=9; } if((c&CONTROL_DN) && (!reptCounter)) { subcursor++; if(subcursor==10) subcursor=0; } if((c&CONTROL_LF) && (!reptCounter)) { tipPage=1-tipPage; } if((c&CONTROL_RT) && (!reptCounter)) { tipPage=1-tipPage; } if(((c&CONTROL_B1) && (!(oldc&CONTROL_B1))) || ((c&CONTROL_B2) && (!(oldc&CONTROL_B2)))) { // exit the tip menu subMode=SUBMODE_NONE; SetHelpText(); } } oldc=c; HandlePauseKeyPresses(mgl); if(lastKey==27) // hit ESC to exit pause menu { if(subMode==SUBMODE_NONE) return PAUSE_RESUME; else if(subMode==SUBMODE_SETKEY || subMode==SUBMODE_SETBTN) subMode=SUBMODE_OPTIONS; else if(subMode==SUBMODE_EQUIPYESNO) subMode=SUBMODE_EQUIP; else subMode=SUBMODE_NONE; lastKey=0; } return PAUSE_PAUSED; } ",16373,True,2882.6868494670807,median "// ********************************************************************* // Generic Utilities for NVIDIA GPU Computing SDK // ********************************************************************* // includes #include ""shrUtils.h"" //#include #include #include // size of PGM file header const unsigned int PGMHeaderSize = 0x40; #define MIN_EPSILON_ERROR 1e-3f // Deallocate memory allocated within shrUtils // ********************************************************************* void shrFree(void* ptr) { if( NULL != ptr) free( ptr); } // Helper function to init data arrays // ********************************************************************* void shrFillArray(float* pfData, int iSize) { int i; const float fScale = 1.0f / (float)RAND_MAX; for (i = 0; i < iSize; ++i) { pfData[i] = fScale * rand(); } } // Helper function to print data arrays // ********************************************************************* void shrPrintArray(float* pfData, int iSize) { int i; for (i = 0; i < iSize; ++i) { shrLog(""%d: %.3f\\n"", i, pfData[i]); } } // Helper function to return precision delta time for 3 counters since last call based upon host high performance counter // ********************************************************************* double shrDeltaT(int iCounterID = 0) { // local var for computation of microseconds since last call double DeltaT; #ifdef _WIN32 // Windows version of precision host timer // Variables that need to retain state between calls static LARGE_INTEGER liOldCount0 = {0, 0}; static LARGE_INTEGER liOldCount1 = {0, 0}; static LARGE_INTEGER liOldCount2 = {0, 0}; // locals for new count, new freq and new time delta LARGE_INTEGER liNewCount, liFreq; if (QueryPerformanceFrequency(&liFreq)) { // Get new counter reading QueryPerformanceCounter(&liNewCount); // Update the requested timer switch (iCounterID) { case 0: { // Calculate time difference for timer 0. (zero when called the first time) DeltaT = liOldCount0.LowPart ? (((double)liNewCount.QuadPart - (double)liOldCount0.QuadPart) / (double)liFreq.QuadPart) : 0.0; // Reset old count to new liOldCount0 = liNewCount; break; } case 1: { // Calculate time difference for timer 1. (zero when called the first time) DeltaT = liOldCount1.LowPart ? (((double)liNewCount.QuadPart - (double)liOldCount1.QuadPart) / (double)liFreq.QuadPart) : 0.0; // Reset old count to new liOldCount1 = liNewCount; break; } case 2: { // Calculate time difference for timer 2. (zero when called the first time) DeltaT = liOldCount2.LowPart ? (((double)liNewCount.QuadPart - (double)liOldCount2.QuadPart) / (double)liFreq.QuadPart) : 0.0; // Reset old count to new liOldCount2 = liNewCount; break; } default: { // Requested counter ID out of range return -9999.0; } } // Returns time difference in seconds sunce the last call return DeltaT; } else { // No high resolution performance counter return -9999.0; } #else // Linux version of precision host timer. See http://www.informit.com/articles/article.aspx?p=23618&seqNum=8 static struct timeval _NewTime; // new wall clock time (struct representation in seconds and microseconds) static struct timeval _OldTime0; // old wall clock time 0(struct representation in seconds and microseconds) static struct timeval _OldTime1; // old wall clock time 1(struct representation in seconds and microseconds) static struct timeval _OldTime2; // old wall clock time 2(struct representation in seconds and microseconds) // Get new counter reading gettimeofday(&_NewTime, NULL); switch (iCounterID) { case 0: { // Calculate time difference for timer 0. (zero when called the first time) DeltaT = ((double)_NewTime.tv_sec + 1.0e-6 * (double)_NewTime.tv_usec) - ((double)_OldTime0.tv_sec + 1.0e-6 * (double)_OldTime0.tv_usec); // Reset old time 0 to new _OldTime0.tv_sec = _NewTime.tv_sec; _OldTime0.tv_usec = _NewTime.tv_usec; break; } case 1: { // Calculate time difference for timer 1. (zero when called the first time) DeltaT = ((double)_NewTime.tv_sec + 1.0e-6 * (double)_NewTime.tv_usec) - ((double)_OldTime1.tv_sec + 1.0e-6 * (double)_OldTime1.tv_usec); // Reset old time 1 to new _OldTime1.tv_sec = _NewTime.tv_sec; _OldTime1.tv_usec = _NewTime.tv_usec; break; } case 2: { // Calculate time difference for timer 2. (zero when called the first time) DeltaT = ((double)_NewTime.tv_sec + 1.0e-6 * (double)_NewTime.tv_usec) - ((double)_OldTime2.tv_sec + 1.0e-6 * (double)_OldTime2.tv_usec); // Reset old time 2 to new _OldTime2.tv_sec = _NewTime.tv_sec; _OldTime2.tv_usec = _NewTime.tv_usec; break; } default: { // Requested counter ID out of range return -9999.0; } } // Returns time difference in seconds sunce the last call return DeltaT; #endif } // Optional LogFileName Override function // ********************************************************************* char* cLogFilePathAndName = NULL; void shrSetLogFileName (const char* cOverRideName) { if( cLogFilePathAndName != NULL ) { free(cLogFilePathAndName); } cLogFilePathAndName = (char*) malloc(strlen(cOverRideName) + 1); #ifdef WIN32 strcpy_s(cLogFilePathAndName, strlen(cOverRideName) + 1, cOverRideName); #else strcpy(cLogFilePathAndName, cOverRideName); #endif return; } // Function to log standardized information to console, file or both // ********************************************************************* static int shrLogV(int iLogMode, int iErrNum, const char* cFormatString, va_list vaArgList) { static FILE* pFileStream0 = NULL; static FILE* pFileStream1 = NULL; size_t szNumWritten = 0; char cFileMode [3]; // if the sample log file is closed and the call incudes a ""write-to-file"", open file for writing if ((pFileStream0 == NULL) && (iLogMode & LOGFILE)) { // if the default filename has not been overriden, set to default if (cLogFilePathAndName == NULL) { shrSetLogFileName(DEFAULTLOGFILE); } #ifdef _WIN32 // Windows version // set the file mode if (iLogMode & APPENDMODE) // append to prexisting file contents { sprintf_s (cFileMode, 3, ""a+""); } else // replace prexisting file contents { sprintf_s (cFileMode, 3, ""w""); } // open the individual sample log file in the requested mode errno_t err = fopen_s(&pFileStream0, cLogFilePathAndName, cFileMode); // if error on attempt to open, be sure the file is null or close it, then return negative error code if (err != 0) { if (pFileStream0) { fclose (pFileStream0); } return -err; } #else // Linux & Mac version // set the file mode if (iLogMode & APPENDMODE) // append to prexisting file contents { sprintf (cFileMode, ""a+""); } else // replace prexisting file contents { sprintf (cFileMode, ""w""); } // open the file in the requested mode if ((pFileStream0 = fopen(cLogFilePathAndName, cFileMode)) == 0) { // if error on attempt to open, be sure the file is null or close it, then return negative error code if (pFileStream0) { fclose (pFileStream0); } return -1; } #endif } // if the master log file is closed and the call incudes a ""write-to-file"" and MASTER, open master logfile file for writing if ((pFileStream1 == NULL) && (iLogMode & LOGFILE) && (iLogMode & MASTER)) { #ifdef _WIN32 // Windows version // open the master log file in append mode errno_t err = fopen_s(&pFileStream1, MASTERLOGFILE, ""a+""); // if error on attempt to open, be sure the file is null or close it, then return negative error code if (err != 0) { if (pFileStream1) { fclose (pFileStream1); } return -err; } #else // Linux & Mac version // open the file in the requested mode if ((pFileStream1 = fopen(MASTERLOGFILE, ""a+"")) == 0) { // if error on attempt to open, be sure the file is null or close it, then return negative error code if (pFileStream1) { fclose (pFileStream1); } return -1; } #endif // If master log file length has become excessive, empty/reopen fseek(pFileStream1, 0L, SEEK_END); if (ftell(pFileStream1) > 50000L) { fclose (pFileStream1); #ifdef _WIN32 // Windows version fopen_s(&pFileStream1, MASTERLOGFILE, ""w""); #else pFileStream1 = fopen(MASTERLOGFILE, ""w""); #endif } } // Handle special Error Message code if (iLogMode & ERRORMSG) { // print string to console if flagged if (iLogMode & LOGCONSOLE) { szNumWritten = printf (""\\n !!! Error # %i at "", iErrNum); // console } // print string to file if flagged if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, ""\\n !!! Error # %i at "", iErrNum); // sample log file } } // Vars used for variable argument processing const char* pStr; const char* cArg; int iArg; double dArg; unsigned int uiArg; std::string sFormatSpec; const std::string sFormatChars = "" -+#0123456789.dioufnpcsXxEeGgAa""; const std::string sTypeChars = ""dioufnpcsXxEeGgAa""; char cType = 'c'; // Start at the head of the string and scan to the null at the end for (pStr = cFormatString; *pStr; ++pStr) { // Check if the current character is not a formatting specifier ('%') if (*pStr != '%') { // character is not '%', so print it verbatim to console and/or files as flagged if (iLogMode & LOGCONSOLE) { szNumWritten = putc(*pStr, stdout); // console } if (iLogMode & LOGFILE) { szNumWritten = putc(*pStr, pFileStream0); // sample log file if (iLogMode & MASTER) { szNumWritten = putc(*pStr, pFileStream1); // master log file } } } else { // character is '%', so skip over it and read the full format specifier for the argument ++pStr; sFormatSpec = '%'; // special handling for string of %%%% bool bRepeater = (*pStr == '%'); if (bRepeater) { cType = '%'; } // chars after the '%' are part of format if on list of constants... scan until that isn't true or NULL is found /*while (pStr && ((sFormatChars.find(*pStr) != string::npos) || bRepeater)) { sFormatSpec += *pStr; // If the char is a type specifier, trap it and stop scanning // (a type specifier char is always the last in the format except for string of %%%) if (sTypeChars.find(*pStr) != string::npos) { cType = *pStr; break; } // Special handling for string of %%% // If a string of %%% was started and then it ends, break (There won't be a typical type specifier) if (bRepeater && (*pStr != '%')) { break; } pStr++; }*/ // Now handle the arg according to type switch (cType) { case '%': // special handling for string of %%%% { if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str()); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str()); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str()); // master log file } } continue; } case 'c': // single byte char case 's': // string of single byte chars { // Set cArg as the next value in list and print to console and/or files if flagged cArg = va_arg(vaArgList, char*); if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str(), cArg); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), cArg); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), cArg); // master log file } } continue; } case 'd': // signed decimal integer case 'i': // signed decimal integer { // set iArg as the next value in list and print to console and/or files if flagged iArg = va_arg(vaArgList, int); if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str(), iArg); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), iArg); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), iArg); // master log file } } continue; } case 'u': // unsigned decimal integer case 'o': // unsigned octal integer case 'x': // unsigned hexadecimal integer using ""abcdef"" case 'X': // unsigned hexadecimal integer using ""ABCDEF"" { // set uiArg as the next value in list and print to console and/or files if flagged uiArg = va_arg(vaArgList, unsigned int); if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str(), uiArg); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), uiArg); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), uiArg); // master log file } } continue; } case 'f': // float/double case 'e': // scientific double/float case 'E': // scientific double/float case 'g': // scientific double/float case 'G': // scientific double/float case 'a': // signed hexadecimal double precision float case 'A': // signed hexadecimal double precision float { // set dArg as the next value in list and print to console and/or files if flagged dArg = va_arg(vaArgList, double); if (iLogMode & LOGCONSOLE) { szNumWritten = printf(sFormatSpec.c_str(), dArg); // console } if (iLogMode & LOGFILE) { szNumWritten = fprintf (pFileStream0, sFormatSpec.c_str(), dArg); // sample log file if (iLogMode & MASTER) { szNumWritten = fprintf(pFileStream1, sFormatSpec.c_str(), dArg); // master log file } } continue; } default: { // print arg of unknown/unsupported type to console and/or file if flagged if (iLogMode & LOGCONSOLE) // console { szNumWritten = putc(*pStr, stdout); } if (iLogMode & LOGFILE) { szNumWritten = putc(*pStr, pFileStream0); // sample log file if (iLogMode & MASTER) { szNumWritten = putc(*pStr, pFileStream1); // master log file } } } } } } // end the sample log with a horizontal line if closing if (iLogMode & CLOSELOG) { if (iLogMode & LOGCONSOLE) { printf(HDASHLINE); } if (iLogMode & LOGFILE) { fprintf(pFileStream0, HDASHLINE); } } // flush console and/or file buffers if updated if (iLogMode & LOGCONSOLE) { fflush(stdout); } if (iLogMode & LOGFILE) { fflush (pFileStream0); // if the master log file has been updated, flush it too if (iLogMode & MASTER) { fflush (pFileStream1); } } // If the log file is open and the caller requests ""close file"", then close and NULL file handle if ((pFileStream0) && (iLogMode & CLOSELOG)) { fclose (pFileStream0); pFileStream0 = NULL; } if ((pFileStream1) && (iLogMode & CLOSELOG)) { fclose (pFileStream1); pFileStream1 = NULL; } // return error code or OK if (iLogMode & ERRORMSG) { return iErrNum; } else { return 0; } } // Function to log standardized information to console, file or both // ********************************************************************* int shrLogEx(int iLogMode = LOGCONSOLE, int iErrNum = 0, const char* cFormatString = """", ...) { return 0; va_list vaArgList; // Prepare variable agument list va_start(vaArgList, cFormatString); int ret = shrLogV(iLogMode, iErrNum, cFormatString, vaArgList); // end variable argument handler va_end(vaArgList); std::cout << cFormatString << std::endl; return ret; } // Function to log standardized information to console, file or both // ********************************************************************* int shrLog(const char* cFormatString = """", ...) { va_list vaArgList; // Prepare variable agument list va_start(vaArgList, cFormatString); int ret = shrLogV(LOGBOTH, 0, cFormatString, vaArgList); // end variable argument handler va_end(vaArgList); return ret; } ////////////////////////////////////////////////////////////////////////////// //! Find the path for a file assuming that //! files are found in the searchPath. //! //! @return the path if succeeded, otherwise 0 //! @param filename name of the file //! @param executable_path optional absolute path of the executable ////////////////////////////////////////////////////////////////////////////// char* shrFindFilePath(const char* filename, const char* executable_path) { // defines a variable that is replaced with the name of the executable // Typical relative search paths to locate needed companion files (e.g. sample input data, or JIT source files) // The origin for the relative search may be the .exe file, a .bat file launching an .exe, a browser .exe launching the .exe or .bat, etc const char* searchPath[] = { ""./"", // same dir ""./data/"", // ""/data/"" subdir ""./src/"", // ""/src/"" subdir ""./src//data/"", // ""/src//data/"" subdir ""./inc/"", // ""/inc/"" subdir ""../"", // up 1 in tree ""../data/"", // up 1 in tree, ""/data/"" subdir ""../src/"", // up 1 in tree, ""/src/"" subdir ""../inc/"", // up 1 in tree, ""/inc/"" subdir ""../OpenCL/src//"", // up 1 in tree, ""/OpenCL/src//"" subdir ""../OpenCL/src//data/"", // up 1 in tree, ""/OpenCL/src//data/"" subdir ""../OpenCL/src//src/"", // up 1 in tree, ""/OpenCL/src//src/"" subdir ""../OpenCL/src//inc/"", // up 1 in tree, ""/OpenCL/src//inc/"" subdir ""../C/src//"", // up 1 in tree, ""/C/src//"" subdir ""../C/src//data/"", // up 1 in tree, ""/C/src//data/"" subdir ""../C/src//src/"", // up 1 in tree, ""/C/src//src/"" subdir ""../C/src//inc/"", // up 1 in tree, ""/C/src//inc/"" subdir ""../DirectCompute/src//"", // up 1 in tree, ""/DirectCompute/src//"" subdir ""../DirectCompute/src//data/"", // up 1 in tree, ""/DirectCompute/src//data/"" subdir ""../DirectCompute/src//src/"", // up 1 in tree, ""/DirectCompute/src//src/"" subdir ""../DirectCompute/src//inc/"", // up 1 in tree, ""/DirectCompute/src//inc/"" subdir ""../../"", // up 2 in tree ""../../data/"", // up 2 in tree, ""/data/"" subdir ""../../src/"", // up 2 in tree, ""/src/"" subdir ""../../inc/"", // up 2 in tree, ""/inc/"" subdir ""../../../"", // up 3 in tree ""../../../src//"", // up 3 in tree, ""/src//"" subdir ""../../../src//data/"", // up 3 in tree, ""/src//data/"" subdir ""../../../src//src/"", // up 3 in tree, ""/src//src/"" subdir ""../../../src//inc/"", // up 3 in tree, ""/src//inc/"" subdir ""../../../sandbox//"", // up 3 in tree, ""/sandbox//"" subdir ""../../../sandbox//data/"", // up 3 in tree, ""/sandbox//data/"" subdir ""../../../sandbox//src/"", // up 3 in tree, ""/sandbox//src/"" subdir ""../../../sandbox//inc/"" // up 3 in tree, ""/sandbox//inc/"" subdir }; // Extract the executable name std::string executable_name; if (executable_path != 0) { executable_name = std::string(executable_path); #ifdef _WIN32 // Windows path delimiter size_t delimiter_pos = executable_name.find_last_of('\\\\'); executable_name.erase(0, delimiter_pos + 1); if (executable_name.rfind("".exe"") != std::string::npos) { // we strip .exe, only if the .exe is found executable_name.resize(executable_name.size() - 4); } #else // Linux & OSX path delimiter size_t delimiter_pos = executable_name.find_last_of('/'); executable_name.erase(0,delimiter_pos+1); #endif } // Loop over all search paths and return the first hit for( unsigned int i = 0; i < sizeof(searchPath)/sizeof(char*); ++i ) { std::string path(searchPath[i]); size_t executable_name_pos = path.find(""""); // If there is executable_name variable in the searchPath // replace it with the value if(executable_name_pos != std::string::npos) { if(executable_path != 0) { path.replace(executable_name_pos, strlen(""""), executable_name); } else { // Skip this path entry if no executable argument is given continue; } } // Test if the file exists path.append(filename); std::fstream fh(path.c_str(), std::fstream::in); if (fh.good()) { // File found // returning an allocated array here for backwards compatibility reasons char* file_path = (char*) malloc(path.length() + 1); #ifdef _WIN32 strcpy_s(file_path, path.length() + 1, path.c_str()); #else strcpy(file_path, path.c_str()); #endif return file_path; } } // File not found return 0; } ////////////////////////////////////////////////////////////////////////////// //! Read file \\filename and return the data //! @return shrTRUE if reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error ////////////////////////////////////////////////////////////////////////////// template shrBOOL shrReadFile( const char* filename, T** data, unsigned int* len, bool verbose) { // check input arguments /*ARGCHECK(NULL != filename); ARGCHECK(NULL != len); // intermediate storage for the data read std::vector data_read; // open file for reading std::fstream fh( filename, std::fstream::in); // check if filestream is valid if(!fh.good()) { if (verbose) std::cerr << ""shrReadFile() : Opening file failed."" << std::endl; return shrFALSE; } // read all data elements T token; while( fh.good()) { fh >> token; data_read.push_back( token); } // the last element is read twice data_read.pop_back(); // check if reading result is consistent if( ! fh.eof()) { if (verbose) std::cerr << ""WARNING : readData() : reading file might have failed."" << std::endl; } fh.close(); // check if the given handle is already initialized if( NULL != *data) { if( *len != data_read.size()) { std::cerr << ""shrReadFile() : Initialized memory given but "" << ""size mismatch with signal read "" << ""(data read / data init = "" << (unsigned int)data_read.size() << "" / "" << *len << "")"" << std::endl; return shrFALSE; } } else { // allocate storage for the data read *data = (T*) malloc( sizeof(T) * data_read.size()); // store signal size *len = static_cast( data_read.size()); } // copy data memcpy( *data, &data_read.front(), sizeof(T) * data_read.size()); */ return shrTRUE; } ////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename //! @return shrTRUE if writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison ////////////////////////////////////////////////////////////////////////////// template shrBOOL shrWriteFile( const char* filename, const T* data, unsigned int len, const T epsilon, bool verbose) { ARGCHECK(NULL != filename); ARGCHECK(NULL != data); // open file for writing std::fstream fh( filename, std::fstream::out); // check if filestream is valid if(!fh.good()) { if (verbose) std::cerr << ""shrWriteFile() : Opening file failed."" << std::endl; return shrFALSE; } // first write epsilon fh << ""# "" << epsilon << ""\\n""; // write data for( unsigned int i = 0; (i < len) && (fh.good()); ++i) { fh << data[i] << ' '; } // Check if writing succeeded if( ! fh.good()) { if (verbose) std::cerr << ""shrWriteFile() : Writing file failed."" << std::endl; return shrFALSE; } // file ends with nl fh << std::endl; return shrTRUE; } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg single precision floating point data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFilef( const char* filename, float** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg double precision floating point data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFiled( const char* filename, double** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg integer data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFilei( const char* filename, int** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg unsigned integer data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFileui( const char* filename, unsigned int** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg char / byte data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFileb( const char* filename, char** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Read file \\filename containg unsigned char / byte data //! @return shrTRUEif reading the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data uninitialized pointer, returned initialized and pointing to //! the data read //! @param len number of data elements in data, -1 on error //////////////////////////////////////////////////////////////////////////////// shrBOOL shrReadFileub( const char* filename, unsigned char** data, unsigned int* len, bool verbose) { return shrReadFile( filename, data, len, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for single precision floating point data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFilef( const char* filename, const float* data, unsigned int len, const float epsilon, bool verbose) { return shrWriteFile( filename, data, len, epsilon, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for double precision floating point data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFiled( const char* filename, const double* data, unsigned int len, const double epsilon, bool verbose) { return shrWriteFile( filename, data, len, epsilon, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for integer data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFilei( const char* filename, const int* data, unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, 0, verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for unsigned integer data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFileui( const char* filename,const unsigned int* data,unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, static_cast(0), verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for byte / char data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFileb( const char* filename, const char* data, unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, static_cast(0), verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for byte / char data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFileub( const char* filename, const unsigned char* data, unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, static_cast(0), verbose); } //////////////////////////////////////////////////////////////////////////////// //! Write a data file \\filename for unsigned byte / char data //! @return shrTRUEif writing the file succeeded, otherwise shrFALSE //! @param filename name of the source file //! @param data data to write //! @param len number of data elements in data, -1 on error //! @param epsilon epsilon for comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrWriteFileb( const char* filename,const unsigned char* data,unsigned int len, bool verbose) { return shrWriteFile( filename, data, len, static_cast(0), verbose); } ////////////////////////////////////////////////////////////////////////////// //! Load PGM or PPM file //! @note if data == NULL then the necessary memory is allocated in the //! function and w and h are initialized to the size of the image //! @return shrTRUE if the file loading succeeded, otherwise shrFALSE //! @param file name of the file to load //! @param data handle to the memory for the image file data //! @param w width of the image //! @param h height of the image //! @param channels number of channels in image ////////////////////////////////////////////////////////////////////////////// shrBOOL loadPPM(const char* file, unsigned char** data, unsigned int *w, unsigned int *h, unsigned int *channels) { FILE* fp = 0; #ifdef _WIN32 // open the file for binary read errno_t err; if ((err = fopen_s(&fp, file, ""rb"")) != 0) #else // open the file for binary read if ((fp = fopen(file, ""rb"")) == 0) #endif { // if error on attempt to open, be sure the file is null or close it, then return negative error code if (fp) { fclose (fp); } std::cerr << ""loadPPM() : Failed to open file: "" << file << std::endl; return shrFALSE; } // check header char header[PGMHeaderSize]; if ((fgets( header, PGMHeaderSize, fp) == NULL) && ferror(fp)) { if (fp) { fclose (fp); } std::cerr << ""loadPPM() : File is not a valid PPM or PGM image"" << std::endl; *channels = 0; return shrFALSE; } if (strncmp(header, ""P5"", 2) == 0) { *channels = 1; } else if (strncmp(header, ""P6"", 2) == 0) { *channels = 3; } else { std::cerr << ""loadPPM() : File is not a PPM or PGM image"" << std::endl; *channels = 0; return shrFALSE; } // parse header, read maxval, width and height unsigned int width = 0; unsigned int height = 0; unsigned int maxval = 0; unsigned int i = 0; while(i < 3) { if ((fgets(header, PGMHeaderSize, fp) == NULL) && ferror(fp)) { if (fp) { fclose (fp); } std::cerr << ""loadPPM() : File is not a valid PPM or PGM image"" << std::endl; return shrFALSE; } if(header[0] == '#') continue; #ifdef _WIN32 if(i == 0) { i += sscanf_s(header, ""%u %u %u"", &width, &height, &maxval); } else if (i == 1) { i += sscanf_s(header, ""%u %u"", &height, &maxval); } else if (i == 2) { i += sscanf_s(header, ""%u"", &maxval); } #else if(i == 0) { i += sscanf(header, ""%u %u %u"", &width, &height, &maxval); } else if (i == 1) { i += sscanf(header, ""%u %u"", &height, &maxval); } else if (i == 2) { i += sscanf(header, ""%u"", &maxval); } #endif } // check if given handle for the data is initialized if(NULL != *data) { if (*w != width || *h != height) { fclose(fp); std::cerr << ""loadPPM() : Invalid image dimensions."" << std::endl; return shrFALSE; } } else { *data = (unsigned char*)malloc( sizeof(unsigned char) * width * height * *channels); *w = width; *h = height; } // read and close file if (fread(*data, sizeof(unsigned char), width * height * *channels, fp) != width * height * *channels) { fclose(fp); std::cerr << ""loadPPM() : Invalid image."" << std::endl; return shrFALSE; } fclose(fp); return shrTRUE; } ////////////////////////////////////////////////////////////////////////////// //! Write / Save PPM or PGM file //! @note Internal usage only //! @param file name of the image file //! @param data handle to the data read //! @param w width of the image //! @param h height of the image ////////////////////////////////////////////////////////////////////////////// shrBOOL savePPM( const char* file, unsigned char *data, unsigned int w, unsigned int h, unsigned int channels) { ARGCHECK(NULL != data); ARGCHECK(w > 0); ARGCHECK(h > 0); std::fstream fh( file, std::fstream::out | std::fstream::binary ); if( fh.bad()) { std::cerr << ""savePPM() : Opening file failed."" << std::endl; return shrFALSE; } if (channels == 1) { fh << ""P5\\n""; } else if (channels == 3) { fh << ""P6\\n""; } else { std::cerr << ""savePPM() : Invalid number of channels."" << std::endl; return shrFALSE; } fh << w << ""\\n"" << h << ""\\n"" << 0xff << std::endl; for( unsigned int i = 0; (i < (w*h*channels)) && fh.good(); ++i) { fh << data[i]; } fh.flush(); if( fh.bad()) { std::cerr << ""savePPM() : Writing data failed."" << std::endl; return shrFALSE; } fh.close(); return shrTRUE; } //////////////////////////////////////////////////////////////////////////////// //! Load PPM image file (with unsigned char as data element type), padding 4th component //! @return shrTrue if reading the file succeeded, otherwise shrFALSE //! @param file name of the image file //! @param data handle to the data read //! @param w width of the image //! @param h height of the image //////////////////////////////////////////////////////////////////////////////// shrBOOL shrLoadPPM4ub( const char* file, unsigned char** OutData, unsigned int *w, unsigned int *h) { // Load file data into a temporary buffer with automatic allocation unsigned char* cLocalData = 0; unsigned int channels; shrBOOL bLoadOK = loadPPM(file, &cLocalData, w, h, &channels); // this allocates cLocalData, which must be freed later // If the data loaded OK from file to temporary buffer, then go ahead with padding and transfer if (shrTRUE == bLoadOK) { // if the receiving buffer is null, allocate it... caller must free this int size = *w * *h; if (*OutData == NULL) { *OutData = (unsigned char*)malloc(sizeof(unsigned char) * size * 4); } // temp pointers for incrementing unsigned char* cTemp = cLocalData; unsigned char* cOutPtr = *OutData; // transfer data, padding 4th element for(int i=0; i( arg_name); if( NULL != v) { // assign value *val = *v; ret_val = shrTRUE; } else { // fail safe val = NULL; }*/ } catch( const std::exception& /*ex*/) { std::cerr << ""Error when parsing command line argument string."" << std::endl; } return ret_val; } //////////////////////////////////////////////////////////////////////////////// //! Get the value of a command line argument of type unsigned int //! @return shrTRUE if command line argument \\a arg_name has been given and //! is of the requested type, otherwise shrFALSE //! @param argc argc as passed to main() //! @param argv argv as passed to main() //! @param arg_name name of the command line argument //! @param val value of the command line argument //////////////////////////////////////////////////////////////////////////////// shrBOOL shrGetCmdLineArgumentu( const int argc, const char** argv, const char* arg_name, unsigned int* val) { shrBOOL ret_val = shrFALSE; try { // initialize /*CmdArgReader::init( argc, argv); // access argument const int* v = CmdArgReader::getArg( arg_name); if( NULL != v) { // assign value *val = *v; ret_val = shrTRUE; } else { // fail safe val = NULL; }*/ } catch( const std::exception& /*ex*/) { std::cerr << ""Error when parsing command line argument string."" << std::endl; } return ret_val; } //////////////////////////////////////////////////////////////////////////////// //! Get the value of a command line argument of type float //! @return shrTRUE if command line argument \\a arg_name has been given and //! is of the requested type, otherwise shrFALSE //! @param argc argc as passed to main() //! @param argv argv as passed to main() //! @param arg_name name of the command line argument //! @param val value of the command line argument //////////////////////////////////////////////////////////////////////////////// shrBOOL shrGetCmdLineArgumentf( const int argc, const char** argv, const char* arg_name, float* val) { shrBOOL ret_val = shrFALSE; try { // initialize /*CmdArgReader::init( argc, argv); // access argument const float* v = CmdArgReader::getArg( arg_name); if( NULL != v) { // assign value *val = *v; ret_val = shrTRUE; } else { // fail safe val = NULL; }*/ } catch( const std::exception& /*ex*/) { std::cerr << ""Error when parsing command line argument string."" << std::endl; } return ret_val; } //////////////////////////////////////////////////////////////////////////////// //! Get the value of a command line argument of type string //! @return shrTRUE if command line argument \\a arg_name has been given and //! is of the requested type, otherwise shrFALSE //! @param argc argc as passed to main() //! @param argv argv as passed to main() //! @param arg_name name of the command line argument //! @param val value of the command line argument //////////////////////////////////////////////////////////////////////////////// shrBOOL shrGetCmdLineArgumentstr( const int argc, const char** argv, const char* arg_name, char** val) { shrBOOL ret_val = shrFALSE; try { // initialize /*CmdArgReader::init( argc, argv); // access argument const std::string* v = CmdArgReader::getArg( arg_name); if( NULL != v) { // allocate memory for the string *val = (char*)malloc(sizeof(char) * (v->length() + 1)); // copy from string to c_str #ifdef WIN32 strcpy_s(*val, v->length() + 1, v->c_str()); #else strcpy(*val, v->c_str()); #endif ret_val = shrTRUE; } else { // fail safe *val = NULL; }*/ } catch( const std::exception& /*ex*/) { std::cerr << ""Error when parsing command line argument string.""<< std::endl; } return ret_val; } ////////////////////////////////////////////////////////////////////////////// //! Compare two arrays of arbitrary type //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison ////////////////////////////////////////////////////////////////////////////// template shrBOOL compareData( const T* reference, const T* data, const unsigned int len, const S epsilon, const float threshold) { ARGCHECK( epsilon >= 0); bool result = true; unsigned int error_count = 0; for( unsigned int i = 0; i < len; ++i) { T diff = reference[i] - data[i]; bool comp = (diff <= epsilon) && (diff >= -epsilon); result &= comp; error_count += !comp; #ifdef _DEBUG if( ! comp) { std::cerr << ""ERROR, i = "" << i << "",\\t "" << reference[i] << "" / "" << data[i] << "" (reference / data)\\n""; } #endif } if (threshold == 0.0f) { return (result) ? shrTRUE : shrFALSE; } else { return (len*threshold > error_count) ? shrTRUE : shrFALSE; } } ////////////////////////////////////////////////////////////////////////////// //! Compare two arrays of arbitrary type //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison ////////////////////////////////////////////////////////////////////////////// template shrBOOL compareDataAsFloat( const T* reference, const T* data, const unsigned int len, const S epsilon) { ARGCHECK(epsilon >= 0); // If we set epsilon to be 0, let's set a minimum threshold float max_error = MAX( (float)epsilon, MIN_EPSILON_ERROR ); int error_count = 0; bool result = true; for( unsigned int i = 0; i < len; ++i) { float diff = fabs((float)reference[i] - (float)data[i]); bool comp = (diff < max_error); result &= comp; if( ! comp) { error_count++; #ifdef _DEBUG if (error_count < 50) { shrLog(""\\n ERROR(epsilon=%4.3f), i=%d, (ref)0x%02x / (data)0x%02x / (diff)%d\\n"", max_error, i, reference[i], data[i], (unsigned int)diff); } #endif } } if (error_count) { shrLog(""\\n Total # of errors = %d\\n"", error_count); } return (error_count == 0) ? shrTRUE : shrFALSE; } ////////////////////////////////////////////////////////////////////////////// //! Compare two arrays of arbitrary type //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison //! @param epsilon threshold % of (# of bytes) for pass/fail ////////////////////////////////////////////////////////////////////////////// template shrBOOL compareDataAsFloatThreshold( const T* reference, const T* data, const unsigned int len, const S epsilon, const float threshold) { ARGCHECK(epsilon >= 0); // If we set epsilon to be 0, let's set a minimum threshold float max_error = MAX( (float)epsilon, MIN_EPSILON_ERROR); int error_count = 0; bool result = true; for( unsigned int i = 0; i < len; ++i) { float diff = fabs((float)reference[i] - (float)data[i]); bool comp = (diff < max_error); result &= comp; if( ! comp) { error_count++; #ifdef _DEBUG if (error_count < 50) { shrLog(""\\n ERROR(epsilon=%4.3f), i=%d, (ref)0x%02x / (data)0x%02x / (diff)%d\\n"", max_error, i, reference[i], data[i], (unsigned int)diff); } #endif } } if (threshold == 0.0f) { if (error_count) { shrLog(""\\n Total # of errors = %d\\n"", error_count); } return (error_count == 0) ? shrTRUE : shrFALSE; } else { if (error_count) { shrLog(""\\n %.2f(%%) of bytes mismatched (count=%d)\\n"", (float)error_count*100/(float)len, error_count); } return ((len*threshold > error_count) ? shrTRUE : shrFALSE); } } //////////////////////////////////////////////////////////////////////////////// //! Compare two float arrays //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparef( const float* reference, const float* data, const unsigned int len ) { const float epsilon = 0.0; return compareData( reference, data, len, epsilon, 0.0f ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two integer arrays //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparei( const int* reference, const int* data, const unsigned int len ) { const int epsilon = 0; return compareData( reference, data, len, epsilon, 0.0f); } //////////////////////////////////////////////////////////////////////////////// //! Compare two unsigned integer arrays, with epsilon and threshold //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareuit( const unsigned int* reference, const unsigned int* data, const unsigned int len, const float epsilon, const float threshold ) { // const int epsilon = 0; return compareData( reference, data, len, epsilon, threshold ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two integer arrays //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareub( const unsigned char* reference, const unsigned char* data, const unsigned int len ) { const int epsilon = 0; return compareData( reference, data, len, epsilon, 0.0f); } //////////////////////////////////////////////////////////////////////////////// //! Compare two integer arrays (inc Threshold for # of pixel we can have errors) //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareubt( const unsigned char* reference, const unsigned char* data, const unsigned int len, const float epsilon, const float threshold ) { return compareDataAsFloatThreshold( reference, data, len, epsilon, threshold ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two integer arrays //! @return shrTRUE if \\a reference and \\a data are identical, //! otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareube( const unsigned char* reference, const unsigned char* data, const unsigned int len, const float epsilon ) { return compareDataAsFloat( reference, data, len, epsilon ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two float arrays with an epsilon tolerance for equality //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparefe( const float* reference, const float* data, const unsigned int len, const float epsilon ) { return compareData( reference, data, len, epsilon, 0.0f); } //////////////////////////////////////////////////////////////////////////////// //! Compare two float arrays with an epsilon tolerance for equality and a //! threshold for # pixel errors //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparefet( const float* reference, const float* data, const unsigned int len, const float epsilon, const float threshold ) { return compareDataAsFloatThreshold( reference, data, len, epsilon, threshold ); } //////////////////////////////////////////////////////////////////////////////// //! Compare two float arrays using L2-norm with an epsilon tolerance for equality //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param reference handle to the reference data / gold image //! @param data handle to the computed data //! @param len number of elements in reference and data //! @param epsilon epsilon to use for the comparison //////////////////////////////////////////////////////////////////////////////// shrBOOL shrCompareL2fe( const float* reference, const float* data, const unsigned int len, const float epsilon ) { ARGCHECK(epsilon >= 0); float error = 0; float ref = 0; for( unsigned int i = 0; i < len; ++i) { float diff = reference[i] - data[i]; error += diff * diff; ref += reference[i] * reference[i]; } float normRef = 0.0f;//sqrtf(ref); if (fabs(ref) < 1e-7) { #ifdef _DEBUG std::cerr << ""ERROR, reference l2-norm is 0\\n""; #endif return shrFALSE; } float normError = 0.0f; //sqrtf(error); error = normError / normRef; bool result = error < epsilon; #ifdef _DEBUG if( ! result) { std::cerr << ""ERROR, l2-norm error "" << error << "" is greater than epsilon "" << epsilon << ""\\n""; } #endif return result ? shrTRUE : shrFALSE; } //////////////////////////////////////////////////////////////////////////////// //! Compare two PPM image files with an epsilon tolerance for equality //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param src_file filename for the image to be compared //! @param data filename for the reference data / gold image //! @param epsilon epsilon to use for the comparison //! @param threshold threshold of pixels that can still mismatch to pass (i.e. 0.15f = 15% must pass) //! @param verboseErrors output details of image mismatch to std::cerr //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparePPM( const char *src_file, const char *ref_file, const float epsilon, const float threshold) { unsigned char* src_data = NULL; unsigned char* ref_data = NULL; unsigned long error_count = 0; unsigned int ref_width, ref_height; unsigned int src_width, src_height; // Check sample and reference file pointers if (src_file == NULL || ref_file == NULL) { shrLog(""\\n> shrComparePGM: src_file or ref_file is NULL\\n Aborting comparison !!!\\n\\n""); return shrFALSE; } shrLog(""\\n> shrComparePPM:\\n (a)rendered: <%s>\\n (b)reference: <%s>\\n"", src_file, ref_file); // Load the ref image file if (shrLoadPPM4ub(ref_file, &ref_data, &ref_width, &ref_height) != shrTRUE) { shrLog(""\\n Unable to load ref image file: %s\\n Aborting comparison !!!\\n\\n"", ref_file); return shrFALSE; } // Load the sample image file if (shrLoadPPM4ub(src_file, &src_data, &src_width, &src_height) != shrTRUE) { shrLog(""\\n Unable to load src image file: %s\\n Aborting comparison !!!\\n\\n"", src_file); return shrFALSE; } // check to see if image dimensions match if(src_height != ref_height || src_width != ref_width) { shrLog(""\\n Source and ref size mismatch (%u x %u) vs (%u x %u)\\n Aborting Comparison !!!\\n\\n "", src_width, src_height, ref_width, ref_height); return shrFALSE; } // compare the images if (shrCompareubt(ref_data, src_data, src_width*src_height*4, epsilon, threshold ) == shrFALSE) { error_count=1; } shrLog("" Images %s\\n\\n"", (error_count == 0) ? ""Match"" : ""Don't Match !!!""); return (error_count == 0) ? shrTRUE : shrFALSE; // returns true if all pixels pass } //////////////////////////////////////////////////////////////////////////////// //! Compare two PGM image files with an epsilon tolerance for equality //! @return shrTRUE if \\a reference and \\a data are identical, otherwise shrFALSE //! @param src_file filename for the image to be compared //! @param data filename for the reference data / gold image //! @param epsilon epsilon to use for the comparison //! @param threshold threshold of pixels that can still mismatch to pass (i.e. 0.15f = 15% must pass) //////////////////////////////////////////////////////////////////////////////// shrBOOL shrComparePGM( const char *src_file, const char *ref_file, const float epsilon, const float threshold) { unsigned char* src_data = NULL; unsigned char* ref_data = NULL; unsigned long error_count = 0; unsigned int ref_width, ref_height; unsigned int src_width, src_height; // Check sample and reference file pointers if (src_file == NULL || ref_file == NULL) { shrLog(""\\n> shrComparePGM: src_file or ref_file is NULL\\n Aborting comparison !!!\\n\\n""); return shrFALSE; } shrLog(""\\n> shrComparePGM:\\n (a)rendered: <%s>\\n (b)reference: <%s>\\n"", src_file, ref_file); // Load the ref image file if (shrLoadPPM4ub(ref_file, &ref_data, &ref_width, &ref_height) != shrTRUE) { shrLog(""\\n Unable to load ref image file: %s\\n Aborting comparison !!!\\n\\n"", ref_file); return shrFALSE; } // Load the sample image file if (shrLoadPPM4ub(src_file, &src_data, &src_width, &src_height) != shrTRUE) { shrLog(""\\n Unable to load src image file: %s\\n Aborting comparison !!!\\n\\n"", src_file); return shrFALSE; } // check to see if image dimensions match if(src_height != ref_height || src_width != ref_width) { shrLog(""\\n Source and ref size mismatch (%u x %u) vs (%u x %u)\\n Aborting Comparison !!!\\n\\n "", src_width, src_height, ref_width, ref_height); return shrFALSE; } // compare the images if (shrCompareubt(ref_data, src_data, src_width*src_height*4, epsilon, threshold ) == shrFALSE) { error_count=1; } shrLog("" Images %s\\n\\n"", (error_count == 0) ? ""Match"" : ""Don't Match !!!""); return (error_count == 0) ? shrTRUE : shrFALSE; // returns true if all pixels pass } // Load raw data from disk unsigned char* shrLoadRawFile(const char* filename, size_t size) { FILE *fp = NULL; #ifdef WIN32 errno_t err; if ((err = fopen_s(&fp, filename, ""rb"")) != 0) #else if ((fp = fopen(filename, ""rb"")) == NULL) #endif { shrLog("" Error opening file '%s' !!!\\n"", filename); return 0; } unsigned char* data = (unsigned char*)malloc(size); size_t read = fread(data, 1, size, fp); fclose(fp); shrLog("" Read '%s', %d bytes\\n"", filename, read); return data; } // Round Up Division function size_t shrRoundUp(int group_size, int global_size) { int r = global_size % group_size; if(r == 0) { return global_size; } else { return global_size + group_size - r; } } ",16162,False,2323.0851359937483,median "// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""src/compiler/ast-graph-builder.h"" #include ""src/compiler.h"" #include ""src/compiler/control-builders.h"" #include ""src/compiler/machine-operator.h"" #include ""src/compiler/node-properties.h"" #include ""src/compiler/node-properties-inl.h"" #include ""src/full-codegen.h"" #include ""src/parser.h"" #include ""src/scopes.h"" namespace v8 { namespace internal { namespace compiler { AstGraphBuilder::AstGraphBuilder(CompilationInfo* info, JSGraph* jsgraph) : StructuredGraphBuilder(jsgraph->graph(), jsgraph->common()), info_(info), jsgraph_(jsgraph), globals_(0, info->zone()), breakable_(NULL), execution_context_(NULL) { InitializeAstVisitor(info->zone()); } Node* AstGraphBuilder::GetFunctionClosure() { if (!function_closure_.is_set()) { // Parameter -1 is special for the function closure const Operator* op = common()->Parameter(-1); Node* node = NewNode(op, graph()->start()); function_closure_.set(node); } return function_closure_.get(); } Node* AstGraphBuilder::GetFunctionContext() { if (!function_context_.is_set()) { // Parameter (arity + 1) is special for the outer context of the function const Operator* op = common()->Parameter(info()->num_parameters() + 1); Node* node = NewNode(op, graph()->start()); function_context_.set(node); } return function_context_.get(); } bool AstGraphBuilder::CreateGraph() { Scope* scope = info()->scope(); DCHECK(graph() != NULL); // Set up the basic structure of the graph. int parameter_count = info()->num_parameters(); graph()->SetStart(graph()->NewNode(common()->Start(parameter_count))); // Initialize the top-level environment. Environment env(this, scope, graph()->start()); set_environment(&env); // Build node to initialize local function context. Node* closure = GetFunctionClosure(); Node* outer = GetFunctionContext(); Node* inner = BuildLocalFunctionContext(outer, closure); // Push top-level function scope for the function body. ContextScope top_context(this, scope, inner); // Build the arguments object if it is used. BuildArgumentsObject(scope->arguments()); // Emit tracing call if requested to do so. if (FLAG_trace) { NewNode(javascript()->Runtime(Runtime::kTraceEnter, 0)); } // Visit implicit declaration of the function name. if (scope->is_function_scope() && scope->function() != NULL) { VisitVariableDeclaration(scope->function()); } // Visit declarations within the function scope. VisitDeclarations(scope->declarations()); // TODO(mstarzinger): This should do an inlined stack check. Node* node = NewNode(javascript()->Runtime(Runtime::kStackGuard, 0)); PrepareFrameState(node, BailoutId::FunctionEntry()); // Visit statements in the function body. VisitStatements(info()->function()->body()); if (HasStackOverflow()) return false; // Emit tracing call if requested to do so. if (FLAG_trace) { // TODO(mstarzinger): Only traces implicit return. Node* return_value = jsgraph()->UndefinedConstant(); NewNode(javascript()->Runtime(Runtime::kTraceExit, 1), return_value); } // Return 'undefined' in case we can fall off the end. Node* control = NewNode(common()->Return(), jsgraph()->UndefinedConstant()); UpdateControlDependencyToLeaveFunction(control); // Finish the basic structure of the graph. environment()->UpdateControlDependency(exit_control()); graph()->SetEnd(NewNode(common()->End())); return true; } // Left-hand side can only be a property, a global or a variable slot. enum LhsKind { VARIABLE, NAMED_PROPERTY, KEYED_PROPERTY }; // Determine the left-hand side kind of an assignment. static LhsKind DetermineLhsKind(Expression* expr) { Property* property = expr->AsProperty(); DCHECK(expr->IsValidReferenceExpression()); LhsKind lhs_kind = (property == NULL) ? VARIABLE : (property->key()->IsPropertyName()) ? NAMED_PROPERTY : KEYED_PROPERTY; return lhs_kind; } // Helper to find an existing shared function info in the baseline code for the // given function literal. Used to canonicalize SharedFunctionInfo objects. static Handle SearchSharedFunctionInfo( Code* unoptimized_code, FunctionLiteral* expr) { int start_position = expr->start_position(); for (RelocIterator it(unoptimized_code); !it.done(); it.next()) { RelocInfo* rinfo = it.rinfo(); if (rinfo->rmode() != RelocInfo::EMBEDDED_OBJECT) continue; Object* obj = rinfo->target_object(); if (obj->IsSharedFunctionInfo()) { SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj); if (shared->start_position() == start_position) { return Handle(shared); } } } return Handle(); } StructuredGraphBuilder::Environment* AstGraphBuilder::CopyEnvironment( StructuredGraphBuilder::Environment* env) { return new (zone()) Environment(*reinterpret_cast(env)); } AstGraphBuilder::Environment::Environment(AstGraphBuilder* builder, Scope* scope, Node* control_dependency) : StructuredGraphBuilder::Environment(builder, control_dependency), parameters_count_(scope->num_parameters() + 1), locals_count_(scope->num_stack_slots()), parameters_node_(NULL), locals_node_(NULL), stack_node_(NULL) { DCHECK_EQ(scope->num_parameters() + 1, parameters_count()); // Bind the receiver variable. Node* receiver = builder->graph()->NewNode(common()->Parameter(0), builder->graph()->start()); values()->push_back(receiver); // Bind all parameter variables. The parameter indices are shifted by 1 // (receiver is parameter index -1 but environment index 0). for (int i = 0; i < scope->num_parameters(); ++i) { Node* parameter = builder->graph()->NewNode(common()->Parameter(i + 1), builder->graph()->start()); values()->push_back(parameter); } // Bind all local variables to undefined. Node* undefined_constant = builder->jsgraph()->UndefinedConstant(); values()->insert(values()->end(), locals_count(), undefined_constant); } AstGraphBuilder::Environment::Environment(const Environment& copy) : StructuredGraphBuilder::Environment( static_cast(copy)), parameters_count_(copy.parameters_count_), locals_count_(copy.locals_count_), parameters_node_(copy.parameters_node_), locals_node_(copy.locals_node_), stack_node_(copy.stack_node_) {} void AstGraphBuilder::Environment::UpdateStateValues(Node** state_values, int offset, int count) { bool should_update = false; Node** env_values = (count == 0) ? NULL : &values()->at(offset); if (*state_values == NULL || (*state_values)->InputCount() != count) { should_update = true; } else { DCHECK(static_cast(offset + count) <= values()->size()); for (int i = 0; i < count; i++) { if ((*state_values)->InputAt(i) != env_values[i]) { should_update = true; break; } } } if (should_update) { const Operator* op = common()->StateValues(count); (*state_values) = graph()->NewNode(op, count, env_values); } } Node* AstGraphBuilder::Environment::Checkpoint( BailoutId ast_id, OutputFrameStateCombine combine) { UpdateStateValues(¶meters_node_, 0, parameters_count()); UpdateStateValues(&locals_node_, parameters_count(), locals_count()); UpdateStateValues(&stack_node_, parameters_count() + locals_count(), stack_height()); const Operator* op = common()->FrameState(JS_FRAME, ast_id, combine); return graph()->NewNode(op, parameters_node_, locals_node_, stack_node_, GetContext(), builder()->jsgraph()->UndefinedConstant()); } AstGraphBuilder::AstContext::AstContext(AstGraphBuilder* own, Expression::Context kind) : kind_(kind), owner_(own), outer_(own->ast_context()) { owner()->set_ast_context(this); // Push. #ifdef DEBUG original_height_ = environment()->stack_height(); #endif } AstGraphBuilder::AstContext::~AstContext() { owner()->set_ast_context(outer_); // Pop. } AstGraphBuilder::AstEffectContext::~AstEffectContext() { DCHECK(environment()->stack_height() == original_height_); } AstGraphBuilder::AstValueContext::~AstValueContext() { DCHECK(environment()->stack_height() == original_height_ + 1); } AstGraphBuilder::AstTestContext::~AstTestContext() { DCHECK(environment()->stack_height() == original_height_ + 1); } void AstGraphBuilder::AstEffectContext::ProduceValue(Node* value) { // The value is ignored. } void AstGraphBuilder::AstValueContext::ProduceValue(Node* value) { environment()->Push(value); } void AstGraphBuilder::AstTestContext::ProduceValue(Node* value) { environment()->Push(owner()->BuildToBoolean(value)); } Node* AstGraphBuilder::AstEffectContext::ConsumeValue() { return NULL; } Node* AstGraphBuilder::AstValueContext::ConsumeValue() { return environment()->Pop(); } Node* AstGraphBuilder::AstTestContext::ConsumeValue() { return environment()->Pop(); } AstGraphBuilder::BreakableScope* AstGraphBuilder::BreakableScope::FindBreakable( BreakableStatement* target) { BreakableScope* current = this; while (current != NULL && current->target_ != target) { owner_->environment()->Drop(current->drop_extra_); current = current->next_; } DCHECK(current != NULL); // Always found (unless stack is malformed). return current; } void AstGraphBuilder::BreakableScope::BreakTarget(BreakableStatement* stmt) { FindBreakable(stmt)->control_->Break(); } void AstGraphBuilder::BreakableScope::ContinueTarget(BreakableStatement* stmt) { FindBreakable(stmt)->control_->Continue(); } void AstGraphBuilder::VisitForValueOrNull(Expression* expr) { if (expr == NULL) { return environment()->Push(jsgraph()->NullConstant()); } VisitForValue(expr); } void AstGraphBuilder::VisitForValues(ZoneList* exprs) { for (int i = 0; i < exprs->length(); ++i) { VisitForValue(exprs->at(i)); } } void AstGraphBuilder::VisitForValue(Expression* expr) { AstValueContext for_value(this); if (!HasStackOverflow()) { expr->Accept(this); } } void AstGraphBuilder::VisitForEffect(Expression* expr) { AstEffectContext for_effect(this); if (!HasStackOverflow()) { expr->Accept(this); } } void AstGraphBuilder::VisitForTest(Expression* expr) { AstTestContext for_condition(this); if (!HasStackOverflow()) { expr->Accept(this); } } void AstGraphBuilder::VisitVariableDeclaration(VariableDeclaration* decl) { Variable* variable = decl->proxy()->var(); VariableMode mode = decl->mode(); bool hole_init = mode == CONST || mode == CONST_LEGACY || mode == LET; switch (variable->location()) { case Variable::UNALLOCATED: { Handle value = variable->binding_needs_init() ? isolate()->factory()->the_hole_value() : isolate()->factory()->undefined_value(); globals()->Add(variable->name(), zone()); globals()->Add(value, zone()); break; } case Variable::PARAMETER: case Variable::LOCAL: if (hole_init) { Node* value = jsgraph()->TheHoleConstant(); environment()->Bind(variable, value); } break; case Variable::CONTEXT: if (hole_init) { Node* value = jsgraph()->TheHoleConstant(); const Operator* op = javascript()->StoreContext(0, variable->index()); NewNode(op, current_context(), value); } break; case Variable::LOOKUP: UNIMPLEMENTED(); } } void AstGraphBuilder::VisitFunctionDeclaration(FunctionDeclaration* decl) { Variable* variable = decl->proxy()->var(); switch (variable->location()) { case Variable::UNALLOCATED: { Handle function = Compiler::BuildFunctionInfo(decl->fun(), info()->script(), info()); // Check for stack-overflow exception. if (function.is_null()) return SetStackOverflow(); globals()->Add(variable->name(), zone()); globals()->Add(function, zone()); break; } case Variable::PARAMETER: case Variable::LOCAL: { VisitForValue(decl->fun()); Node* value = environment()->Pop(); environment()->Bind(variable, value); break; } case Variable::CONTEXT: { VisitForValue(decl->fun()); Node* value = environment()->Pop(); const Operator* op = javascript()->StoreContext(0, variable->index()); NewNode(op, current_context(), value); break; } case Variable::LOOKUP: UNIMPLEMENTED(); } } void AstGraphBuilder::VisitModuleDeclaration(ModuleDeclaration* decl) { UNREACHABLE(); } void AstGraphBuilder::VisitImportDeclaration(ImportDeclaration* decl) { UNREACHABLE(); } void AstGraphBuilder::VisitExportDeclaration(ExportDeclaration* decl) { UNREACHABLE(); } void AstGraphBuilder::VisitModuleLiteral(ModuleLiteral* modl) { UNREACHABLE(); } void AstGraphBuilder::VisitModuleVariable(ModuleVariable* modl) { UNREACHABLE(); } void AstGraphBuilder::VisitModulePath(ModulePath* modl) { UNREACHABLE(); } void AstGraphBuilder::VisitModuleUrl(ModuleUrl* modl) { UNREACHABLE(); } void AstGraphBuilder::VisitBlock(Block* stmt) { BlockBuilder block(this); BreakableScope scope(this, stmt, &block, 0); if (stmt->labels() != NULL) block.BeginBlock(); if (stmt->scope() == NULL) { // Visit statements in the same scope, no declarations. VisitStatements(stmt->statements()); } else { const Operator* op = javascript()->CreateBlockContext(); Node* scope_info = jsgraph()->Constant(stmt->scope()->GetScopeInfo()); Node* context = NewNode(op, scope_info, GetFunctionClosure()); ContextScope scope(this, stmt->scope(), context); // Visit declarations and statements in a block scope. VisitDeclarations(stmt->scope()->declarations()); VisitStatements(stmt->statements()); } if (stmt->labels() != NULL) block.EndBlock(); } void AstGraphBuilder::VisitModuleStatement(ModuleStatement* stmt) { UNREACHABLE(); } void AstGraphBuilder::VisitExpressionStatement(ExpressionStatement* stmt) { VisitForEffect(stmt->expression()); } void AstGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) { // Do nothing. } void AstGraphBuilder::VisitIfStatement(IfStatement* stmt) { IfBuilder compare_if(this); VisitForTest(stmt->condition()); Node* condition = environment()->Pop(); compare_if.If(condition); compare_if.Then(); Visit(stmt->then_statement()); compare_if.Else(); Visit(stmt->else_statement()); compare_if.End(); } void AstGraphBuilder::VisitContinueStatement(ContinueStatement* stmt) { StructuredGraphBuilder::Environment* env = environment()->CopyAsUnreachable(); breakable()->ContinueTarget(stmt->target()); set_environment(env); } void AstGraphBuilder::VisitBreakStatement(BreakStatement* stmt) { StructuredGraphBuilder::Environment* env = environment()->CopyAsUnreachable(); breakable()->BreakTarget(stmt->target()); set_environment(env); } void AstGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) { VisitForValue(stmt->expression()); Node* result = environment()->Pop(); Node* control = NewNode(common()->Return(), result); UpdateControlDependencyToLeaveFunction(control); } void AstGraphBuilder::VisitWithStatement(WithStatement* stmt) { VisitForValue(stmt->expression()); Node* value = environment()->Pop(); const Operator* op = javascript()->CreateWithContext(); Node* context = NewNode(op, value, GetFunctionClosure()); ContextScope scope(this, stmt->scope(), context); Visit(stmt->statement()); } void AstGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) { ZoneList* clauses = stmt->cases(); SwitchBuilder compare_switch(this, clauses->length()); BreakableScope scope(this, stmt, &compare_switch, 0); compare_switch.BeginSwitch(); int default_index = -1; // Keep the switch value on the stack until a case matches. VisitForValue(stmt->tag()); Node* tag = environment()->Top(); // Iterate over all cases and create nodes for label comparison. for (int i = 0; i < clauses->length(); i++) { CaseClause* clause = clauses->at(i); // The default is not a test, remember index. if (clause->is_default()) { default_index = i; continue; } // Create nodes to perform label comparison as if via '==='. The switch // value is still on the operand stack while the label is evaluated. VisitForValue(clause->label()); Node* label = environment()->Pop(); const Operator* op = javascript()->StrictEqual(); Node* condition = NewNode(op, tag, label); compare_switch.BeginLabel(i, condition); // Discard the switch value at label match. environment()->Pop(); compare_switch.EndLabel(); } // Discard the switch value and mark the default case. environment()->Pop(); if (default_index >= 0) { compare_switch.DefaultAt(default_index); } // Iterate over all cases and create nodes for case bodies. for (int i = 0; i < clauses->length(); i++) { CaseClause* clause = clauses->at(i); compare_switch.BeginCase(i); VisitStatements(clause->statements()); compare_switch.EndCase(); } compare_switch.EndSwitch(); } void AstGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) { LoopBuilder while_loop(this); while_loop.BeginLoop(); VisitIterationBody(stmt, &while_loop, 0); while_loop.EndBody(); VisitForTest(stmt->cond()); Node* condition = environment()->Pop(); while_loop.BreakUnless(condition); while_loop.EndLoop(); } void AstGraphBuilder::VisitWhileStatement(WhileStatement* stmt) { LoopBuilder while_loop(this); while_loop.BeginLoop(); VisitForTest(stmt->cond()); Node* condition = environment()->Pop(); while_loop.BreakUnless(condition); VisitIterationBody(stmt, &while_loop, 0); while_loop.EndBody(); while_loop.EndLoop(); } void AstGraphBuilder::VisitForStatement(ForStatement* stmt) { LoopBuilder for_loop(this); VisitIfNotNull(stmt->init()); for_loop.BeginLoop(); if (stmt->cond() != NULL) { VisitForTest(stmt->cond()); Node* condition = environment()->Pop(); for_loop.BreakUnless(condition); } VisitIterationBody(stmt, &for_loop, 0); for_loop.EndBody(); VisitIfNotNull(stmt->next()); for_loop.EndLoop(); } // TODO(dcarney): this is a big function. Try to clean up some. void AstGraphBuilder::VisitForInStatement(ForInStatement* stmt) { VisitForValue(stmt->subject()); Node* obj = environment()->Pop(); // Check for undefined or null before entering loop. IfBuilder is_undefined(this); Node* is_undefined_cond = NewNode(javascript()->StrictEqual(), obj, jsgraph()->UndefinedConstant()); is_undefined.If(is_undefined_cond); is_undefined.Then(); is_undefined.Else(); { IfBuilder is_null(this); Node* is_null_cond = NewNode(javascript()->StrictEqual(), obj, jsgraph()->NullConstant()); is_null.If(is_null_cond); is_null.Then(); is_null.Else(); // Convert object to jsobject. // PrepareForBailoutForId(stmt->PrepareId(), TOS_REG); obj = NewNode(javascript()->ToObject(), obj); environment()->Push(obj); // TODO(dcarney): should do a fast enum cache check here to skip runtime. environment()->Push(obj); Node* cache_type = ProcessArguments( javascript()->Runtime(Runtime::kGetPropertyNamesFast, 1), 1); // TODO(dcarney): these next runtime calls should be removed in favour of // a few simplified instructions. environment()->Push(obj); environment()->Push(cache_type); Node* cache_pair = ProcessArguments(javascript()->Runtime(Runtime::kForInInit, 2), 2); // cache_type may have been replaced. Node* cache_array = NewNode(common()->Projection(0), cache_pair); cache_type = NewNode(common()->Projection(1), cache_pair); environment()->Push(cache_type); environment()->Push(cache_array); Node* cache_length = ProcessArguments( javascript()->Runtime(Runtime::kForInCacheArrayLength, 2), 2); { // TODO(dcarney): this check is actually supposed to be for the // empty enum case only. IfBuilder have_no_properties(this); Node* empty_array_cond = NewNode(javascript()->StrictEqual(), cache_length, jsgraph()->ZeroConstant()); have_no_properties.If(empty_array_cond); have_no_properties.Then(); // Pop obj and skip loop. environment()->Pop(); have_no_properties.Else(); { // Construct the rest of the environment. environment()->Push(cache_type); environment()->Push(cache_array); environment()->Push(cache_length); environment()->Push(jsgraph()->ZeroConstant()); // PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS); LoopBuilder for_loop(this); for_loop.BeginLoop(); // Check loop termination condition. Node* index = environment()->Peek(0); Node* exit_cond = NewNode(javascript()->LessThan(), index, cache_length); // TODO(jarin): provide real bailout id. PrepareFrameState(exit_cond, BailoutId::None()); for_loop.BreakUnless(exit_cond); // TODO(dcarney): this runtime call should be a handful of // simplified instructions that // basically produce // value = array[index] environment()->Push(obj); environment()->Push(cache_array); environment()->Push(cache_type); environment()->Push(index); Node* pair = ProcessArguments(javascript()->Runtime(Runtime::kForInNext, 4), 4); Node* value = NewNode(common()->Projection(0), pair); Node* should_filter = NewNode(common()->Projection(1), pair); environment()->Push(value); { // Test if FILTER_KEY needs to be called. IfBuilder test_should_filter(this); Node* should_filter_cond = NewNode(javascript()->StrictEqual(), should_filter, jsgraph()->TrueConstant()); test_should_filter.If(should_filter_cond); test_should_filter.Then(); value = environment()->Pop(); Node* builtins = BuildLoadBuiltinsObject(); Node* function = BuildLoadObjectField( builtins, JSBuiltinsObject::OffsetOfFunctionWithId(Builtins::FILTER_KEY)); // Callee. environment()->Push(function); // Receiver. environment()->Push(obj); // Args. environment()->Push(value); // result is either the string key or Smi(0) indicating the property // is gone. Node* res = ProcessArguments( javascript()->Call(3, NO_CALL_FUNCTION_FLAGS), 3); // TODO(jarin): provide real bailout id. PrepareFrameState(res, BailoutId::None()); Node* property_missing = NewNode(javascript()->StrictEqual(), res, jsgraph()->ZeroConstant()); { IfBuilder is_property_missing(this); is_property_missing.If(property_missing); is_property_missing.Then(); // Inc counter and continue. Node* index_inc = NewNode(javascript()->Add(), index, jsgraph()->OneConstant()); // TODO(jarin): provide real bailout id. PrepareFrameState(index_inc, BailoutId::None()); environment()->Poke(0, index_inc); for_loop.Continue(); is_property_missing.Else(); is_property_missing.End(); } // Replace 'value' in environment. environment()->Push(res); test_should_filter.Else(); test_should_filter.End(); } value = environment()->Pop(); // Bind value and do loop body. VisitForInAssignment(stmt->each(), value); VisitIterationBody(stmt, &for_loop, 5); for_loop.EndBody(); // Inc counter and continue. Node* index_inc = NewNode(javascript()->Add(), index, jsgraph()->OneConstant()); // TODO(jarin): provide real bailout id. PrepareFrameState(index_inc, BailoutId::None()); environment()->Poke(0, index_inc); for_loop.EndLoop(); environment()->Drop(5); // PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS); } have_no_properties.End(); } is_null.End(); } is_undefined.End(); } void AstGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) { VisitForValue(stmt->subject()); environment()->Pop(); // TODO(turbofan): create and use loop builder. } void AstGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) { UNREACHABLE(); } void AstGraphBuilder::VisitTryFinallyStatement(TryFinallyStatement* stmt) { UNREACHABLE(); } void AstGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) { // TODO(turbofan): Do we really need a separate reloc-info for this? Node* node = NewNode(javascript()->Runtime(Runtime::kDebugBreak, 0)); PrepareFrameState(node, stmt->DebugBreakId()); } void AstGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) { Node* context = current_context(); // Build a new shared function info if we cannot find one in the baseline // code. We also have a stack overflow if the recursive compilation did. Handle shared_info = SearchSharedFunctionInfo(info()->shared_info()->code(), expr); if (shared_info.is_null()) { shared_info = Compiler::BuildFunctionInfo(expr, info()->script(), info()); CHECK(!shared_info.is_null()); // TODO(mstarzinger): Set stack overflow? } // Create node to instantiate a new closure. Node* info = jsgraph()->Constant(shared_info); Node* pretenure = expr->pretenure() ? jsgraph()->TrueConstant() : jsgraph()->FalseConstant(); const Operator* op = javascript()->Runtime(Runtime::kNewClosure, 3); Node* value = NewNode(op, context, info, pretenure); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitClassLiteral(ClassLiteral* expr) { // TODO(arv): Implement. UNREACHABLE(); } void AstGraphBuilder::VisitNativeFunctionLiteral(NativeFunctionLiteral* expr) { UNREACHABLE(); } void AstGraphBuilder::VisitConditional(Conditional* expr) { IfBuilder compare_if(this); VisitForTest(expr->condition()); Node* condition = environment()->Pop(); compare_if.If(condition); compare_if.Then(); Visit(expr->then_expression()); compare_if.Else(); Visit(expr->else_expression()); compare_if.End(); ast_context()->ReplaceValue(); } void AstGraphBuilder::VisitVariableProxy(VariableProxy* expr) { Node* value = BuildVariableLoad(expr->var(), expr->id()); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitLiteral(Literal* expr) { Node* value = jsgraph()->Constant(expr->value()); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) { Node* closure = GetFunctionClosure(); // Create node to materialize a regular expression literal. Node* literals_array = BuildLoadObjectField(closure, JSFunction::kLiteralsOffset); Node* literal_index = jsgraph()->Constant(expr->literal_index()); Node* pattern = jsgraph()->Constant(expr->pattern()); Node* flags = jsgraph()->Constant(expr->flags()); const Operator* op = javascript()->Runtime(Runtime::kMaterializeRegExpLiteral, 4); Node* literal = NewNode(op, literals_array, literal_index, pattern, flags); ast_context()->ProduceValue(literal); } void AstGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) { Node* closure = GetFunctionClosure(); // Create node to deep-copy the literal boilerplate. expr->BuildConstantProperties(isolate()); Node* literals_array = BuildLoadObjectField(closure, JSFunction::kLiteralsOffset); Node* literal_index = jsgraph()->Constant(expr->literal_index()); Node* constants = jsgraph()->Constant(expr->constant_properties()); Node* flags = jsgraph()->Constant(expr->ComputeFlags()); const Operator* op = javascript()->Runtime(Runtime::kCreateObjectLiteral, 4); Node* literal = NewNode(op, literals_array, literal_index, constants, flags); // The object is expected on the operand stack during computation of the // property values and is the value of the entire expression. environment()->Push(literal); // Mark all computed expressions that are bound to a key that is shadowed by // a later occurrence of the same key. For the marked expressions, no store // code is emitted. expr->CalculateEmitStore(zone()); // Create nodes to store computed values into the literal. AccessorTable accessor_table(zone()); for (int i = 0; i < expr->properties()->length(); i++) { ObjectLiteral::Property* property = expr->properties()->at(i); if (property->IsCompileTimeValue()) continue; Literal* key = property->key(); switch (property->kind()) { case ObjectLiteral::Property::CONSTANT: UNREACHABLE(); case ObjectLiteral::Property::MATERIALIZED_LITERAL: DCHECK(!CompileTimeValue::IsCompileTimeValue(property->value())); // Fall through. case ObjectLiteral::Property::COMPUTED: { // It is safe to use [[Put]] here because the boilerplate already // contains computed properties with an uninitialized value. if (key->value()->IsInternalizedString()) { if (property->emit_store()) { VisitForValue(property->value()); Node* value = environment()->Pop(); Unique name = MakeUnique(key->AsPropertyName()); Node* store = NewNode(javascript()->StoreNamed(strict_mode(), name), literal, value); PrepareFrameState(store, key->id()); } else { VisitForEffect(property->value()); } break; } environment()->Push(literal); // Duplicate receiver. VisitForValue(property->key()); VisitForValue(property->value()); Node* value = environment()->Pop(); Node* key = environment()->Pop(); Node* receiver = environment()->Pop(); if (property->emit_store()) { Node* strict = jsgraph()->Constant(SLOPPY); const Operator* op = javascript()->Runtime(Runtime::kSetProperty, 4); NewNode(op, receiver, key, value, strict); } break; } case ObjectLiteral::Property::PROTOTYPE: { environment()->Push(literal); // Duplicate receiver. VisitForValue(property->value()); Node* value = environment()->Pop(); Node* receiver = environment()->Pop(); if (property->emit_store()) { const Operator* op = javascript()->Runtime(Runtime::kSetPrototype, 2); NewNode(op, receiver, value); } break; } case ObjectLiteral::Property::GETTER: accessor_table.lookup(key)->second->getter = property->value(); break; case ObjectLiteral::Property::SETTER: accessor_table.lookup(key)->second->setter = property->value(); break; } } // Create nodes to define accessors, using only a single call to the runtime // for each pair of corresponding getters and setters. for (AccessorTable::Iterator it = accessor_table.begin(); it != accessor_table.end(); ++it) { VisitForValue(it->first); VisitForValueOrNull(it->second->getter); VisitForValueOrNull(it->second->setter); Node* setter = environment()->Pop(); Node* getter = environment()->Pop(); Node* name = environment()->Pop(); Node* attr = jsgraph()->Constant(NONE); const Operator* op = javascript()->Runtime(Runtime::kDefineAccessorPropertyUnchecked, 5); Node* call = NewNode(op, literal, name, getter, setter, attr); PrepareFrameState(call, it->first->id()); } // Transform literals that contain functions to fast properties. if (expr->has_function()) { const Operator* op = javascript()->Runtime(Runtime::kToFastProperties, 1); NewNode(op, literal); } ast_context()->ProduceValue(environment()->Pop()); } void AstGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { Node* closure = GetFunctionClosure(); // Create node to deep-copy the literal boilerplate. expr->BuildConstantElements(isolate()); Node* literals_array = BuildLoadObjectField(closure, JSFunction::kLiteralsOffset); Node* literal_index = jsgraph()->Constant(expr->literal_index()); Node* constants = jsgraph()->Constant(expr->constant_elements()); Node* flags = jsgraph()->Constant(expr->ComputeFlags()); const Operator* op = javascript()->Runtime(Runtime::kCreateArrayLiteral, 4); Node* literal = NewNode(op, literals_array, literal_index, constants, flags); // The array and the literal index are both expected on the operand stack // during computation of the element values. environment()->Push(literal); environment()->Push(literal_index); // Create nodes to evaluate all the non-constant subexpressions and to store // them into the newly cloned array. for (int i = 0; i < expr->values()->length(); i++) { Expression* subexpr = expr->values()->at(i); if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue; VisitForValue(subexpr); Node* value = environment()->Pop(); Node* index = jsgraph()->Constant(i); Node* store = NewNode(javascript()->StoreProperty(strict_mode()), literal, index, value); PrepareFrameState(store, expr->GetIdForElement(i)); } environment()->Pop(); // Array literal index. ast_context()->ProduceValue(environment()->Pop()); } void AstGraphBuilder::VisitForInAssignment(Expression* expr, Node* value) { DCHECK(expr->IsValidReferenceExpression()); // Left-hand side can only be a property, a global or a variable slot. Property* property = expr->AsProperty(); LhsKind assign_type = DetermineLhsKind(expr); // Evaluate LHS expression and store the value. switch (assign_type) { case VARIABLE: { Variable* var = expr->AsVariableProxy()->var(); // TODO(jarin) Fill in the correct bailout id. BuildVariableAssignment(var, value, Token::ASSIGN, BailoutId::None()); break; } case NAMED_PROPERTY: { environment()->Push(value); VisitForValue(property->obj()); Node* object = environment()->Pop(); value = environment()->Pop(); Unique name = MakeUnique(property->key()->AsLiteral()->AsPropertyName()); Node* store = NewNode(javascript()->StoreNamed(strict_mode(), name), object, value); // TODO(jarin) Fill in the correct bailout id. PrepareFrameState(store, BailoutId::None()); break; } case KEYED_PROPERTY: { environment()->Push(value); VisitForValue(property->obj()); VisitForValue(property->key()); Node* key = environment()->Pop(); Node* object = environment()->Pop(); value = environment()->Pop(); Node* store = NewNode(javascript()->StoreProperty(strict_mode()), object, key, value); // TODO(jarin) Fill in the correct bailout id. PrepareFrameState(store, BailoutId::None()); break; } } } void AstGraphBuilder::VisitAssignment(Assignment* expr) { DCHECK(expr->target()->IsValidReferenceExpression()); // Left-hand side can only be a property, a global or a variable slot. Property* property = expr->target()->AsProperty(); LhsKind assign_type = DetermineLhsKind(expr->target()); // Evaluate LHS expression. switch (assign_type) { case VARIABLE: // Nothing to do here. break; case NAMED_PROPERTY: VisitForValue(property->obj()); break; case KEYED_PROPERTY: { VisitForValue(property->obj()); VisitForValue(property->key()); break; } } // Evaluate the value and potentially handle compound assignments by loading // the left-hand side value and performing a binary operation. if (expr->is_compound()) { Node* old_value = NULL; switch (assign_type) { case VARIABLE: { Variable* variable = expr->target()->AsVariableProxy()->var(); old_value = BuildVariableLoad(variable, expr->target()->id()); break; } case NAMED_PROPERTY: { Node* object = environment()->Top(); Unique name = MakeUnique(property->key()->AsLiteral()->AsPropertyName()); old_value = NewNode(javascript()->LoadNamed(name), object); PrepareFrameState(old_value, property->LoadId(), kPushOutput); break; } case KEYED_PROPERTY: { Node* key = environment()->Top(); Node* object = environment()->Peek(1); old_value = NewNode(javascript()->LoadProperty(), object, key); PrepareFrameState(old_value, property->LoadId(), kPushOutput); break; } } environment()->Push(old_value); VisitForValue(expr->value()); Node* right = environment()->Pop(); Node* left = environment()->Pop(); Node* value = BuildBinaryOp(left, right, expr->binary_op()); PrepareFrameState(value, expr->binary_operation()->id(), kPushOutput); environment()->Push(value); } else { VisitForValue(expr->value()); } // Store the value. Node* value = environment()->Pop(); switch (assign_type) { case VARIABLE: { Variable* variable = expr->target()->AsVariableProxy()->var(); BuildVariableAssignment(variable, value, expr->op(), expr->AssignmentId()); break; } case NAMED_PROPERTY: { Node* object = environment()->Pop(); Unique name = MakeUnique(property->key()->AsLiteral()->AsPropertyName()); Node* store = NewNode(javascript()->StoreNamed(strict_mode(), name), object, value); PrepareFrameState(store, expr->AssignmentId()); break; } case KEYED_PROPERTY: { Node* key = environment()->Pop(); Node* object = environment()->Pop(); Node* store = NewNode(javascript()->StoreProperty(strict_mode()), object, key, value); PrepareFrameState(store, expr->AssignmentId()); break; } } ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitYield(Yield* expr) { VisitForValue(expr->generator_object()); VisitForValue(expr->expression()); environment()->Pop(); environment()->Pop(); // TODO(turbofan): VisitYield ast_context()->ProduceValue(jsgraph()->UndefinedConstant()); } void AstGraphBuilder::VisitThrow(Throw* expr) { VisitForValue(expr->exception()); Node* exception = environment()->Pop(); const Operator* op = javascript()->Runtime(Runtime::kThrow, 1); Node* value = NewNode(op, exception); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitProperty(Property* expr) { Node* value; if (expr->key()->IsPropertyName()) { VisitForValue(expr->obj()); Node* object = environment()->Pop(); Unique name = MakeUnique(expr->key()->AsLiteral()->AsPropertyName()); value = NewNode(javascript()->LoadNamed(name), object); } else { VisitForValue(expr->obj()); VisitForValue(expr->key()); Node* key = environment()->Pop(); Node* object = environment()->Pop(); value = NewNode(javascript()->LoadProperty(), object, key); } PrepareFrameState(value, expr->id(), ast_context()->GetStateCombine()); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitCall(Call* expr) { Expression* callee = expr->expression(); Call::CallType call_type = expr->GetCallType(isolate()); // Prepare the callee and the receiver to the function call. This depends on // the semantics of the underlying call type. CallFunctionFlags flags = NO_CALL_FUNCTION_FLAGS; Node* receiver_value = NULL; Node* callee_value = NULL; bool possibly_eval = false; switch (call_type) { case Call::GLOBAL_CALL: { Variable* variable = callee->AsVariableProxy()->var(); callee_value = BuildVariableLoad(variable, expr->expression()->id()); receiver_value = jsgraph()->UndefinedConstant(); break; } case Call::LOOKUP_SLOT_CALL: { Variable* variable = callee->AsVariableProxy()->var(); DCHECK(variable->location() == Variable::LOOKUP); Node* name = jsgraph()->Constant(variable->name()); const Operator* op = javascript()->Runtime(Runtime::kLoadLookupSlot, 2); Node* pair = NewNode(op, current_context(), name); callee_value = NewNode(common()->Projection(0), pair); receiver_value = NewNode(common()->Projection(1), pair); break; } case Call::PROPERTY_CALL: { Property* property = callee->AsProperty(); VisitForValue(property->obj()); Node* object = environment()->Top(); if (property->key()->IsPropertyName()) { Unique name = MakeUnique(property->key()->AsLiteral()->AsPropertyName()); callee_value = NewNode(javascript()->LoadNamed(name), object); } else { VisitForValue(property->key()); Node* key = environment()->Pop(); callee_value = NewNode(javascript()->LoadProperty(), object, key); } PrepareFrameState(callee_value, property->LoadId(), kPushOutput); receiver_value = environment()->Pop(); // Note that a PROPERTY_CALL requires the receiver to be wrapped into an // object for sloppy callees. This could also be modeled explicitly here, // thereby obsoleting the need for a flag to the call operator. flags = CALL_AS_METHOD; break; } case Call::POSSIBLY_EVAL_CALL: possibly_eval = true; // Fall through. case Call::OTHER_CALL: VisitForValue(callee); callee_value = environment()->Pop(); receiver_value = jsgraph()->UndefinedConstant(); break; } // The callee and the receiver both have to be pushed onto the operand stack // before arguments are being evaluated. environment()->Push(callee_value); environment()->Push(receiver_value); // Evaluate all arguments to the function call, ZoneList* args = expr->arguments(); VisitForValues(args); // Resolve callee and receiver for a potential direct eval call. This block // will mutate the callee and receiver values pushed onto the environment. if (possibly_eval && args->length() > 0) { int arg_count = args->length(); // Extract callee and source string from the environment. Node* callee = environment()->Peek(arg_count + 1); Node* source = environment()->Peek(arg_count - 1); // Create node to ask for help resolving potential eval call. This will // provide a fully resolved callee and the corresponding receiver. Node* receiver = environment()->Lookup(info()->scope()->receiver()); Node* strict = jsgraph()->Constant(strict_mode()); Node* position = jsgraph()->Constant(info()->scope()->start_position()); const Operator* op = javascript()->Runtime(Runtime::kResolvePossiblyDirectEval, 5); Node* pair = NewNode(op, callee, source, receiver, strict, position); Node* new_callee = NewNode(common()->Projection(0), pair); Node* new_receiver = NewNode(common()->Projection(1), pair); // Patch callee and receiver on the environment. environment()->Poke(arg_count + 1, new_callee); environment()->Poke(arg_count + 0, new_receiver); } // Create node to perform the function call. const Operator* call = javascript()->Call(args->length() + 2, flags); Node* value = ProcessArguments(call, args->length() + 2); PrepareFrameState(value, expr->id(), ast_context()->GetStateCombine()); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitCallNew(CallNew* expr) { VisitForValue(expr->expression()); // Evaluate all arguments to the construct call. ZoneList* args = expr->arguments(); VisitForValues(args); // Create node to perform the construct call. const Operator* call = javascript()->CallNew(args->length() + 1); Node* value = ProcessArguments(call, args->length() + 1); PrepareFrameState(value, expr->id(), ast_context()->GetStateCombine()); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitCallJSRuntime(CallRuntime* expr) { Handle name = expr->name(); // The callee and the receiver both have to be pushed onto the operand stack // before arguments are being evaluated. CallFunctionFlags flags = NO_CALL_FUNCTION_FLAGS; Node* receiver_value = BuildLoadBuiltinsObject(); Unique unique = MakeUnique(name); Node* callee_value = NewNode(javascript()->LoadNamed(unique), receiver_value); // TODO(jarin): Find/create a bailout id to deoptimize to (crankshaft // refuses to optimize functions with jsruntime calls). PrepareFrameState(callee_value, BailoutId::None(), kPushOutput); environment()->Push(callee_value); environment()->Push(receiver_value); // Evaluate all arguments to the JS runtime call. ZoneList* args = expr->arguments(); VisitForValues(args); // Create node to perform the JS runtime call. const Operator* call = javascript()->Call(args->length() + 2, flags); Node* value = ProcessArguments(call, args->length() + 2); PrepareFrameState(value, expr->id(), ast_context()->GetStateCombine()); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitCallRuntime(CallRuntime* expr) { const Runtime::Function* function = expr->function(); // Handle calls to runtime functions implemented in JavaScript separately as // the call follows JavaScript ABI and the callee is statically unknown. if (expr->is_jsruntime()) { DCHECK(function == NULL && expr->name()->length() > 0); return VisitCallJSRuntime(expr); } // Evaluate all arguments to the runtime call. ZoneList* args = expr->arguments(); VisitForValues(args); // Create node to perform the runtime call. Runtime::FunctionId functionId = function->function_id; const Operator* call = javascript()->Runtime(functionId, args->length()); Node* value = ProcessArguments(call, args->length()); PrepareFrameState(value, expr->id(), ast_context()->GetStateCombine()); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) { switch (expr->op()) { case Token::DELETE: return VisitDelete(expr); case Token::VOID: return VisitVoid(expr); case Token::TYPEOF: return VisitTypeof(expr); case Token::NOT: return VisitNot(expr); default: UNREACHABLE(); } } void AstGraphBuilder::VisitCountOperation(CountOperation* expr) { DCHECK(expr->expression()->IsValidReferenceExpression()); // Left-hand side can only be a property, a global or a variable slot. Property* property = expr->expression()->AsProperty(); LhsKind assign_type = DetermineLhsKind(expr->expression()); // Reserve space for result of postfix operation. bool is_postfix = expr->is_postfix() && !ast_context()->IsEffect(); if (is_postfix) environment()->Push(jsgraph()->UndefinedConstant()); // Evaluate LHS expression and get old value. Node* old_value = NULL; int stack_depth = -1; switch (assign_type) { case VARIABLE: { Variable* variable = expr->expression()->AsVariableProxy()->var(); old_value = BuildVariableLoad(variable, expr->expression()->id()); stack_depth = 0; break; } case NAMED_PROPERTY: { VisitForValue(property->obj()); Node* object = environment()->Top(); Unique name = MakeUnique(property->key()->AsLiteral()->AsPropertyName()); old_value = NewNode(javascript()->LoadNamed(name), object); PrepareFrameState(old_value, property->LoadId(), kPushOutput); stack_depth = 1; break; } case KEYED_PROPERTY: { VisitForValue(property->obj()); VisitForValue(property->key()); Node* key = environment()->Top(); Node* object = environment()->Peek(1); old_value = NewNode(javascript()->LoadProperty(), object, key); PrepareFrameState(old_value, property->LoadId(), kPushOutput); stack_depth = 2; break; } } // Convert old value into a number. old_value = NewNode(javascript()->ToNumber(), old_value); // Save result for postfix expressions at correct stack depth. if (is_postfix) environment()->Poke(stack_depth, old_value); // Create node to perform +1/-1 operation. Node* value = BuildBinaryOp(old_value, jsgraph()->OneConstant(), expr->binary_op()); // TODO(jarin) Insert proper bailout id here (will need to change // full code generator). PrepareFrameState(value, BailoutId::None()); // Store the value. switch (assign_type) { case VARIABLE: { Variable* variable = expr->expression()->AsVariableProxy()->var(); environment()->Push(value); BuildVariableAssignment(variable, value, expr->op(), expr->AssignmentId()); environment()->Pop(); break; } case NAMED_PROPERTY: { Node* object = environment()->Pop(); Unique name = MakeUnique(property->key()->AsLiteral()->AsPropertyName()); Node* store = NewNode(javascript()->StoreNamed(strict_mode(), name), object, value); environment()->Push(value); PrepareFrameState(store, expr->AssignmentId()); environment()->Pop(); break; } case KEYED_PROPERTY: { Node* key = environment()->Pop(); Node* object = environment()->Pop(); Node* store = NewNode(javascript()->StoreProperty(strict_mode()), object, key, value); environment()->Push(value); PrepareFrameState(store, expr->AssignmentId()); environment()->Pop(); break; } } // Restore old value for postfix expressions. if (is_postfix) value = environment()->Pop(); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) { switch (expr->op()) { case Token::COMMA: return VisitComma(expr); case Token::OR: case Token::AND: return VisitLogicalExpression(expr); default: { VisitForValue(expr->left()); VisitForValue(expr->right()); Node* right = environment()->Pop(); Node* left = environment()->Pop(); Node* value = BuildBinaryOp(left, right, expr->op()); PrepareFrameState(value, expr->id(), ast_context()->GetStateCombine()); ast_context()->ProduceValue(value); } } } void AstGraphBuilder::VisitCompareOperation(CompareOperation* expr) { const Operator* op; switch (expr->op()) { case Token::EQ: op = javascript()->Equal(); break; case Token::NE: op = javascript()->NotEqual(); break; case Token::EQ_STRICT: op = javascript()->StrictEqual(); break; case Token::NE_STRICT: op = javascript()->StrictNotEqual(); break; case Token::LT: op = javascript()->LessThan(); break; case Token::GT: op = javascript()->GreaterThan(); break; case Token::LTE: op = javascript()->LessThanOrEqual(); break; case Token::GTE: op = javascript()->GreaterThanOrEqual(); break; case Token::INSTANCEOF: op = javascript()->InstanceOf(); break; case Token::IN: op = javascript()->HasProperty(); break; default: op = NULL; UNREACHABLE(); } VisitForValue(expr->left()); VisitForValue(expr->right()); Node* right = environment()->Pop(); Node* left = environment()->Pop(); Node* value = NewNode(op, left, right); PrepareFrameState(value, expr->id(), ast_context()->GetStateCombine()); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitThisFunction(ThisFunction* expr) { Node* value = GetFunctionClosure(); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitSuperReference(SuperReference* expr) { UNREACHABLE(); } void AstGraphBuilder::VisitCaseClause(CaseClause* expr) { UNREACHABLE(); } void AstGraphBuilder::VisitDeclarations(ZoneList* declarations) { DCHECK(globals()->is_empty()); AstVisitor::VisitDeclarations(declarations); if (globals()->is_empty()) return; Handle data = isolate()->factory()->NewFixedArray(globals()->length(), TENURED); for (int i = 0; i < globals()->length(); ++i) data->set(i, *globals()->at(i)); int encoded_flags = DeclareGlobalsEvalFlag::encode(info()->is_eval()) | DeclareGlobalsNativeFlag::encode(info()->is_native()) | DeclareGlobalsStrictMode::encode(strict_mode()); Node* flags = jsgraph()->Constant(encoded_flags); Node* pairs = jsgraph()->Constant(data); const Operator* op = javascript()->Runtime(Runtime::kDeclareGlobals, 3); NewNode(op, current_context(), pairs, flags); globals()->Rewind(0); } void AstGraphBuilder::VisitIfNotNull(Statement* stmt) { if (stmt == NULL) return; Visit(stmt); } void AstGraphBuilder::VisitIterationBody(IterationStatement* stmt, LoopBuilder* loop, int drop_extra) { BreakableScope scope(this, stmt, loop, drop_extra); Visit(stmt->body()); } void AstGraphBuilder::VisitDelete(UnaryOperation* expr) { Node* value; if (expr->expression()->IsVariableProxy()) { // Delete of an unqualified identifier is only allowed in classic mode but // deleting ""this"" is allowed in all language modes. Variable* variable = expr->expression()->AsVariableProxy()->var(); DCHECK(strict_mode() == SLOPPY || variable->is_this()); value = BuildVariableDelete(variable); } else if (expr->expression()->IsProperty()) { Property* property = expr->expression()->AsProperty(); VisitForValue(property->obj()); VisitForValue(property->key()); Node* key = environment()->Pop(); Node* object = environment()->Pop(); value = NewNode(javascript()->DeleteProperty(strict_mode()), object, key); } else { VisitForEffect(expr->expression()); value = jsgraph()->TrueConstant(); } ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitVoid(UnaryOperation* expr) { VisitForEffect(expr->expression()); Node* value = jsgraph()->UndefinedConstant(); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitTypeof(UnaryOperation* expr) { Node* operand; if (expr->expression()->IsVariableProxy()) { // Typeof does not throw a reference error on global variables, hence we // perform a non-contextual load in case the operand is a variable proxy. Variable* variable = expr->expression()->AsVariableProxy()->var(); operand = BuildVariableLoad(variable, expr->expression()->id(), NOT_CONTEXTUAL); } else { VisitForValue(expr->expression()); operand = environment()->Pop(); } Node* value = NewNode(javascript()->TypeOf(), operand); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitNot(UnaryOperation* expr) { VisitForValue(expr->expression()); Node* operand = environment()->Pop(); // TODO(mstarzinger): Possible optimization when we are in effect context. Node* value = NewNode(javascript()->UnaryNot(), operand); ast_context()->ProduceValue(value); } void AstGraphBuilder::VisitComma(BinaryOperation* expr) { VisitForEffect(expr->left()); Visit(expr->right()); ast_context()->ReplaceValue(); } void AstGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) { bool is_logical_and = expr->op() == Token::AND; IfBuilder compare_if(this); VisitForValue(expr->left()); Node* condition = environment()->Top(); compare_if.If(BuildToBoolean(condition)); compare_if.Then(); if (is_logical_and) { environment()->Pop(); Visit(expr->right()); } else if (ast_context()->IsEffect()) { environment()->Pop(); } compare_if.Else(); if (!is_logical_and) { environment()->Pop(); Visit(expr->right()); } else if (ast_context()->IsEffect()) { environment()->Pop(); } compare_if.End(); ast_context()->ReplaceValue(); } Node* AstGraphBuilder::ProcessArguments(const Operator* op, int arity) { DCHECK(environment()->stack_height() >= arity); Node** all = info()->zone()->NewArray(arity); for (int i = arity - 1; i >= 0; --i) { all[i] = environment()->Pop(); } Node* value = NewNode(op, arity, all); return value; } Node* AstGraphBuilder::BuildLocalFunctionContext(Node* context, Node* closure) { int heap_slots = info()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS; if (heap_slots <= 0) return context; set_current_context(context); // Allocate a new local context. const Operator* op = javascript()->CreateFunctionContext(); Node* local_context = NewNode(op, closure); set_current_context(local_context); // Copy parameters into context if necessary. int num_parameters = info()->scope()->num_parameters(); for (int i = 0; i < num_parameters; i++) { Variable* variable = info()->scope()->parameter(i); if (!variable->IsContextSlot()) continue; // Temporary parameter node. The parameter indices are shifted by 1 // (receiver is parameter index -1 but environment index 0). Node* parameter = NewNode(common()->Parameter(i + 1), graph()->start()); // Context variable (at bottom of the context chain). DCHECK_EQ(0, info()->scope()->ContextChainLength(variable->scope())); const Operator* op = javascript()->StoreContext(0, variable->index()); NewNode(op, local_context, parameter); } return local_context; } Node* AstGraphBuilder::BuildArgumentsObject(Variable* arguments) { if (arguments == NULL) return NULL; // Allocate and initialize a new arguments object. Node* callee = GetFunctionClosure(); const Operator* op = javascript()->Runtime(Runtime::kNewArguments, 1); Node* object = NewNode(op, callee); // Assign the object to the arguments variable. DCHECK(arguments->IsContextSlot() || arguments->IsStackAllocated()); // This should never lazy deopt, so it is fine to send invalid bailout id. BuildVariableAssignment(arguments, object, Token::ASSIGN, BailoutId::None()); return object; } Node* AstGraphBuilder::BuildHoleCheckSilent(Node* value, Node* for_hole, Node* not_hole) { IfBuilder hole_check(this); Node* the_hole = jsgraph()->TheHoleConstant(); Node* check = NewNode(javascript()->StrictEqual(), value, the_hole); hole_check.If(check); hole_check.Then(); environment()->Push(for_hole); hole_check.Else(); environment()->Push(not_hole); hole_check.End(); return environment()->Pop(); } Node* AstGraphBuilder::BuildHoleCheckThrow(Node* value, Variable* variable, Node* not_hole) { IfBuilder hole_check(this); Node* the_hole = jsgraph()->TheHoleConstant(); Node* check = NewNode(javascript()->StrictEqual(), value, the_hole); hole_check.If(check); hole_check.Then(); environment()->Push(BuildThrowReferenceError(variable)); hole_check.Else(); environment()->Push(not_hole); hole_check.End(); return environment()->Pop(); } Node* AstGraphBuilder::BuildVariableLoad(Variable* variable, BailoutId bailout_id, ContextualMode contextual_mode) { Node* the_hole = jsgraph()->TheHoleConstant(); VariableMode mode = variable->mode(); switch (variable->location()) { case Variable::UNALLOCATED: { // Global var, const, or let variable. Node* global = BuildLoadGlobalObject(); Unique name = MakeUnique(variable->name()); const Operator* op = javascript()->LoadNamed(name, contextual_mode); Node* node = NewNode(op, global); PrepareFrameState(node, bailout_id, kPushOutput); return node; } case Variable::PARAMETER: case Variable::LOCAL: { // Local var, const, or let variable. Node* value = environment()->Lookup(variable); if (mode == CONST_LEGACY) { // Perform check for uninitialized legacy const variables. if (value->op() == the_hole->op()) { value = jsgraph()->UndefinedConstant(); } else if (value->opcode() == IrOpcode::kPhi) { Node* undefined = jsgraph()->UndefinedConstant(); value = BuildHoleCheckSilent(value, undefined, value); } } else if (mode == LET || mode == CONST) { // Perform check for uninitialized let/const variables. if (value->op() == the_hole->op()) { value = BuildThrowReferenceError(variable); } else if (value->opcode() == IrOpcode::kPhi) { value = BuildHoleCheckThrow(value, variable, value); } } return value; } case Variable::CONTEXT: { // Context variable (potentially up the context chain). int depth = current_scope()->ContextChainLength(variable->scope()); bool immutable = variable->maybe_assigned() == kNotAssigned; const Operator* op = javascript()->LoadContext(depth, variable->index(), immutable); Node* value = NewNode(op, current_context()); // TODO(titzer): initialization checks are redundant for already // initialized immutable context loads, but only specialization knows. // Maybe specializer should be a parameter to the graph builder? if (mode == CONST_LEGACY) { // Perform check for uninitialized legacy const variables. Node* undefined = jsgraph()->UndefinedConstant(); value = BuildHoleCheckSilent(value, undefined, value); } else if (mode == LET || mode == CONST) { // Perform check for uninitialized let/const variables. value = BuildHoleCheckThrow(value, variable, value); } return value; } case Variable::LOOKUP: { // Dynamic lookup of context variable (anywhere in the chain). Node* name = jsgraph()->Constant(variable->name()); Runtime::FunctionId function_id = (contextual_mode == CONTEXTUAL) ? Runtime::kLoadLookupSlot : Runtime::kLoadLookupSlotNoReferenceError; const Operator* op = javascript()->Runtime(function_id, 2); Node* pair = NewNode(op, current_context(), name); return NewNode(common()->Projection(0), pair); } } UNREACHABLE(); return NULL; } Node* AstGraphBuilder::BuildVariableDelete(Variable* variable) { switch (variable->location()) { case Variable::UNALLOCATED: { // Global var, const, or let variable. Node* global = BuildLoadGlobalObject(); Node* name = jsgraph()->Constant(variable->name()); const Operator* op = javascript()->DeleteProperty(strict_mode()); return NewNode(op, global, name); } case Variable::PARAMETER: case Variable::LOCAL: case Variable::CONTEXT: // Local var, const, or let variable or context variable. return variable->is_this() ? jsgraph()->TrueConstant() : jsgraph()->FalseConstant(); case Variable::LOOKUP: { // Dynamic lookup of context variable (anywhere in the chain). Node* name = jsgraph()->Constant(variable->name()); const Operator* op = javascript()->Runtime(Runtime::kDeleteLookupSlot, 2); return NewNode(op, current_context(), name); } } UNREACHABLE(); return NULL; } Node* AstGraphBuilder::BuildVariableAssignment(Variable* variable, Node* value, Token::Value op, BailoutId bailout_id) { Node* the_hole = jsgraph()->TheHoleConstant(); VariableMode mode = variable->mode(); switch (variable->location()) { case Variable::UNALLOCATED: { // Global var, const, or let variable. Node* global = BuildLoadGlobalObject(); Unique name = MakeUnique(variable->name()); const Operator* op = javascript()->StoreNamed(strict_mode(), name); Node* store = NewNode(op, global, value); PrepareFrameState(store, bailout_id); return store; } case Variable::PARAMETER: case Variable::LOCAL: // Local var, const, or let variable. if (mode == CONST_LEGACY && op == Token::INIT_CONST_LEGACY) { // Perform an initialization check for legacy const variables. Node* current = environment()->Lookup(variable); if (current->op() != the_hole->op()) { value = BuildHoleCheckSilent(current, value, current); } } else if (mode == CONST_LEGACY && op != Token::INIT_CONST_LEGACY) { // Non-initializing assignments to legacy const is ignored. return value; } else if (mode == LET && op != Token::INIT_LET) { // Perform an initialization check for let declared variables. // Also note that the dynamic hole-check is only done to ensure that // this does not break in the presence of do-expressions within the // temporal dead zone of a let declared variable. Node* current = environment()->Lookup(variable); if (current->op() == the_hole->op()) { value = BuildThrowReferenceError(variable); } else if (value->opcode() == IrOpcode::kPhi) { value = BuildHoleCheckThrow(current, variable, value); } } else if (mode == CONST && op != Token::INIT_CONST) { // All assignments to const variables are early errors. UNREACHABLE(); } environment()->Bind(variable, value); return value; case Variable::CONTEXT: { // Context variable (potentially up the context chain). int depth = current_scope()->ContextChainLength(variable->scope()); if (mode == CONST_LEGACY && op == Token::INIT_CONST_LEGACY) { // Perform an initialization check for legacy const variables. const Operator* op = javascript()->LoadContext(depth, variable->index(), false); Node* current = NewNode(op, current_context()); value = BuildHoleCheckSilent(current, value, current); } else if (mode == CONST_LEGACY && op != Token::INIT_CONST_LEGACY) { // Non-initializing assignments to legacy const is ignored. return value; } else if (mode == LET && op != Token::INIT_LET) { // Perform an initialization check for let declared variables. const Operator* op = javascript()->LoadContext(depth, variable->index(), false); Node* current = NewNode(op, current_context()); value = BuildHoleCheckThrow(current, variable, value); } else if (mode == CONST && op != Token::INIT_CONST) { // All assignments to const variables are early errors. UNREACHABLE(); } const Operator* op = javascript()->StoreContext(depth, variable->index()); return NewNode(op, current_context(), value); } case Variable::LOOKUP: { // Dynamic lookup of context variable (anywhere in the chain). Node* name = jsgraph()->Constant(variable->name()); Node* strict = jsgraph()->Constant(strict_mode()); // TODO(mstarzinger): Use Runtime::kInitializeLegacyConstLookupSlot for // initializations of const declarations. const Operator* op = javascript()->Runtime(Runtime::kStoreLookupSlot, 4); return NewNode(op, value, current_context(), name, strict); } } UNREACHABLE(); return NULL; } Node* AstGraphBuilder::BuildLoadObjectField(Node* object, int offset) { // TODO(sigurds) Use simplified load here once it is ready. Node* field_load = NewNode(jsgraph()->machine()->Load(kMachAnyTagged), object, jsgraph()->Int32Constant(offset - kHeapObjectTag)); return field_load; } Node* AstGraphBuilder::BuildLoadBuiltinsObject() { Node* global = BuildLoadGlobalObject(); Node* builtins = BuildLoadObjectField(global, JSGlobalObject::kBuiltinsOffset); return builtins; } Node* AstGraphBuilder::BuildLoadGlobalObject() { Node* context = GetFunctionContext(); const Operator* load_op = javascript()->LoadContext(0, Context::GLOBAL_OBJECT_INDEX, true); return NewNode(load_op, context); } Node* AstGraphBuilder::BuildToBoolean(Node* value) { // TODO(mstarzinger): Possible optimization is to NOP for boolean values. return NewNode(javascript()->ToBoolean(), value); } Node* AstGraphBuilder::BuildThrowReferenceError(Variable* variable) { // TODO(mstarzinger): Should be unified with the VisitThrow implementation. Node* variable_name = jsgraph()->Constant(variable->name()); const Operator* op = javascript()->Runtime(Runtime::kThrowReferenceError, 1); return NewNode(op, variable_name); } Node* AstGraphBuilder::BuildBinaryOp(Node* left, Node* right, Token::Value op) { const Operator* js_op; switch (op) { case Token::BIT_OR: js_op = javascript()->BitwiseOr(); break; case Token::BIT_AND: js_op = javascript()->BitwiseAnd(); break; case Token::BIT_XOR: js_op = javascript()->BitwiseXor(); break; case Token::SHL: js_op = javascript()->ShiftLeft(); break; case Token::SAR: js_op = javascript()->ShiftRight(); break; case Token::SHR: js_op = javascript()->ShiftRightLogical(); break; case Token::ADD: js_op = javascript()->Add(); break; case Token::SUB: js_op = javascript()->Subtract(); break; case Token::MUL: js_op = javascript()->Multiply(); break; case Token::DIV: js_op = javascript()->Divide(); break; case Token::MOD: js_op = javascript()->Modulus(); break; default: UNREACHABLE(); js_op = NULL; } return NewNode(js_op, left, right); } void AstGraphBuilder::PrepareFrameState(Node* node, BailoutId ast_id, OutputFrameStateCombine combine) { if (OperatorProperties::HasFrameStateInput(node->op())) { DCHECK(NodeProperties::GetFrameStateInput(node)->opcode() == IrOpcode::kDead); NodeProperties::ReplaceFrameStateInput( node, environment()->Checkpoint(ast_id, combine)); } } } } } // namespace v8::internal::compiler ",16133,True,3446.0839565232222,median "//-------------------------------------------------------------------------------------- // File: xwbtool.cpp // // Simple command-line tool for building wave banks from 1 or more .WAV files. This // generates binary wave banks compliant with XACT 3's Wave Bank .XWB format. The // .WAV files are not format converted or compressed. // // For a more full-featured builder, see XACT 3 and the XACTBLD tool in the legacy // DirectX SDK (June 2010) release. // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // // http://go.microsoft.com/fwlink/?LinkId=248929 //-------------------------------------------------------------------------------------- #pragma warning(push) #pragma warning(disable : 4005) #define WIN32_LEAN_AND_MEAN #define NOMINMAX #define NODRAWTEXT #define NOGDI #define NOBITMAP #define NOMCX #define NOSERVICE #define NOHELP #pragma warning(pop) #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""WAVFileReader.h"" #ifdef __INTEL_COMPILER #pragma warning(disable : 161) // warning #161: unrecognized #pragma #endif ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifndef MAKEFOURCC #define MAKEFOURCC(ch0, ch1, ch2, ch3) \\ (static_cast(static_cast(ch0)) \\ | (static_cast(static_cast(ch1)) << 8) \\ | (static_cast(static_cast(ch2)) << 16) \\ | (static_cast(static_cast(ch3)) << 24)) #endif /* defined(MAKEFOURCC) */ #ifndef WAVE_FORMAT_XMA2 #define WAVE_FORMAT_XMA2 0x166 #pragma pack(push,1) struct XMA2WAVEFORMATEX { WAVEFORMATEX wfx; // Meaning of the WAVEFORMATEX fields here: // wFormatTag; // Audio format type; always WAVE_FORMAT_XMA2 // nChannels; // Channel count of the decoded audio // nSamplesPerSec; // Sample rate of the decoded audio // nAvgBytesPerSec; // Used internally by the XMA encoder // nBlockAlign; // Decoded sample size; channels * wBitsPerSample / 8 // wBitsPerSample; // Bits per decoded mono sample; always 16 for XMA // cbSize; // Size in bytes of the rest of this structure (34) WORD NumStreams; // Number of audio streams (1 or 2 channels each) DWORD ChannelMask; // Spatial positions of the channels in this file, // stored as SPEAKER_xxx values (see audiodefs.h) DWORD SamplesEncoded; // Total number of PCM samples per channel the file decodes to DWORD BytesPerBlock; // XMA block size (but the last one may be shorter) DWORD PlayBegin; // First valid sample in the decoded audio DWORD PlayLength; // Length of the valid part of the decoded audio DWORD LoopBegin; // Beginning of the loop region in decoded sample terms DWORD LoopLength; // Length of the loop region in decoded sample terms BYTE LoopCount; // Number of loop repetitions; 255 = infinite BYTE EncoderVersion; // Version of XMA encoder that generated the file WORD BlockCount; // XMA blocks in file (and entries in its seek table) }; #pragma pack(pop) #endif static_assert(sizeof(XMA2WAVEFORMATEX) == 52, ""Mismatch of XMA2 type""); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// namespace { struct handle_closer { void operator()(HANDLE h) { if (h) CloseHandle(h); } }; using ScopedHandle = std::unique_ptr; inline HANDLE safe_handle(HANDLE h) { return (h == INVALID_HANDLE_VALUE) ? nullptr : h; } struct find_closer { void operator()(HANDLE h) { assert(h != INVALID_HANDLE_VALUE); if (h) FindClose(h); } }; using ScopedFindHandle = std::unique_ptr; #define BLOCKALIGNPAD(a, b) \\ ((((a) + ((b) - 1)) / (b)) * (b)) #define XACT_CONTENT_VERSION 46 // DirectX SDK (June 2010) #pragma pack(push, 1) static const size_t DVD_SECTOR_SIZE = 2048; static const size_t ALIGNMENT_MIN = 4; static const size_t ALIGNMENT_DVD = DVD_SECTOR_SIZE; static const size_t MAX_COMPACT_DATA_SEGMENT_SIZE = 0x001FFFFF; static const size_t ENTRYNAME_LENGTH = 64; struct REGION { uint32_t dwOffset; // Region offset, in bytes. uint32_t dwLength; // Region length, in bytes. }; struct SAMPLEREGION { uint32_t dwStartSample; // Start sample for the region. uint32_t dwTotalSamples; // Region length in samples. }; struct HEADER { static const uint32_t SIGNATURE = MAKEFOURCC('W', 'B', 'N', 'D'); static const uint32_t VERSION = 44; enum SEGIDX { SEGIDX_BANKDATA = 0, // Bank data SEGIDX_ENTRYMETADATA, // Entry meta-data SEGIDX_SEEKTABLES, // Storage for seek tables for the encoded waves. SEGIDX_ENTRYNAMES, // Entry friendly names SEGIDX_ENTRYWAVEDATA, // Entry wave data SEGIDX_COUNT }; uint32_t dwSignature; // File signature uint32_t dwVersion; // Version of the tool that created the file uint32_t dwHeaderVersion; // Version of the file format REGION Segments[SEGIDX_COUNT]; // Segment lookup table }; #pragma warning( disable : 4201 4203 ) union MINIWAVEFORMAT { static const uint32_t TAG_PCM = 0x0; static const uint32_t TAG_XMA = 0x1; static const uint32_t TAG_ADPCM = 0x2; static const uint32_t TAG_WMA = 0x3; static const uint32_t BITDEPTH_8 = 0x0; // PCM only static const uint32_t BITDEPTH_16 = 0x1; // PCM only static const size_t ADPCM_BLOCKALIGN_CONVERSION_OFFSET = 22; struct { uint32_t wFormatTag : 2; // Format tag uint32_t nChannels : 3; // Channel count (1 - 6) uint32_t nSamplesPerSec : 18; // Sampling rate uint32_t wBlockAlign : 8; // Block alignment. For WMA, lower 6 bits block alignment index, upper 2 bits bytes-per-second index. uint32_t wBitsPerSample : 1; // Bits per sample (8 vs. 16, PCM only); WMAudio2/WMAudio3 (for WMA) }; uint32_t dwValue; }; struct ENTRY { static const uint32_t FLAGS_READAHEAD = 0x00000001; // Enable stream read-ahead static const uint32_t FLAGS_LOOPCACHE = 0x00000002; // One or more looping sounds use this wave static const uint32_t FLAGS_REMOVELOOPTAIL = 0x00000004;// Remove data after the end of the loop region static const uint32_t FLAGS_IGNORELOOP = 0x00000008; // Used internally when the loop region can't be used static const uint32_t FLAGS_MASK = 0x00000008; union { struct { // Entry flags uint32_t dwFlags : 4; // Duration of the wave, in units of one sample. // For instance, a ten second long wave sampled // at 48KHz would have a duration of 480,000. // This value is not affected by the number of // channels, the number of bits per sample, or the // compression format of the wave. uint32_t Duration : 28; }; uint32_t dwFlagsAndDuration; }; MINIWAVEFORMAT Format; // Entry format. REGION PlayRegion; // Region within the wave data segment that contains this entry. SAMPLEREGION LoopRegion; // Region within the wave data (in samples) that should loop. }; struct ENTRYCOMPACT { uint32_t dwOffset : 21; // Data offset, in multiplies of the bank alignment uint32_t dwLengthDeviation : 11; // Data length deviation, in bytes }; struct BANKDATA { static const size_t BANKNAME_LENGTH = 64; static const uint32_t TYPE_BUFFER = 0x00000000; static const uint32_t TYPE_STREAMING = 0x00000001; static const uint32_t TYPE_MASK = 0x00000001; static const uint32_t FLAGS_ENTRYNAMES = 0x00010000; static const uint32_t FLAGS_COMPACT = 0x00020000; static const uint32_t FLAGS_SYNC_DISABLED = 0x00040000; static const uint32_t FLAGS_SEEKTABLES = 0x00080000; static const uint32_t FLAGS_MASK = 0x000F0000; uint32_t dwFlags; // Bank flags uint32_t dwEntryCount; // Number of entries in the bank char szBankName[BANKNAME_LENGTH]; // Bank friendly name uint32_t dwEntryMetaDataElementSize; // Size of each entry meta-data element, in bytes uint32_t dwEntryNameElementSize; // Size of each entry name element, in bytes uint32_t dwAlignment; // Entry alignment, in bytes MINIWAVEFORMAT CompactFormat; // Format data for compact bank FILETIME BuildTime; // Build timestamp }; #pragma pack(pop) static_assert(sizeof(REGION) == 8, ""Mismatch with xact3wb.h""); static_assert(sizeof(SAMPLEREGION) == 8, ""Mismatch with xact3wb.h""); static_assert(sizeof(HEADER) == 52, ""Mismatch with xact3wb.h""); static_assert(sizeof(ENTRY) == 24, ""Mismatch with xact3wb.h""); static_assert(sizeof(MINIWAVEFORMAT) == 4, ""Mismatch with xact3wb.h""); static_assert(sizeof(ENTRY) == 24, ""Mismatch with xact3wb.h""); static_assert(sizeof(ENTRYCOMPACT) == 4, ""Mismatch with xact3wb.h""); static_assert(sizeof(BANKDATA) == 96, ""Mismatch with xact3wb.h""); template WORD ChannelsSpecifiedInMask(T x) { WORD bitCount = 0; while (x) { ++bitCount; x &= (x - 1); } return bitCount; } WORD AdpcmBlockSizeFromPcmFrames(WORD nPcmFrames, WORD nChannels) { // The full calculation is as follows: // UINT uHeaderBytes = MSADPCM_HEADER_LENGTH * nChannels; // UINT uBitsPerSample = MSADPCM_BITS_PER_SAMPLE * nChannels; // UINT uBlockAlign = uHeaderBytes + (nPcmFrames - 2) * uBitsPerSample / 8; // return WORD(uBlockAlign); assert(nChannels == 1 || nChannels == 2); if (nPcmFrames) { if (nChannels == 1) { assert(nPcmFrames % 2 == 0); // Mono data needs even nPcmFrames return WORD(nPcmFrames / 2 + 6); } else { return WORD(nPcmFrames + 12); } } else { return 0; } } DWORD EncodeWMABlockAlign(DWORD dwBlockAlign, DWORD dwAvgBytesPerSec) { static const uint32_t aWMABlockAlign[] = { 929, 1487, 1280, 2230, 8917, 8192, 4459, 5945, 2304, 1536, 1485, 1008, 2731, 4096, 6827, 5462, 1280 }; static const uint32_t aWMAAvgBytesPerSec[] = { 12000, 24000, 4000, 6000, 8000, 20000, 2500 }; auto bit = std::find(std::begin(aWMABlockAlign), std::end(aWMABlockAlign), dwBlockAlign); if (bit == std::end(aWMABlockAlign)) return DWORD(-1); DWORD blockAlignIndex = DWORD(bit - std::begin(aWMABlockAlign)); auto ait = std::find(std::begin(aWMAAvgBytesPerSec), std::end(aWMAAvgBytesPerSec), dwAvgBytesPerSec); if (ait == std::end(aWMAAvgBytesPerSec)) return DWORD(-1); DWORD bytesPerSecIndex = DWORD(ait - std::begin(aWMAAvgBytesPerSec)); return DWORD(blockAlignIndex | (bytesPerSecIndex << 5)); } bool ConvertToMiniFormat(const WAVEFORMATEX* wfx, bool hasSeek, MINIWAVEFORMAT& miniFmt) { if (!wfx) return false; if (!wfx->nChannels) { wprintf(L""ERROR: Wave bank entry must have at least 1 channel\\n""); return false; } if (wfx->nChannels > 7) { wprintf(L""ERROR: Wave banks only support up to 7 channels\\n""); return false; } if (!wfx->nSamplesPerSec) { wprintf(L""ERROR: Wave banks entry sample rate must be non-zero\\n""); return false; } if (wfx->nSamplesPerSec > 262143) { wprintf(L""ERROR: Wave banks only support sample rates up to 2^18 (262143)\\n""); return false; } miniFmt.dwValue = 0; miniFmt.nSamplesPerSec = wfx->nSamplesPerSec; miniFmt.nChannels = wfx->nChannels; switch (wfx->wFormatTag) { case WAVE_FORMAT_PCM: if ((wfx->wBitsPerSample != 8) && (wfx->wBitsPerSample != 16)) { wprintf(L""ERROR: Wave banks only support 8-bit or 16-bit integer PCM data\\n""); return false; } if (wfx->nBlockAlign > 255) { wprintf(L""ERROR: Wave banks only support block alignments up to 255 (%u)\\n"", wfx->nBlockAlign); return false; } if (wfx->nBlockAlign != (wfx->nChannels * wfx->wBitsPerSample / 8)) { wprintf(L""ERROR: nBlockAlign (%u) != nChannels (%u) * wBitsPerSample (%u) / 8\\n"", wfx->nBlockAlign, wfx->nChannels, wfx->wBitsPerSample); return false; } if (wfx->nAvgBytesPerSec != (wfx->nSamplesPerSec * wfx->nBlockAlign)) { wprintf(L""ERROR: nAvgBytesPerSec (%lu) != nSamplesPerSec (%lu) * nBlockAlign (%u)\\n"", wfx->nAvgBytesPerSec, wfx->nSamplesPerSec, wfx->nBlockAlign); return false; } miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_PCM; miniFmt.wBitsPerSample = (wfx->wBitsPerSample == 16) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; miniFmt.wBlockAlign = wfx->nBlockAlign; return true; case WAVE_FORMAT_IEEE_FLOAT: wprintf(L""ERROR: Wave banks do not support IEEE float PCM data\\n""); return false; case WAVE_FORMAT_ADPCM: if ((wfx->nChannels != 1) && (wfx->nChannels != 2)) { wprintf(L""ERROR: ADPCM wave format must have 1 or 2 channels (not %u)\\n"", wfx->nChannels); return false; } if (wfx->wBitsPerSample != 4 /*MSADPCM_BITS_PER_SAMPLE*/) { wprintf(L""ERROR: ADPCM wave format must have 4 bits per sample (not %u)\\n"", wfx->wBitsPerSample); return false; } if (wfx->cbSize != 32 /*MSADPCM_FORMAT_EXTRA_BYTES*/) { wprintf(L""ERROR: ADPCM wave format must have cbSize = 32 (not %u)\\n"", wfx->cbSize); return false; } else { auto wfadpcm = reinterpret_cast(wfx); if (wfadpcm->wNumCoef != 7 /*MSADPCM_NUM_COEFFICIENTS*/) { wprintf(L""ERROR: ADPCM wave format must have 7 coefficients (not %u)\\n"", wfadpcm->wNumCoef); return false; } bool valid = true; for (int j = 0; j < 7 /*MSADPCM_NUM_COEFFICIENTS*/; ++j) { // Microsoft ADPCM standard encoding coefficients static const short g_pAdpcmCoefficients1[] = { 256, 512, 0, 192, 240, 460, 392 }; static const short g_pAdpcmCoefficients2[] = { 0, -256, 0, 64, 0, -208, -232 }; if (wfadpcm->aCoef[j].iCoef1 != g_pAdpcmCoefficients1[j] || wfadpcm->aCoef[j].iCoef2 != g_pAdpcmCoefficients2[j]) { valid = false; } } if (!valid) { wprintf(L""ERROR: Non-standard coefficients for ADPCM found\\n""); return false; } if ((wfadpcm->wSamplesPerBlock < 4 /*MSADPCM_MIN_SAMPLES_PER_BLOCK*/) || (wfadpcm->wSamplesPerBlock > 64000 /*MSADPCM_MAX_SAMPLES_PER_BLOCK*/)) { wprintf(L""ERROR: ADPCM wave format wSamplesPerBlock must be 4..64000\\n""); return false; } if (wfadpcm->wfx.nChannels == 1 && (wfadpcm->wSamplesPerBlock % 2)) { wprintf(L""ERROR: ADPCM wave format mono files must have even wSamplesPerBlock\\n""); return false; } unsigned int nHeaderBytes = 7 /*MSADPCM_HEADER_LENGTH*/ * wfx->nChannels; unsigned int nBitsPerFrame = 4 /*MSADPCM_BITS_PER_SAMPLE*/ * wfx->nChannels; unsigned int nPcmFramesPerBlock = (wfx->nBlockAlign - nHeaderBytes) * 8 / nBitsPerFrame + 2; if (wfadpcm->wSamplesPerBlock != nPcmFramesPerBlock) { wprintf(L""ERROR: ADPCM %u-channel format with nBlockAlign = %u must have wSamplesPerBlock = %u (not %u)\\n"", wfx->nChannels, wfx->nBlockAlign, nPcmFramesPerBlock, wfadpcm->wSamplesPerBlock); return false; } miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_ADPCM; miniFmt.wBitsPerSample = 0; miniFmt.wBlockAlign = AdpcmBlockSizeFromPcmFrames(wfadpcm->wSamplesPerBlock, 1) - MINIWAVEFORMAT::ADPCM_BLOCKALIGN_CONVERSION_OFFSET; } return true; case WAVE_FORMAT_WMAUDIO2: case WAVE_FORMAT_WMAUDIO3: if (!hasSeek) { wprintf(L""ERROR: xWMA requires seek tables ('dpds' chunk)\\n""); return false; } if (wfx->wBitsPerSample != 16) { wprintf(L""ERROR: Wave banks only support 16-bit xWMA data\\n""); return false; } if (!wfx->nBlockAlign) { wprintf(L""ERROR: Wave bank xWMA must have a non-zero nBlockAlign\\n""); return false; } if (!wfx->nAvgBytesPerSec) { wprintf(L""ERROR: Wave bank xWMA must have a non-zero nAvgBytesPerSec\\n""); return false; } if (wfx->cbSize != 0) { wprintf(L""ERROR: Unexpected data found in xWMA header\\n""); return false; } miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_WMA; miniFmt.wBitsPerSample = (wfx->wFormatTag == WAVE_FORMAT_WMAUDIO3) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; { DWORD blockAlign = EncodeWMABlockAlign(wfx->nBlockAlign, wfx->nAvgBytesPerSec); if (blockAlign == DWORD(-1)) { wprintf(L""ERROR: Failed encoding nBlockAlign and nAvgBytesPerSec for xWMA\\n""); return false; } miniFmt.wBlockAlign = blockAlign; } return true; case WAVE_FORMAT_XMA2: if (!hasSeek) { wprintf(L""ERROR: XMA2 requires seek tables ('seek' chunk)\\n""); return false; } if (wfx->nBlockAlign != wfx->nChannels * 2 /*XMA_OUTPUT_SAMPLE_BYTES*/) { wprintf(L""ERROR: XMA2 nBlockAlign (%u) != nChannels(%u) * 2\\n"", wfx->nBlockAlign, wfx->nChannels); return false; } if (wfx->wBitsPerSample != 16 /*XMA_OUTPUT_SAMPLE_BITS*/) { wprintf(L""ERROR: XMA2 wBitsPerSample (%u) should be 16\\n"", wfx->wBitsPerSample); return false; } if (wfx->cbSize != (sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX))) { wprintf(L""ERROR: XMA2 cbSize must be %zu (%u)"", (sizeof(XMA2WAVEFORMATEX) - sizeof(WAVEFORMATEX)), wfx->cbSize); return false; } else { auto xmaFmt = reinterpret_cast(wfx); if (xmaFmt->EncoderVersion < 3) { wprintf(L""ERROR: XMA2 encoder version (%u) - 3 or higher is required"", xmaFmt->EncoderVersion); return false; } if (!xmaFmt->BlockCount) { wprintf(L""ERROR: XMA2 BlockCount must be non-zero\\n""); return false; } if (!xmaFmt->BytesPerBlock || (xmaFmt->BytesPerBlock > 8386560 /*XMA_READBUFFER_MAX_BYTES*/)) { wprintf(L""ERROR: XMA2 BytesPerBlock (%lu) is invalid\\n"", xmaFmt->BytesPerBlock); return false; } if (xmaFmt->ChannelMask) { auto channelBits = ChannelsSpecifiedInMask(xmaFmt->ChannelMask); if (channelBits != wfx->nChannels) { wprintf(L""ERROR: XMA2 nChannels=%lu but ChannelMask (%08X) has %u bits set\\n"", xmaFmt->ChannelMask, wfx->nChannels, channelBits); return false; } } if (xmaFmt->NumStreams != ((wfx->nChannels + 1) / 2)) { wprintf(L""ERROR: XMA2 NumStreams (%u) != ( nChannels(%u) + 1 ) / 2\\n"", xmaFmt->NumStreams, wfx->nChannels); return false; } if (!xmaFmt->SamplesEncoded) { wprintf(L""ERROR: XMA2 SamplesEncoded must be non-zero\\n""); return false; } if ((xmaFmt->PlayBegin + xmaFmt->PlayLength) > xmaFmt->SamplesEncoded) { wprintf(L""ERROR: XMA2 play region too large (%lu + %lu > %lu)"", xmaFmt->PlayBegin, xmaFmt->PlayLength, xmaFmt->SamplesEncoded); return false; } if ((xmaFmt->LoopBegin + xmaFmt->LoopLength) > xmaFmt->SamplesEncoded) { wprintf(L""ERROR: XMA2 loop region too large (%lu + %lu > %lu)"", xmaFmt->LoopBegin, xmaFmt->LoopLength, xmaFmt->SamplesEncoded); return false; } miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_XMA; miniFmt.wBlockAlign = 2 * wfx->nChannels; miniFmt.wBitsPerSample = MINIWAVEFORMAT::BITDEPTH_16; } return true; case WAVE_FORMAT_EXTENSIBLE: if (wfx->cbSize < (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX))) { wprintf(L""ERROR: WAVEFORMATEXTENSIBLE cbSize must be at least %zu (%u)"", (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)), wfx->cbSize); return false; } else { static const GUID s_wfexBase = { 0x00000000, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71 } }; auto wfex = reinterpret_cast(wfx); if (memcmp(reinterpret_cast(&wfex->SubFormat) + sizeof(DWORD), reinterpret_cast(&s_wfexBase) + sizeof(DWORD), sizeof(GUID) - sizeof(DWORD)) != 0) { wprintf(L""ERROR: WAVEFORMATEXTENSIBLE encountered with unknown GUID ({%8.8lX-%4.4X-%4.4X-%2.2X%2.2X-%2.2X%2.2X%2.2X%2.2X%2.2X%2.2X})\\n"", wfex->SubFormat.Data1, wfex->SubFormat.Data2, wfex->SubFormat.Data3, wfex->SubFormat.Data4[0], wfex->SubFormat.Data4[1], wfex->SubFormat.Data4[2], wfex->SubFormat.Data4[3], wfex->SubFormat.Data4[4], wfex->SubFormat.Data4[5], wfex->SubFormat.Data4[6], wfex->SubFormat.Data4[7]); return false; } switch (wfex->SubFormat.Data1) { case WAVE_FORMAT_PCM: if ((wfx->wBitsPerSample != 8) && (wfx->wBitsPerSample != 16)) { wprintf(L""ERROR: Wave banks only support 8-bit or 16-bit integer PCM data (%u)\\n"", wfx->wBitsPerSample); return false; } if (!wfex->Samples.wValidBitsPerSample) { wprintf(L""WARNING: Integer PCM WAVEFORMATEXTENSIBLE format should not have wValidBitsPerSample = 0\\n""); } else if (((wfex->Samples.wValidBitsPerSample != 8) && (wfex->Samples.wValidBitsPerSample != 16)) || (wfex->Samples.wValidBitsPerSample > wfx->wBitsPerSample)) { wprintf(L""ERROR: Unexpected wValidBitsPerSample value (%u)\\n"", wfex->Samples.wValidBitsPerSample); return false; } if (wfx->nBlockAlign > 255) { wprintf(L""ERROR: Wave banks only support block alignments up to 255 (%u)\\n"", wfx->nBlockAlign); return false; } if (wfx->nBlockAlign != (wfx->nChannels * wfx->wBitsPerSample / 8)) { wprintf(L""ERROR: nBlockAlign (%u) != nChannels (%u) * wBitsPerSample (%u) / 8\\n"", wfx->nBlockAlign, wfx->nChannels, wfx->wBitsPerSample); return false; } if (wfx->nAvgBytesPerSec != (wfx->nSamplesPerSec * wfx->nBlockAlign)) { wprintf(L""ERROR: nAvgBytesPerSec (%lu) != nSamplesPerSec (%lu) * nBlockAlign (%u)\\n"", wfx->nAvgBytesPerSec, wfx->nSamplesPerSec, wfx->nBlockAlign); return false; } miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_PCM; miniFmt.wBitsPerSample = (wfex->Samples.wValidBitsPerSample == 16) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; miniFmt.wBlockAlign = wfx->nBlockAlign; break; case WAVE_FORMAT_IEEE_FLOAT: wprintf(L""ERROR: Wave banks do not support float PCM data\\n""); return false; case WAVE_FORMAT_ADPCM: wprintf(L""ERROR: ADPCM is not supported as a WAVEFORMATEXTENSIBLE\\n""); return false; case WAVE_FORMAT_WMAUDIO2: case WAVE_FORMAT_WMAUDIO3: if (!hasSeek) { wprintf(L""ERROR: xWMA requires seek tables (dpds chunk)\\n""); return false; } if (wfx->wBitsPerSample != 16) { wprintf(L""ERROR: Wave banks only support 16-bit xWMA data\\n""); return false; } if (!wfx->nBlockAlign) { wprintf(L""ERROR: Wvae bank xWMA must have a non-zero nBlockAlign\\n""); return false; } if (!wfx->nAvgBytesPerSec) { wprintf(L""ERROR: Wave bank xWMA must have a non-zero nAvgBytesPerSec\\n""); return false; } miniFmt.wFormatTag = MINIWAVEFORMAT::TAG_WMA; miniFmt.wBitsPerSample = (wfx->wFormatTag == WAVE_FORMAT_WMAUDIO3) ? MINIWAVEFORMAT::BITDEPTH_16 : MINIWAVEFORMAT::BITDEPTH_8; { DWORD blockAlign = EncodeWMABlockAlign(wfx->nBlockAlign, wfx->nAvgBytesPerSec); if (blockAlign == DWORD(-1)) { wprintf(L""ERROR: Failed encoding nBlockAlign and nAvgBytesPerSec for xWMA\\n""); return false; } miniFmt.wBlockAlign = blockAlign; } break; case WAVE_FORMAT_XMA2: wprintf(L""ERROR: XMA2 is not supported as a WAVEFORMATEXTENSIBLE\\n""); return false; default: wprintf(L""ERROR: Unknown WAVEFORMATEXTENSIBLE format tag\\n""); return false; } if (wfex->dwChannelMask) { auto channelBits = ChannelsSpecifiedInMask(wfex->dwChannelMask); if (channelBits != wfx->nChannels) { wprintf(L""ERROR: WAVEFORMATEXTENSIBLE: nChannels=%u but ChannelMask has %u bits set\\n"", wfx->nChannels, channelBits); return false; } else { wprintf(L""WARNING: WAVEFORMATEXTENSIBLE ChannelMask is ignored in wave banks\\n""); } } return true; } default: return false; } } } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// enum OPTIONS { OPT_RECURSIVE = 1, OPT_STREAMING, OPT_OUTPUTFILE, OPT_OUTPUTHEADER, OPT_TOLOWER, OPT_OVERWRITE, OPT_COMPACT, OPT_NOCOMPACT, OPT_FRIENDLY_NAMES, OPT_NOLOGO, OPT_FILELIST, OPT_MAX }; static_assert(OPT_MAX <= 32, ""dwOptions is a DWORD bitfield""); struct SConversion { wchar_t szSrc[MAX_PATH]; }; struct SValue { LPCWSTR pName; DWORD dwValue; }; struct WaveFile { DirectX::WAVData data; size_t conv; MINIWAVEFORMAT miniFmt; std::unique_ptr waveData; WaveFile() noexcept : data{}, conv(0), miniFmt{} {} WaveFile(WaveFile&) = delete; WaveFile& operator= (WaveFile&) = delete; WaveFile(WaveFile&&) = default; WaveFile& operator= (WaveFile&&) = default; }; namespace { void FileNameToIdentifier(_Inout_updates_all_(count) wchar_t* str, size_t count) { size_t j = 0; for (wchar_t* c = str; j < count && *c != 0; ++c, ++j) { wchar_t t = towupper(*c); if (!iswdigit(t) && !iswalpha(t)) t = '_'; *c = t; } } } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// const SValue g_pOptions[] = { { L""r"", OPT_RECURSIVE }, { L""s"", OPT_STREAMING }, { L""o"", OPT_OUTPUTFILE }, { L""l"", OPT_TOLOWER }, { L""h"", OPT_OUTPUTHEADER }, { L""y"", OPT_OVERWRITE }, { L""c"", OPT_COMPACT }, { L""nc"", OPT_NOCOMPACT }, { L""f"", OPT_FRIENDLY_NAMES }, { L""nologo"", OPT_NOLOGO }, { L""flist"", OPT_FILELIST }, { nullptr, 0 } }; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// namespace { #ifdef _PREFAST_ #pragma prefast(disable : 26018, ""Only used with static internal arrays"") #endif DWORD LookupByName(const wchar_t *pName, const SValue *pArray) { while (pArray->pName) { if (!_wcsicmp(pName, pArray->pName)) return pArray->dwValue; pArray++; } return 0; } void SearchForFiles(const wchar_t* path, std::list& files, bool recursive) { // Process files WIN32_FIND_DATAW findData = {}; ScopedFindHandle hFile(safe_handle(FindFirstFileExW(path, FindExInfoBasic, &findData, FindExSearchNameMatch, nullptr, FIND_FIRST_EX_LARGE_FETCH))); if (hFile) { for (;;) { if (!(findData.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_DIRECTORY))) { wchar_t drive[_MAX_DRIVE] = {}; wchar_t dir[_MAX_DIR] = {}; _wsplitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0); SConversion conv = {}; _wmakepath_s(conv.szSrc, drive, dir, findData.cFileName, nullptr); files.push_back(conv); } if (!FindNextFileW(hFile.get(), &findData)) break; } } // Process directories if (recursive) { wchar_t searchDir[MAX_PATH] = {}; { wchar_t drive[_MAX_DRIVE] = {}; wchar_t dir[_MAX_DIR] = {}; _wsplitpath_s(path, drive, _MAX_DRIVE, dir, _MAX_DIR, nullptr, 0, nullptr, 0); _wmakepath_s(searchDir, drive, dir, L""*"", nullptr); } hFile.reset(safe_handle(FindFirstFileExW(searchDir, FindExInfoBasic, &findData, FindExSearchLimitToDirectories, nullptr, FIND_FIRST_EX_LARGE_FETCH))); if (!hFile) return; for (;;) { if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (findData.cFileName[0] != L'.') { wchar_t subdir[MAX_PATH] = {}; { wchar_t drive[_MAX_DRIVE] = {}; wchar_t dir[_MAX_DIR] = {}; wchar_t fname[_MAX_FNAME] = {}; wchar_t ext[_MAX_FNAME] = {}; _wsplitpath_s(path, drive, dir, fname, ext); wcscat_s(dir, findData.cFileName); _wmakepath_s(subdir, drive, dir, fname, ext); } SearchForFiles(subdir, files, recursive); } } if (!FindNextFileW(hFile.get(), &findData)) break; } } } void PrintLogo() { wchar_t version[32] = {}; wchar_t appName[_MAX_PATH] = {}; if (GetModuleFileNameW(nullptr, appName, static_cast(std::size(appName)))) { DWORD size = GetFileVersionInfoSizeW(appName, nullptr); if (size > 0) { auto verInfo = std::make_unique(size); if (GetFileVersionInfoW(appName, 0, size, verInfo.get())) { LPVOID lpstr = nullptr; UINT strLen = 0; if (VerQueryValueW(verInfo.get(), L""\\\\StringFileInfo\\\\040904B0\\\\ProductVersion"", &lpstr, &strLen)) { wcsncpy_s(version, reinterpret_cast(lpstr), strLen); } } } } if (!*version) { wcscpy_s(version, L""MISSING""); } wprintf(L""Microsoft (R) XACT-style Wave Bank Tool [DirectXTK] Version %ls\\n"", version); wprintf(L""Copyright (C) Microsoft Corp. All rights reserved.\\n""); #ifdef _DEBUG wprintf(L""*** Debug build ***\\n""); #endif wprintf(L""\\n""); } void PrintUsage() { PrintLogo(); wprintf(L""Usage: xwbtool \\n""); wprintf(L""\\n""); wprintf(L"" -r wildcard filename search is recursive\\n""); wprintf(L"" -s creates a streaming wave bank,\\n""); wprintf(L"" otherwise an in-memory bank is created\\n""); wprintf(L"" -o output filename\\n""); wprintf(L"" -h output C/C++ header\\n""); wprintf(L"" -l force output filename to lower case\\n""); wprintf(L"" -y overwrite existing output file (if any)\\n""); wprintf(L"" -c force creation of compact wavebank\\n""); wprintf(L"" -nc force creation of non-compact wavebank\\n""); wprintf(L"" -f include entry friendly names\\n""); wprintf(L"" -nologo suppress copyright message\\n""); wprintf(L"" -flist use text file with a list of input files (one per line)\\n""); } const char* GetFormatTagName(WORD wFormatTag) { switch (wFormatTag) { case WAVE_FORMAT_PCM: return ""PCM""; case WAVE_FORMAT_ADPCM: return ""MS ADPCM""; case WAVE_FORMAT_EXTENSIBLE: return ""EXTENSIBLE""; case WAVE_FORMAT_IEEE_FLOAT: return ""IEEE float""; case WAVE_FORMAT_MPEGLAYER3: return ""ISO/MPEG Layer3""; case WAVE_FORMAT_DOLBY_AC3_SPDIF: return ""Dolby Audio Codec 3 over S/PDIF""; case WAVE_FORMAT_WMAUDIO2: return ""Windows Media Audio""; case WAVE_FORMAT_WMAUDIO3: return ""Windows Media Audio Pro""; case WAVE_FORMAT_WMASPDIF: return ""Windows Media Audio over S/PDIF""; case 0x165: /*WAVE_FORMAT_XMA*/ return ""Xbox XMA""; case 0x166: /*WAVE_FORMAT_XMA2*/ return ""Xbox XMA2""; default: return ""*UNKNOWN*""; } } const char *ChannelDesc(DWORD dwChannelMask) { switch (dwChannelMask) { case 0x00000004 /*SPEAKER_MONO*/: return ""Mono""; case 0x00000003 /* SPEAKER_STEREO */: return ""Stereo""; case 0x0000000B /* SPEAKER_2POINT1 */: return ""2.1""; case 0x00000107 /* SPEAKER_SURROUND */: return ""Surround""; case 0x00000033 /* SPEAKER_QUAD */: return ""Quad""; case 0x0000003B /* SPEAKER_4POINT1 */: return ""4.1""; case 0x0000003F /* SPEAKER_5POINT1 */: return ""5.1""; case 0x000000FF /* SPEAKER_7POINT1 */: return ""7.1""; case 0x0000060F /* SPEAKER_5POINT1_SURROUND */: return ""Surround5.1""; case 0x0000063F /* SPEAKER_7POINT1_SURROUND */: return ""Surround7.1""; default: return ""Custom""; } } void PrintInfo(const WaveFile& wave) { if (wave.data.wfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE && (wave.data.wfx->cbSize >= (sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)))) { auto wext = reinterpret_cast(&wave.data.wfx); wprintf(L"" (%hs %u channels, %u-bit, %lu Hz, CMask:%hs)"", GetFormatTagName(wave.data.wfx->wFormatTag), wave.data.wfx->nChannels, wave.data.wfx->wBitsPerSample, wave.data.wfx->nSamplesPerSec, ChannelDesc(wext->dwChannelMask)); } else { wprintf(L"" (%hs %u channels, %u-bit, %lu Hz)"", GetFormatTagName(wave.data.wfx->wFormatTag), wave.data.wfx->nChannels, wave.data.wfx->wBitsPerSample, wave.data.wfx->nSamplesPerSec); } } } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------------------- // Entry-point //-------------------------------------------------------------------------------------- #ifdef _PREFAST_ #pragma prefast(disable : 28198, ""Command-line tool, frees all memory on exit"") #endif int __cdecl wmain(_In_ int argc, _In_z_count_(argc) wchar_t* argv[]) { // Parameters and defaults wchar_t szOutputFile[MAX_PATH] = {}; wchar_t szHeaderFile[MAX_PATH] = {}; ScopedHandle hFile; // Process command line DWORD dwOptions = 0; std::list conversion; for (int iArg = 1; iArg < argc; iArg++) { PWSTR pArg = argv[iArg]; if (('-' == pArg[0]) || ('/' == pArg[0])) { pArg++; PWSTR pValue; for (pValue = pArg; *pValue && (':' != *pValue); pValue++); if (*pValue) *pValue++ = 0; DWORD dwOption = LookupByName(pArg, g_pOptions); if (!dwOption || (dwOptions & (1 << dwOption))) { PrintUsage(); return 1; } dwOptions |= 1 << dwOption; // Handle options with additional value parameter switch (dwOption) { case OPT_OUTPUTFILE: case OPT_OUTPUTHEADER: case OPT_FILELIST: if (!*pValue) { if ((iArg + 1 >= argc)) { PrintUsage(); return 1; } iArg++; pValue = argv[iArg]; } break; } switch (dwOption) { case OPT_OUTPUTFILE: wcscpy_s(szOutputFile, MAX_PATH, pValue); break; case OPT_OUTPUTHEADER: wcscpy_s(szHeaderFile, MAX_PATH, pValue); break; case OPT_COMPACT: if (dwOptions & (1 << OPT_NOCOMPACT)) { wprintf(L""-c and -nc are mutually exclusive options\\n""); return 1; } break; case OPT_NOCOMPACT: if (dwOptions & (1 << OPT_COMPACT)) { wprintf(L""-c and -nc are mutually exclusive options\\n""); return 1; } break; case OPT_FILELIST: { std::wifstream inFile(pValue); if (!inFile) { wprintf(L""Error opening -flist file %ls\\n"", pValue); return 1; } wchar_t fname[1024] = {}; for (;;) { inFile >> fname; if (!inFile) break; if (*fname == L'#') { // Comment } else if (*fname == L'-') { wprintf(L""Command-line arguments not supported in -flist file\\n""); return 1; } else if (wcspbrk(fname, L""?*"") != nullptr) { wprintf(L""Wildcards not supported in -flist file\\n""); return 1; } else { SConversion conv = {}; wcscpy_s(conv.szSrc, MAX_PATH, fname); conversion.push_back(conv); } inFile.ignore(1000, '\\n'); } inFile.close(); } break; } } else if (wcspbrk(pArg, L""?*"") != nullptr) { size_t count = conversion.size(); SearchForFiles(pArg, conversion, (dwOptions & (1 << OPT_RECURSIVE)) != 0); if (conversion.size() <= count) { wprintf(L""No matching files found for %ls\\n"", pArg); return 1; } } else { SConversion conv = {}; wcscpy_s(conv.szSrc, MAX_PATH, pArg); conversion.push_back(conv); } } if (conversion.empty()) { wprintf(L""ERROR: Need at least 1 wave file to build wave bank\\n\\n""); PrintUsage(); return 0; } if (~dwOptions & (1 << OPT_NOLOGO)) PrintLogo(); // Determine output file name if (!*szOutputFile) { auto pConv = conversion.begin(); wchar_t ext[_MAX_EXT] = {}; wchar_t fname[_MAX_FNAME] = {}; _wsplitpath_s(pConv->szSrc, nullptr, 0, nullptr, 0, fname, _MAX_FNAME, ext, _MAX_EXT); if (_wcsicmp(ext, L"".xwb"") == 0) { wprintf(L""ERROR: Need to specify output file via -o\\n""); return 1; } _wmakepath_s(szOutputFile, nullptr, nullptr, fname, L"".xwb""); } if (dwOptions & (1 << OPT_TOLOWER)) { (void)_wcslwr_s(szOutputFile); if (*szHeaderFile) { (void)_wcslwr_s(szHeaderFile); } } if (~dwOptions & (1 << OPT_OVERWRITE)) { if (GetFileAttributesW(szOutputFile) != INVALID_FILE_ATTRIBUTES) { wprintf(L""ERROR: Output file %ls already exists, use -y to overwrite!\\n"", szOutputFile); return 1; } if (*szHeaderFile) { if (GetFileAttributesW(szHeaderFile) != INVALID_FILE_ATTRIBUTES) { wprintf(L""ERROR: Output header file %ls already exists!\\n"", szHeaderFile); return 1; } } } // Gather wave files std::unique_ptr entries; std::unique_ptr entryNames; std::vector waves; MINIWAVEFORMAT compactFormat = {}; bool xma = false; size_t index = 0; for (auto pConv = conversion.begin(); pConv != conversion.end(); ++pConv, ++index) { wchar_t ext[_MAX_EXT] = {}; wchar_t fname[_MAX_FNAME] = {}; _wsplitpath_s(pConv->szSrc, nullptr, 0, nullptr, 0, fname, _MAX_FNAME, ext, _MAX_EXT); // Load source image if (pConv != conversion.begin()) wprintf(L""\\n""); wprintf(L""reading %ls"", pConv->szSrc); fflush(stdout); WaveFile wave; wave.conv = index; std::unique_ptr waveData; HRESULT hr = DirectX::LoadWAVAudioFromFileEx(pConv->szSrc, waveData, wave.data); if (FAILED(hr)) { wprintf(L""\\nERROR: Failed to load file (%08X)\\n"", static_cast(hr)); return 1; } wave.waveData = std::move(waveData); PrintInfo(wave); if (wave.data.wfx->wFormatTag == WAVE_FORMAT_XMA2) xma = true; waves.emplace_back(std::move(wave)); } wprintf(L""\\n""); DWORD dwAlignment = ALIGNMENT_MIN; if (dwOptions & (1 << OPT_STREAMING)) dwAlignment = ALIGNMENT_DVD; else if (xma) dwAlignment = 2048; // Convert wave format to miniformat, failing if any won't map // Check to see if we can use the compact wave bank format bool compact = (dwOptions & (1 << OPT_NOCOMPACT)) ? false : true; int reason = 0; uint64_t waveOffset = 0; for (auto it = waves.begin(); it != waves.end(); ++it) { if (!ConvertToMiniFormat(it->data.wfx, it->data.seek != nullptr, it->miniFmt)) { auto cit = conversion.cbegin(); advance(cit, it->conv); wprintf(L""ERROR: Failed encoding %ls\\n"", cit->szSrc); return 1; } if (it == waves.begin()) { memcpy(&compactFormat, &it->miniFmt, sizeof(MINIWAVEFORMAT)); } else if (memcmp(&compactFormat, &it->miniFmt, sizeof(MINIWAVEFORMAT)) != 0) { compact = false; reason |= 0x1; } if (it->data.loopLength > 0) { compact = false; reason |= 0x2; } DWORD alignedSize = BLOCKALIGNPAD(it->data.audioBytes, dwAlignment); waveOffset += alignedSize; } if (waveOffset > UINT32_MAX) { wprintf(L""ERROR: Audio wave data is too large to encode into wavebank (offset %llu)"", waveOffset); return 1; } else if (waveOffset > (MAX_COMPACT_DATA_SEGMENT_SIZE * uint64_t(dwAlignment))) { compact = false; reason |= 0x4; } if ((dwOptions & (1 << OPT_COMPACT)) && !compact) { wprintf(L""ERROR: Cannot create compact wave bank:\\n""); if (reason & 0x1) { wprintf(L""- Mismatched formats. All formats must be identical for a compact wavebank.\\n""); } if (reason & 0x2) { wprintf(L""- Found loop points. Compact wavebanks do not support loop points.\\n""); } if (reason & 0x4) { wprintf(L""- Audio wave data is too large to encode in compact wavebank (%llu > %llu).\\n"", waveOffset, (uint64_t(MAX_COMPACT_DATA_SEGMENT_SIZE) * uint64_t(dwAlignment))); } return 1; } // Build entry metadata (and assign wave offset within data segment) // Build entry friendly names if requested entries.reset(new uint8_t[(compact ? sizeof(ENTRYCOMPACT) : sizeof(ENTRY)) * waves.size()]); if (dwOptions & (1 << OPT_FRIENDLY_NAMES)) { entryNames.reset(new char[waves.size() * ENTRYNAME_LENGTH]); memset(entryNames.get(), 0, sizeof(char) * waves.size() * ENTRYNAME_LENGTH); } waveOffset = 0; size_t count = 0; size_t seekEntries = 0; for (auto it = waves.begin(); it != waves.end(); ++it, ++count) { DWORD alignedSize = BLOCKALIGNPAD(it->data.audioBytes, dwAlignment); auto wfx = it->data.wfx; uint64_t duration = 0; switch (it->miniFmt.wFormatTag) { case MINIWAVEFORMAT::TAG_XMA: if (it->data.seekCount > 0) seekEntries += size_t(it->data.seekCount) + 1u; duration = reinterpret_cast(wfx)->SamplesEncoded; break; case MINIWAVEFORMAT::TAG_ADPCM: { auto adpcmFmt = reinterpret_cast(wfx); duration = (uint64_t(it->data.audioBytes) / uint64_t(wfx->nBlockAlign)) * uint64_t(adpcmFmt->wSamplesPerBlock); int partial = it->data.audioBytes % wfx->nBlockAlign; if (partial) { if (partial >= (7 * wfx->nChannels)) duration += (uint64_t(partial) * 2 / uint64_t(wfx->nChannels - 12)); } } break; case MINIWAVEFORMAT::TAG_WMA: if (it->data.seekCount > 0) { seekEntries += size_t(it->data.seekCount) + 1u; duration = it->data.seek[it->data.seekCount - 1] / uint32_t(2 * wfx->nChannels); } break; default: // MINIWAVEFORMAT::TAG_PCM duration = (uint64_t(it->data.audioBytes) * 8) / (uint64_t(wfx->wBitsPerSample) * uint64_t(wfx->nChannels)); break; } if (compact) { auto entry = reinterpret_cast(entries.get() + count * sizeof(ENTRYCOMPACT)); memset(entry, 0, sizeof(ENTRYCOMPACT)); assert(waveOffset <= (MAX_COMPACT_DATA_SEGMENT_SIZE * uint64_t(dwAlignment))); entry->dwOffset = uint32_t(waveOffset / dwAlignment); assert(dwAlignment <= 2048); entry->dwLengthDeviation = alignedSize - it->data.audioBytes; } else { auto entry = reinterpret_cast(entries.get() + count * sizeof(ENTRY)); memset(entry, 0, sizeof(ENTRY)); if (duration > 268435455) { wprintf(L""ERROR: Duration of audio too long to encode into wavebank (%llu > 2^28))\\n"", duration); return 1; } entry->Duration = uint32_t(duration); memcpy(&entry->Format, &it->miniFmt, sizeof(MINIWAVEFORMAT)); entry->PlayRegion.dwOffset = uint32_t(waveOffset); entry->PlayRegion.dwLength = it->data.audioBytes; if (it->data.loopLength > 0) { entry->LoopRegion.dwStartSample = it->data.loopStart; entry->LoopRegion.dwTotalSamples = it->data.loopLength; } } if (dwOptions & (1 << OPT_FRIENDLY_NAMES)) { auto cit = conversion.cbegin(); advance(cit, it->conv); wchar_t wEntryName[_MAX_FNAME] = {}; _wsplitpath_s(cit->szSrc, nullptr, 0, nullptr, 0, wEntryName, _MAX_FNAME, nullptr, 0); int result = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, wEntryName, -1, &entryNames[count * ENTRYNAME_LENGTH], ENTRYNAME_LENGTH, nullptr, nullptr); if (result <= 0) { memset(&entryNames[count * ENTRYNAME_LENGTH], 0, ENTRYNAME_LENGTH); } } waveOffset += alignedSize; } assert(count > 0 && count == waves.size()); // Create wave bank assert(*szOutputFile != 0); wprintf(L""writing %ls%ls wavebank %ls w/ %zu entries\\n"", (compact) ? L""compact "" : L"""", (dwOptions & (1 << OPT_STREAMING)) ? L""streaming"" : L""in-memory"", szOutputFile, waves.size()); fflush(stdout); hFile.reset(safe_handle(CreateFileW(szOutputFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr))); if (!hFile) { wprintf(L""ERROR: Failed opening output file %ls, %lu\\n"", szOutputFile, GetLastError()); return 1; } // Setup wave bank header HEADER header = {}; header.dwSignature = HEADER::SIGNATURE; header.dwHeaderVersion = HEADER::VERSION; header.dwVersion = XACT_CONTENT_VERSION; DWORD segmentOffset = sizeof(HEADER); // Write bank metadata assert((segmentOffset % 4) == 0); BANKDATA data = {}; data.dwEntryCount = uint32_t(waves.size()); data.dwAlignment = dwAlignment; GetSystemTimeAsFileTime(&data.BuildTime); data.dwFlags = (dwOptions & (1 << OPT_STREAMING)) ? BANKDATA::TYPE_STREAMING : BANKDATA::TYPE_BUFFER; if (seekEntries > 0) { data.dwFlags |= BANKDATA::FLAGS_SEEKTABLES; } if (dwOptions & (1 << OPT_FRIENDLY_NAMES)) { data.dwFlags |= BANKDATA::FLAGS_ENTRYNAMES; data.dwEntryNameElementSize = ENTRYNAME_LENGTH; } if (compact) { data.dwFlags |= BANKDATA::FLAGS_COMPACT; data.dwEntryMetaDataElementSize = sizeof(ENTRYCOMPACT); memcpy(&data.CompactFormat, &compactFormat, sizeof(MINIWAVEFORMAT)); } else { data.dwEntryMetaDataElementSize = sizeof(ENTRY); } { wchar_t wBankName[_MAX_FNAME] = {}; _wsplitpath_s(szOutputFile, nullptr, 0, nullptr, 0, wBankName, _MAX_FNAME, nullptr, 0); int result = WideCharToMultiByte(CP_UTF8, WC_NO_BEST_FIT_CHARS, wBankName, -1, data.szBankName, BANKDATA::BANKNAME_LENGTH, nullptr, nullptr); if (result <= 0) { memset(data.szBankName, 0, BANKDATA::BANKNAME_LENGTH); } } if (SetFilePointer(hFile.get(), LONG(segmentOffset), nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { wprintf(L""ERROR: Failed writing bank data to %ls, SFP %lu\\n"", szOutputFile, GetLastError()); return 1; } DWORD bytesWritten; if (!WriteFile(hFile.get(), &data, sizeof(data), &bytesWritten, nullptr) || bytesWritten != sizeof(data)) { wprintf(L""ERROR: Failed writing bank data to %ls, %lu\\n"", szOutputFile, GetLastError()); return 1; } header.Segments[HEADER::SEGIDX_BANKDATA].dwOffset = segmentOffset; header.Segments[HEADER::SEGIDX_BANKDATA].dwLength = sizeof(BANKDATA); segmentOffset += sizeof(BANKDATA); // Write entry metadata assert((segmentOffset % 4) == 0); if (SetFilePointer(hFile.get(), LONG(segmentOffset), nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { wprintf(L""ERROR: Failed writing entry metadata to %ls, SFP %lu\\n"", szOutputFile, GetLastError()); return 1; } uint32_t entryBytes = uint32_t(waves.size() * data.dwEntryMetaDataElementSize); if (!WriteFile(hFile.get(), entries.get(), entryBytes, &bytesWritten, nullptr) || bytesWritten != entryBytes) { wprintf(L""ERROR: Failed writing entry metadata to %ls, %lu\\n"", szOutputFile, GetLastError()); return 1; } header.Segments[HEADER::SEGIDX_ENTRYMETADATA].dwOffset = segmentOffset; header.Segments[HEADER::SEGIDX_ENTRYMETADATA].dwLength = entryBytes; segmentOffset += entryBytes; // Write seek tables assert((segmentOffset % 4) == 0); header.Segments[HEADER::SEGIDX_SEEKTABLES].dwOffset = segmentOffset; if (seekEntries > 0) { seekEntries += waves.size(); // Room for an offset per entry auto seekTables = std::make_unique(seekEntries); if (SetFilePointer(hFile.get(), LONG(segmentOffset), nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { wprintf(L""ERROR: Failed writing seek tables to %ls, SFP %lu\\n"", szOutputFile, GetLastError()); return 1; } uint32_t seekoffset = 0; uint32_t windex = 0; for (auto it = waves.begin(); it != waves.end(); ++it, ++windex) { if (it->miniFmt.wFormatTag == MINIWAVEFORMAT::TAG_WMA) { seekTables[windex] = seekoffset * sizeof(uint32_t); uint32_t baseoffset = uint32_t(waves.size() + seekoffset); seekTables[baseoffset] = it->data.seekCount; for (uint32_t j = 0; j < it->data.seekCount; ++j) { seekTables[size_t(baseoffset) + size_t(j) + 1u] = it->data.seek[j]; } seekoffset += size_t(it->data.seekCount) + 1u; } else if (it->miniFmt.wFormatTag == MINIWAVEFORMAT::TAG_XMA) { seekTables[windex] = seekoffset * sizeof(uint32_t); uint32_t baseoffset = uint32_t(waves.size() + seekoffset); seekTables[baseoffset] = it->data.seekCount; for (uint32_t j = 0; j < it->data.seekCount; ++j) { seekTables[size_t(baseoffset) + size_t(j) + 1u] = _byteswap_ulong(it->data.seek[j]); } seekoffset += it->data.seekCount + 1; } else { seekTables[windex] = uint32_t(-1); } } uint32_t seekLen = uint32_t(sizeof(uint32_t) * seekEntries); if (!WriteFile(hFile.get(), seekTables.get(), seekLen, &bytesWritten, nullptr) || bytesWritten != seekLen) { wprintf(L""ERROR: Failed writing seek tables to %ls, %lu\\n"", szOutputFile, GetLastError()); return 1; } segmentOffset += seekLen; header.Segments[HEADER::SEGIDX_SEEKTABLES].dwLength = seekLen; } else { header.Segments[HEADER::SEGIDX_SEEKTABLES].dwLength = 0; } // Write entry names if (dwOptions & (1 << OPT_FRIENDLY_NAMES)) { assert((segmentOffset % 4) == 0); if (SetFilePointer(hFile.get(), LONG(segmentOffset), nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { wprintf(L""ERROR: Failed writing friendly entry names to %ls, SFP %lu\\n"", szOutputFile, GetLastError()); return 1; } uint32_t entryNamesBytes = uint32_t(count * data.dwEntryNameElementSize); if (!WriteFile(hFile.get(), entryNames.get(), entryNamesBytes, &bytesWritten, nullptr) || bytesWritten != entryNamesBytes) { wprintf(L""ERROR: Failed writing friendly entry names to %ls, %lu\\n"", szOutputFile, GetLastError()); return 1; } header.Segments[HEADER::SEGIDX_ENTRYNAMES].dwOffset = segmentOffset; header.Segments[HEADER::SEGIDX_ENTRYNAMES].dwLength = entryNamesBytes; segmentOffset += entryNamesBytes; } // Write wave data segmentOffset = BLOCKALIGNPAD(segmentOffset, dwAlignment); header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwOffset = segmentOffset; header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwLength = uint32_t(waveOffset); for (auto it = waves.begin(); it != waves.end(); ++it) { if (SetFilePointer(hFile.get(), LONG(segmentOffset), nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { wprintf(L""ERROR: Failed writing audio data to %ls, SFP %lu\\n"", szOutputFile, GetLastError()); return 1; } if (!WriteFile(hFile.get(), it->data.startAudio, it->data.audioBytes, &bytesWritten, nullptr) || bytesWritten != it->data.audioBytes) { wprintf(L""ERROR: Failed writing audio data to %ls, %lu\\n"", szOutputFile, GetLastError()); return 1; } DWORD alignedSize = BLOCKALIGNPAD(it->data.audioBytes, dwAlignment); if ((uint64_t(segmentOffset) + alignedSize) > UINT32_MAX) { wprintf(L""ERROR: Data exceeds maximum size for wavebank\\n""); return 1; } segmentOffset += alignedSize; } assert(segmentOffset == (header.Segments[HEADER::SEGIDX_ENTRYWAVEDATA].dwOffset + waveOffset)); // Commit wave bank if (SetFilePointer(hFile.get(), LONG(segmentOffset), nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { wprintf(L""ERROR: Failed committing output file %ls, EOF %lu\\n"", szOutputFile, GetLastError()); return 1; } if (!SetEndOfFile(hFile.get())) { wprintf(L""ERROR: Failed committing output file %ls, EOF %lu\\n"", szOutputFile, GetLastError()); return 1; } if (SetFilePointer(hFile.get(), 0, nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { wprintf(L""ERROR: Failed committing output file %ls, HDR %lu\\n"", szOutputFile, GetLastError()); return 1; } if (!WriteFile(hFile.get(), &header, sizeof(header), &bytesWritten, nullptr) || bytesWritten != sizeof(header)) { wprintf(L""ERROR: Failed committing output file %ls, HDR %lu\\n"", szOutputFile, GetLastError()); return 1; } // Write C header if requested if (*szHeaderFile) { wprintf(L""writing C header %ls\\n"", szHeaderFile); fflush(stdout); FILE* file = nullptr; if (!_wfopen_s(&file, szHeaderFile, L""wt"")) { wchar_t wBankName[_MAX_FNAME] = {}; _wsplitpath_s(szOutputFile, nullptr, 0, nullptr, 0, wBankName, _MAX_FNAME, nullptr, 0); FileNameToIdentifier(wBankName, _MAX_FNAME); fprintf_s(file, ""#pragma once\\n\\nenum XACT_WAVEBANK_%ls : unsigned int\\n{\\n"", wBankName); size_t windex = 0; for (auto it = waves.begin(); it != waves.end(); ++it, ++windex) { auto cit = conversion.cbegin(); advance(cit, it->conv); wchar_t wEntryName[_MAX_FNAME] = {}; _wsplitpath_s(cit->szSrc, nullptr, 0, nullptr, 0, wEntryName, _MAX_FNAME, nullptr, 0); FileNameToIdentifier(wEntryName, _MAX_FNAME); fprintf_s(file, "" XACT_WAVEBANK_%ls_%ls = %zu,\\n"", wBankName, wEntryName, windex); } fprintf_s(file, ""};\\n\\n#define XACT_WAVEBANK_%ls_ENTRY_COUNT %zu\\n"", wBankName, count); fclose(file); } else { wprintf(L""ERROR: Failed writing wave bank C header %ls\\n"", szHeaderFile); return 1; } } return 0; } ",16187,True,2600.2123628278605,median "/* * Copyright (C) 2020 Open Source Robotics Foundation * * 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. * */ #include #include ""ConnectionHelper.hh"" std::map> subt::ConnectionHelper::connectionPoints = { {""Constrained Tunnel Tile Short"", {{0, -10, 0}, {0, 10, 0}}}, {""Constrained Tunnel Tile Tall"", {{0, -10, 0}, {0, 10, 0}}}, {""Tunnel Bend Right"", {{0, 0, 0}, {15, 25, 0}}}, {""Tunnel Corner Left"", {{0, 0, 0}, {-10, 15, 0}}}, {""Tunnel Corner Right"", {{0, 0, 0}, {10, 15, 0}}}, {""Tunnel Elevation"", {{0, 0, 0}, {0, 20, 5}}}, {""Tunnel Intersection"", {{0, 0, 0}, {7.5, 7.5, 0}, {-7.5, 7.5, 0}, {0, 15, 0}}}, {""Tunnel Intersection T"", {{0, 0, 0}, {7.5, 7.5, 0}, {-7.5, 7.5, 0}}}, {""Tunnel Straight"", {{0, 0, 0}, {0, 5, 0}}}, {""subt_tunnel_staging_area"", {{10, 0, 0}}}, {""Tunnel Tile 1"", {{0.0, 10.0, 0.0}, {10.0, 0.0, 0.0}, {0.0, -10.0, 0.0}, {-10.0, 0.0, 0.0}}}, {""Tunnel Tile 1 Lights"", {{0.0, 10.0, 0.0}, {10.0, 0.0, 0.0}, {0.0, -10.0, 0.0}, {-10.0, 0.0, 0.0}}}, {""Tunnel Tile 2"", {{10, 0, 0}, {0, -10, 0}}}, {""Tunnel Tile 2 Lights"", {{10, 0, 0}, {0, -10, 0}}}, {""Tunnel Tile 3"", {{0.0, 10.0, 0.0}, {10.0, 0.0, 0.0}, {0.0, -10.0, 0.0}, {-10.0, 0.0, 0.0}}}, {""Tunnel Tile 3 Lights"", {{0.0, 10.0, 0.0}, {10.0, 0.0, 0.0}, {0.0, -10.0, 0.0}, {-10.0, 0.0, 0.0}}}, {""Tunnel Tile 4"", {{0.0, 10.0, 0.0}, {10.0, 0.0, 0.0}, {0.0, -10.0, 0.0}, {-10.0, 0.0, 0.0}}}, {""Tunnel Tile 4 Lights"", {{0.0, 10.0, 0.0}, {10.0, 0.0, 0.0}, {0.0, -10.0, 0.0}, {-10.0, 0.0, 0.0}}}, {""Tunnel Tile 5"", {{0, -10, 0}, {0, 10, 0}}}, {""Tunnel Tile 5 Lights"", {{0, -10, 0}, {0, 10, 0}}}, {""Tunnel Tile 6"", {{0, -10, 0}, {0, 10, 5}}}, {""Tunnel Tile 6 Lights"", {{0, -10, 0}, {0, 10, 5}}}, {""Tunnel Tile 7"", {{0, -10, 0}, {0, 10, 5}}}, {""Tunnel Tile 7 Lights"", {{0, -10, 0}, {0, 10, 5}}}, {""Rough Tunnel Tile 90-degree Turn"", {{0, -10, 0}, {10, 0, 0}}}, {""Rough Tunnel Tile 90-degree Turn Lights"", {{0, -10, 0}, {10, 0, 0}}}, {""Rough Tunnel Tile Ramp"", {{0, -10, 0}, {0, 10, 5}}}, {""Rough Tunnel Tile Ramp Lights"", {{0, -10, 0}, {0, 10, 5}}}, {""Rough Tunnel Tile Straight"", {{0, -10, 0}, {0, 10, 0}}}, {""Rough Tunnel Tile Straight Lights"", {{0, -10, 0}, {0, 10, 0}}}, {""Rough Tunnel Tile Vertical Shaft"", {{0, -10, 0}, {0, 10, 5}}}, {""Rough Tunnel Tile 4-way Intersection"", {{0, -10, 0}, {0, 10, 0}, {10, 0, 0}, {-10, 0, 0}}}, {""Rough Tunnel Tile 4-way Intersection Lights"", {{0, -10, 0}, {0, 10, 0}, {10, 0, 0}, {-10, 0, 0}}}, {""Urban Straight"", {{0, 20, 0}, {0, -20, 0}}}, {""Urban Straight Lights"", {{0, 20, 0}, {0, -20, 0}}}, {""Urban Bend Right"", {{0, -20, 0}, {20, 0, 0}}}, {""Urban Bend Left"", {{0, -20, 0}, {-20, 0, 0}}}, {""Urban Bend Left Lights"", {{0, -20, 0}, {-20, 0, 0}}}, {""Urban Bend Mixed"", {{0, -20, 0}, {20, 0, 0}}}, {""Urban Superpose"", {{0, 20, 0}, {0, -20, 0}, {-20, 0, 10}, {20, 0, 10}}}, {""Urban 3-Way Right Intersection"", {{0, 20, 0}, {0, -20, 0}, {20, 0, 0}}}, {""Urban 4way Intersection"", {{0, -10, 0}, {0, 10, 0}, {10, 0, 0}, {-10, 0, 0}}}, {""Urban Straight Door Right"", {{20, 0, 0}, {-20, 0, 0}, {-16.021, 3.94, 0.94}}}, {""Urban Straight Door Left"", {{20, 0, 0}, {-20, 0, 0}, {-16.021, -3.94, 0.94}}}, {""Urban Straight Door Right Flipped"", {{20, 0, 0}, {-20, 0, 0}, {-16.021, 3.94, 0.94}}}, {""Urban Straight Door Right Flipped Lights"", {{20, 0, 0}, {-20, 0, 0}, {-16.021, 3.94, 0.94}}}, {""Urban Straight Door Left Flipped"", {{20, 0, 0}, {-20, 0, 0}, {-16.021, -3.94, 0.94}}}, {""Urban Straight Door Left Extension"", {{20, 0, 0}, {-20, 0, 0}, {0, -20, 0}}}, {""Urban Straight Door Right Extension"", {{20, 0, 0}, {-20, 0, 0}, {0, 20, 0}}}, {""Urban Straight Door Right Extension Lights"", {{20, 0, 0}, {-20, 0, 0}, {0, 20, 0}}}, {""Urban Service Room Centered"", {{0, 20, 0}}}, {""Urban Service Room Centered Lights"", {{0, 20, 0}}}, {""Urban Service Room"", {{-16.023, 3.906, 0.919}}}, {""Urban Service Room Lights"", {{-16.023, 3.906, 0.919}}}, {""Urban Service Room Straight"", {{0, -20, 0}, {0, 20, 0}}}, {""Urban Service Room Straight Lights"", {{0, -20, 0}, {0, 20, 0}}}, {""Urban Platform"", {{20, 0, 0}, {-20, 0, 0}, {0, 20, 1.7}, {23.979, 3.906, 0.94}, {-23.979, 3.906, 0.94}}}, {""Urban Platform Open"", {{20, 0, 0}, {-20, 0, 0}, {0, 20, 0}, {23.979, 3.906, 0.919}, {-23.979, 3.906, 0.919}, {23.982, 11.743, 0.919}}}, {""Urban Stairwell Platform"", {{0, 20, 11.69}, {0, -20, 1.69}}}, {""Urban Stairwell Platform Lights"", {{0, 20, 11.69}, {0, -20, 1.69}}}, {""Urban Stairwell Platform Centered"", {{0, 20, 10}, {0, -20, 0}}}, {""Urban Stairwell Platform Centered Lights"", {{0, 20, 10}, {0, -20, 0}}}, {""Urban Starting Area"", {{-16.021, 3.94, 0.919}}}, {""Urban Elevation Up"", {{0, 20, 5}, {0, -20, 0}}}, {""Urban Elevation Up Lights"", {{0, 20, 5}, {0, -20, 0}}}, {""Urban Elevation Down"", {{0, 20, 0}, {0, -20, 5}}}, {""Urban 2 Story"", {{0, 20, 10}, {0, -20, 0}, {-20, 0, 10}, {20, 0, 0}}}, {""Urban 2 Story Lights"", {{0, 20, 10}, {0, -20, 0}, {-20, 0, 10}, {20, 0, 0}}}, {""Urban 2 Story Large Side 1 Lights"", {{0, 20, 10}, {0, -20, 0}}}, {""Urban 2 Story Large Side 2 Lights"", {{0, -20, 0}, {0, 20, 0}}}, {""Urban 2 Story Large Side 1"", {{0, 20, 10}, {0, -20, 0}}}, {""Urban 2 Story Large Side 2"", {{0, -20, 0}, {0, 20, 0}}}, {""Urban Large Room Split"", {{0, -20, 0}, {-20, 0, 0}, {0, 20, 0}}}, {""Urban Large Room Split Lights"", {{0, -20, 0}, {-20, 0, 0}, {0, 20, 0}}}, {""Cave Starting Area Type B"", {{12.5, 0, 0}}}, {""Cave Straight 01"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 01 Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 01 Lights Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 02 Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 02 Lights Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 03 Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 04 Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 04 Lights Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 05 Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Straight 05 Lights Type B"", {{0, 12.5, 0}, {0, -12.5, 0}}}, {""Cave Corner 01 Type B"", {{-12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave Corner 01 Lights Type B"", {{-12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave Corner 02 Type B"", {{-12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave Corner 02 Lights Type B"", {{-12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave 3 Way 01 Type B"", {{12.5, 0, 0}, {-12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave 3 Way 01 Lights Type B"", {{12.5, 0, 0}, {-12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave Elevation Type B"", {{0, 12.5, 0}, {0, -12.5, 10}}}, {""Cave Elevation Lights Type B"", {{0, 12.5, 0}, {0, -12.5, 10}}}, {""Cave Vertical Shaft Type B"", {{0, 12.5, 20}, {0, -12.5, 0}}}, {""Cave Vertical Shaft Lights Type B"", {{0, 12.5, 20}, {0, -12.5, 0}}}, {""Cave Cavern Split 01 Type B"", {{0, 25, 25}, {12.5, 0, 0}, {-12.5, 0, 0}}}, {""Cave Cavern Split 02 Type B"", {{12.5, 0, 0}, {-12.5, 0, 0}}}, {""Cave Corner 30 Type B"", {{12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave Corner 30F Type B"", {{-12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave Corner 30 D Type B"", {{12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave Corner 30 D Lights Type B"", {{12.5, 0, 0}, {0, 12.5, 0}}}, {""Cave Corner 30F D Type B"", {{12.5, 0, 0}, {0, -12.5, 0}}}, {""Cave Corner 30F D Lights Type B"", {{12.5, 0, 0}, {0, -12.5, 0}}}, {""Cave 2 Way 01 Type A"", {{-25.0, 0.0, 0.0}, {25.0, 0.0, 0.0}}}, {""Cave 3 Way 01 Type A"", {{0.0, -25.0, 0.0}, {-25.0, 50.0, 0.0}, {50.0, 25.0, 0.0}}}, {""Cave 3 Way 02 Type A"", {{-50.0, 25.0, 0.0}, {25.0, 50.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave 3 Way Elevation 01 Type A"", {{0.0, 50.0, 0.0}, {-100.0, -50.0, -25.0}, {0.0, -50.0, -25.0}}}, {""Cave 3 Way Elevation 02 Type A"", {{0.0, -50.0, 0.0}, {-100.0, -50.0, -25.0}, {0.0, 50.0, 0.0}}}, {""Cave 3 Way Elevation 03 Type A"", {{0.0, 50.0, 75.0}, {50.0, 0.0, -50.0}, {0.0, -50.0, 0.0}}}, {""Cave 4 Way 01 Type A"", {{0.0, 25.0, 0.0}, {25.0, 0.0, 0.0}, {0.0, -25.0, 0.0}, {-25.0, 0.0, 0.0}}}, {""Cave Cavern Type A"", {{-25.0, 0.0, 25.0}, {25.0, 0.0, 25.0}, {0.0, 25.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave Corner 01 Type A"", {{25.0, 0.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave Corner 02 Type A"", {{0.0, 25.0, 0.0}, {25.0, -50.0, 0.0}}}, {""Cave Corner 03 Type A"", {{-25.0, 0.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave Corner 03 Type A Lights"", {{-25.0, 0.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave Corner 04 Type A"", {{0.0, 50.0, 25.0}, {-50.0, -50.0, 0.0}}}, {""Cave Cap Type A"", {{0.0, 0.0, 0.0}}}, {""Cave Elevation 01 Type A"", {{0.0, -50.0, 0.0}, {0.0, 50.0, 75.0}}}, {""Cave Elevation 02 Type A"", {{-50.0, 0.0, 75.0}, {50.0, 0.0, 0.0}}}, {""Cave Elevation Corner Type A"", {{25.0, 75.0, 25.0}, {0.0, -100.0, 0.0}}}, {""Cave Elevation Straight Type A"", {{0.0, 50.0, 25.0}, {0.0, -50.0, 0.0}}}, {""Cave Split Type A"", {{0.0, -50.0, 0.0}, {0.0, 50.0, 0.0}}}, {""Cave Straight Shift Type A"", {{-25.0, 25.0, 0.0}, {25.0, -25.0, 0.0}}}, {""Cave Straight Type A"", {{0.0, 25.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave U Turn 01 Type A"", {{-25.0, -25.0, 0.0}, {25.0, -25.0, 0.0}}}, {""Cave U Turn Elevation Type A"", {{-50.0, -25.0, 0.0}, {0.0, -25.0, 25.0}}}, {""Cave Vertical Shaft Cantilevered Type A"", {{0.0, -5.46392e-07, 10.0}, {0.0, 50.0, 25.0}}}, {""Cave Vertical Shaft Straight Bottom Type A"", {{0.0, 0.0, 10.0}, {0.0, 25.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave Vertical Shaft Straight Top Type A"", {{0.0, 25.0, 0.0}, {0.0, -25.0, 0.0}, {0.0, 0.0, 0.0}}}, {""Cave Vertical Shaft Type A"", {{0.0, 0.0, 10.0}, {0.0, 0.0, 25.0}}}, {""Cave Vertical Shaft Dead End Type A"", {{0.0, 0.0, 10.0}}}, {""Cave 3 Way Elevation 02 Lights Type A"", {{0.0, -50.0, 0.0}, {-100.0, -50.0, -25.0}, {0.0, 50.0, 0.0}}}, {""Cave 4 Way 01 Lights Type A"", {{0.0, 25.0, 0.0}, {25.0, 0.0, 0.0}, {0.0, -25.0, 0.0}, {-25.0, 0.0, 0.0}}}, {""Cave Corner 01 Lights Type A"", {{25.0, 0.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave Corner 02 Lights Type A"", {{0.0, 25.0, 0.0}, {25.0, -50.0, 0.0}}}, {""Cave Corner 04 Lights Type A"", {{0.0, 50.0, 25.0}, {-50.0, -50.0, 0.0}}}, {""Cave Elevation Straight Lights Type A"", {{0.0, 50.0, 25.0}, {0.0, -50.0, 0.0}}}, {""Cave Straight Lights Type A"", {{0.0, 25.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave U Turn Elevation Lights Type A"", {{-50.0, -25.0, 0.0}, {0.0, -25.0, 25.0}}}, {""Cave Vertical Shaft Straight Bottom Lights Type A"", {{0.0, 0.0, 10.0}, {0.0, 25.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave Transition Type A to and from Type B"", {{0.0, 25.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Cave Transition Type A to and from Type B Lights"", {{0.0, 25.0, 0.0}, {0.0, -25.0, 0.0}}}, {""Jenolan Section 01"", {{401.144, 13.2017, 63.5658}}}, {""Jenolan Section 02"", {{401.144, 13.2017, 63.5658}, {231.676, 5.12208, 83.5523}}}, {""Jenolan Section 03"", {{231.676, 5.12208, 83.5523}, {193.48, 39.2667, 62.0974}, {173.354, 3.1715, 83.8528}, {175.939, 15.8454, 74.7845}}}, {""Jenolan Section 04"", {{193.48, 39.2667, 62.0974}, {173.354, 3.1715, 83.8528}, {175.939, 15.8454, 74.7845}, {108.945, -.808552, 117.401}, {102.694, -4.59171, 47.6574}}}, {""Jenolan Section 05"", {{43.2806, -4.87545, 130.876}, {108.945, -.808552, 117.401}, {102.694, -4.59171, 47.6574}, {0, 0, 12.5}}}, {""Jenolan Section 06"", {{95.93, 26.3732, 146.106}, {90.7982, -7.84003, 167.789}, {-16.465, 17.3448, 159.529}, {43.2806, -4.87545, 130.876}}}, {""Jenolan Section 07"", {{95.93, 26.3732, 146.106}, {90.7982, -7.84003, 167.789}}}, {""Jenolan Section 08"", {{-82.6196, 39.5982, 140.961}, {-76.3975, 30.5907, 134.982}, {-71.9846, 10.5912, 139.379}, {-16.465, 17.3448, 159.529}}}, {""Jenolan Section 09"", {{-194.72, -9.770950, 132.04}, {-82.6196, 39.5982, 140.961}, {-76.3975, 30.5907, 134.982}, {-71.9846, 10.5912, 139.379}}}, {""Jenolan Section 10"", {{-264.458, 25.7639, 43.2923}, {-241.489, -6.8719, 112.301}, {-194.72, -9.770950, 132.04}}}, {""Jenolan Section 11"", {{-264.458, 25.7639, 43.2923}, {-241.489, -6.8719, 112.301}}}, {""Edgar Mine Virtual STIX Staging"", {{36.59, -98.89, 0.22}}}, {""Edgar Mine Virtual STIX 1"", {{-5.357750, -3.895970, 1.542500}, {14.732500, -54.425900, 1.309480}, {22.352600, -47.677800, 1.840880}, {36.688300, -99.091400, 0.502152}}}, {""Edgar Mine Virtual STIX 2"", {{-28.023300, -8.152720, 1.523010}, {-45.176900, -15.067200, 2.253390}, {-19.575200, -76.385600, 1.611400}, {6.422350, -64.002200, 1.529890}, {14.710200, -54.129700, 1.529890}}}, {""Edgar Mine Virtual STIX 3"", {{-19.323300, -76.383000, 1.596170}, {-57.390400, -91.166200, 0.836131}, {-43.042400, -105.988000, 1.170930}}}, {""Edgar Mine Virtual STIX 4"", {{-76.194300, -42.517800, 1.360100},{-57.313300, -90.930900, 0.757498}}}, {""Edgar Mine Virtual STIX 5"", {{-5.551090, -3.690460, 1.977060},{-10.253500, 4.161460, 1.977060},{-28.316800, -7.717830, 1.677650},{-45.286200, -14.888900, 2.101940},{-76.032100, -42.339900, 1.440770}}}, {""Edgar Mine Virtual STIX 6"", {{-10.134400, 4.764300, 1.700290}, {-21.417500, 20.110100, 1.645820}, {13.817500, 26.329800, 2.133420}, {61.013200, 34.655400, 2.746590}}}, {""Edgar Mine Virtual STIX 7"", {{-21.210300, 20.283600, 1.809090}, {-57.365300, 62.626300, 1.809090} ,{-58.171400, 76.645800, 1.761010}, {-24.210600, 97.656100, 13.359000}}}, {""Edgar Mine Virtual STIX 8"", {{13.824900, 26.428100, 2.063650}, {-24.076000, 97.654300, 12.870300}}}, {""Edgar Mine Virtual STIX 9"", {{69.842000, -14.046400, 2.208530}, {61.017200, 34.481600, 2.769580} ,{106.348000, 8.531670, 2.551910}}}, {""Edgar Mine Virtual STIX 10"", {{22.650300, -47.697300, 1.670630} ,{69.681400, -14.199900, 2.066190}, {106.374000, 8.160290, 2.428980}}}, {""Universal Straight 10"", {{0, 5, 0}, {0, -5, 0}}}, {""Universal Straight 5"", {{0, 2.5, 0}, {0, -2.5, 0}}}, {""Universal Straight 2.5"", {{0, 1.25, 0}, {0, -1.25, 0}}}, {""Universal Shift 5x5"", {{0, 2.5, 0}, {2.5, -2.5, 0}}}, {""Universal Shift 2.5x2.5"", {{0, 1.25, 0}, {1.25, -1.25, 0}}}, {""Cave Tunnel Transition"", {{0, 25, 0}, {0, -25, 0}, {-25, 0, 0}}}, {""Cave Tunnel Transition Lights"", {{0, 25, 0}, {0, -25, 0}, {-25, 0, 0}}}, {""Urban Cave Transition"", {{0, -12, 0}, {0, 12, 0}, {-25, 0, 0}}}, {""Urban Cave Transition Lights"", {{0, -12, 0}, {0, 12, 0}, {-25, 0, 0}}}, {""Urban Cave Transition 2"", {{0, -12, 0}, {0, 12, 0}, {-25, 0, 0}}}, {""Urban Cave Transition Straight"", {{0, -5, 0}, {0, 5, 0}}}, {""Urban Cave Transition Straight Large"", {{0, -5, 0}, {0, 5, 0}}}, {""Urban Cave Transition Straight Lights"", {{0, -5, 0}, {0, 5, 0}}}, {""Urban Tunnel Transition"", {{0, 0, 0}, {0, -15, -5}}}, {""Urban Tunnel Transition 2"", {{0, 0, 0}, {0, -15, -5}}}, {""Urban Tunnel Transition Straight"", {{0, -5, 0}, {0, 5, 0}}}, {""4-Way Finals Transition"", {{8, 0, 0}, {-8, 0, 0}, {0, 8, 0}, {0, -8, 0}}}, {""4-Way Finals Transition 2"", {{8, 0, 0}, {-8, 0, 0}, {0, 8, 0}, {0, -8, 0}}}, {""4-Way Finals Transition 2 Lights"", {{8, 0, 0}, {-8, 0, 0}, {0, 8, 0}, {0, -8, 0}}}, {""Finals Staging Area"", {{0, 5, 0}}}, {""NIOSH Staging Connector Finals"", {{0, 0, 0}, {-1, 6.5, 0}}}, }; std::map subt::ConnectionHelper::connectionTypes = { {""Constrained Tunnel Tile Short"", subt::ConnectionHelper::STRAIGHT}, {""Constrained Tunnel Tile Tall"", subt::ConnectionHelper::STRAIGHT}, {""Tunnel Bend Right"", subt::ConnectionHelper::TURN}, {""Tunnel Corner Left"", subt::ConnectionHelper::TURN}, {""Tunnel Corner Right"", subt::ConnectionHelper::TURN}, {""Tunnel Elevation"", subt::ConnectionHelper::STRAIGHT}, {""Tunnel Intersection"", subt::ConnectionHelper::TURN}, {""Tunnel Intersection T"", subt::ConnectionHelper::TURN}, {""Tunnel Straight"", subt::ConnectionHelper::STRAIGHT}, {""subt_tunnel_staging_area"", subt::ConnectionHelper::STRAIGHT}, {""Tunnel Tile 1"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 1 Lights"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 2"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 2 Lights"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 3"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 3 Lights"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 4"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 4 Lights"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 5"", subt::ConnectionHelper::STRAIGHT}, {""Tunnel Tile 5 Lights"", subt::ConnectionHelper::STRAIGHT}, {""Tunnel Tile 6"", subt::ConnectionHelper::STRAIGHT}, {""Tunnel Tile 6 Lights"", subt::ConnectionHelper::STRAIGHT}, {""Tunnel Tile 7"", subt::ConnectionHelper::TURN}, {""Tunnel Tile 7 Lights"", subt::ConnectionHelper::TURN}, {""Rough Tunnel Tile 90-degree Turn"", subt::ConnectionHelper::TURN}, {""Rough Tunnel Tile 90-degree Turn Lights"", subt::ConnectionHelper::TURN}, {""Rough Tunnel Tile Ramp"", subt::ConnectionHelper::STRAIGHT}, {""Rough Tunnel Tile Ramp Lights"", subt::ConnectionHelper::STRAIGHT}, {""Rough Tunnel Tile Straight"", subt::ConnectionHelper::STRAIGHT}, {""Rough Tunnel Tile Straight Lights"", subt::ConnectionHelper::STRAIGHT}, {""Rough Tunnel Tile Vertical Shaft"", subt::ConnectionHelper::STRAIGHT}, {""Rough Tunnel Tile 4-way Intersection"", subt::ConnectionHelper::TURN}, {""Rough Tunnel Tile 4-way Intersection Lights"", subt::ConnectionHelper::TURN}, {""Urban Straight"", subt::ConnectionHelper::STRAIGHT}, {""Urban Straight Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Bend Right"", subt::ConnectionHelper::TURN}, {""Urban Bend Left"", subt::ConnectionHelper::TURN}, {""Urban Bend Left Lights"", subt::ConnectionHelper::TURN}, {""Urban Bend Mixed"", subt::ConnectionHelper::TURN}, {""Urban Superpose"", subt::ConnectionHelper::TURN}, {""Urban 3-Way Right Intersection"", subt::ConnectionHelper::TURN}, {""Urban 4way Intersection"", subt::ConnectionHelper::TURN}, {""Urban Straight Door Right"", subt::ConnectionHelper::STRAIGHT}, {""Urban Straight Door Left"", subt::ConnectionHelper::STRAIGHT}, {""Urban Straight Door Right Flipped"", subt::ConnectionHelper::STRAIGHT}, {""Urban Straight Door Right Flipped Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Straight Door Left Flipped"", subt::ConnectionHelper::STRAIGHT}, {""Urban Straight Door Left Extension"", subt::ConnectionHelper::TURN}, {""Urban Straight Door Right Extension"", subt::ConnectionHelper::TURN}, {""Urban Straight Door Right Extension Lights"", subt::ConnectionHelper::TURN}, {""Urban Service Room Centered"", subt::ConnectionHelper::STRAIGHT}, {""Urban Service Room Centered Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Service Room"", subt::ConnectionHelper::STRAIGHT}, {""Urban Service Room Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Service Room Straight"", subt::ConnectionHelper::STRAIGHT}, {""Urban Service Room Straight Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Platform"", subt::ConnectionHelper::TURN}, {""Urban Platform Open"", subt::ConnectionHelper::TURN}, {""Urban Stairwell Platform"", subt::ConnectionHelper::STRAIGHT}, {""Urban Stairwell Platform Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Stairwell Platform Centered"", subt::ConnectionHelper::STRAIGHT}, {""Urban Stairwell Platform Centered Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Starting Area"", subt::ConnectionHelper::STRAIGHT}, {""Urban Elevation Up"", subt::ConnectionHelper::STRAIGHT}, {""Urban Elevation Up Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Elevation Down"", subt::ConnectionHelper::STRAIGHT}, {""Urban 2 Story"", subt::ConnectionHelper::TURN}, {""Urban 2 Story Lights"", subt::ConnectionHelper::TURN}, {""Urban 2 Story Large Side 1 Lights"", subt::ConnectionHelper::TURN}, {""Urban 2 Story Large Side 2 Lights"", subt::ConnectionHelper::TURN}, {""Urban 2 Story Large Side 1"", subt::ConnectionHelper::TURN}, {""Urban 2 Story Large Side 2"", subt::ConnectionHelper::TURN}, {""Urban Large Room Split"", subt::ConnectionHelper::TURN}, {""Urban Large Room Split Lights"", subt::ConnectionHelper::TURN}, {""Cave Starting Area Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 01 Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 01 Lights Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 02 Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 02 Lights Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 03 Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 04 Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 04 Lights Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 05 Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight 05 Lights Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Corner 01 Type B"", subt::ConnectionHelper::TURN}, {""Cave Corner 01 Lights Type B"", subt::ConnectionHelper::TURN}, {""Cave Corner 02 Type B"", subt::ConnectionHelper::TURN}, {""Cave Corner 02 Lights Type B"", subt::ConnectionHelper::TURN}, {""Cave 3 Way 01 Type B"", subt::ConnectionHelper::TURN}, {""Cave 3 Way 01 Lights Type B"", subt::ConnectionHelper::TURN}, {""Cave Elevation Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Elevation Lights Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Vertical Shaft Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Vertical Shaft Lights Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Cavern Split 01 Type B"", subt::ConnectionHelper::TURN}, {""Cave Cavern Split 02 Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Corner 30 Type B"", subt::ConnectionHelper::TURN}, {""Cave Corner 30F Type B"", subt::ConnectionHelper::TURN}, {""Cave Corner 30 D Type B"", subt::ConnectionHelper::TURN}, {""Cave Corner 30 D Lights Type B"", subt::ConnectionHelper::TURN}, {""Cave Corner 30F D Type B"", subt::ConnectionHelper::TURN}, {""Cave Corner 30F D Lights Type B"", subt::ConnectionHelper::TURN}, {""Cave 2 Way 01 Type A"", subt::ConnectionHelper::STRAIGHT}, {""Cave 3 Way 01 Type A"", subt::ConnectionHelper::TURN}, {""Cave 3 Way 02 Type A"", subt::ConnectionHelper::TURN}, {""Cave 3 Way Elevation 01 Type A"", subt::ConnectionHelper::TURN}, {""Cave 3 Way Elevation 02 Type A"", subt::ConnectionHelper::TURN}, {""Cave 3 Way Elevation 03 Type A"", subt::ConnectionHelper::TURN}, {""Cave 4 Way 01 Type A"", subt::ConnectionHelper::TURN}, {""Cave Cavern Type A"", subt::ConnectionHelper::TURN}, {""Cave Corner 01 Type A"", subt::ConnectionHelper::TURN}, {""Cave Corner 02 Type A"", subt::ConnectionHelper::TURN}, {""Cave Corner 03 Type A"", subt::ConnectionHelper::TURN}, {""Cave Corner 03 Type A Lights"", subt::ConnectionHelper::TURN}, {""Cave Corner 04 Type A"", subt::ConnectionHelper::TURN}, {""Cave Cap Type A"", subt::ConnectionHelper::TURN}, {""Cave Elevation 01 Type A"", subt::ConnectionHelper::STRAIGHT}, {""Cave Elevation 02 Type A"", subt::ConnectionHelper::STRAIGHT}, {""Cave Elevation Corner Type A"", subt::ConnectionHelper::TURN}, {""Cave Elevation Straight Type A"", subt::ConnectionHelper::TURN}, {""Cave Split Type A"", subt::ConnectionHelper::TURN}, {""Cave Straight Shift Type A"", subt::ConnectionHelper::STRAIGHT}, {""Cave Straight Type A"", subt::ConnectionHelper::STRAIGHT}, {""Cave U Turn 01 Type A"", subt::ConnectionHelper::TURN}, {""Cave U Turn Elevation Type A"", subt::ConnectionHelper::TURN}, {""Cave Vertical Shaft Cantilevered Type A"", subt::ConnectionHelper::TURN}, {""Cave Vertical Shaft Straight Bottom Type A"", subt::ConnectionHelper::TURN}, {""Cave Vertical Shaft Straight Top Type A"", subt::ConnectionHelper::TURN}, {""Cave Vertical Shaft Type A"", subt::ConnectionHelper::STRAIGHT}, {""Cave Vertical Shaft Dead End Type A"", subt::ConnectionHelper::STRAIGHT}, {""Cave 3 Way Elevation 02 Lights Type A"", subt::ConnectionHelper::TURN}, {""Cave 4 Way 01 Lights Type A"", subt::ConnectionHelper::TURN}, {""Cave Corner 01 Lights Type A"", subt::ConnectionHelper::TURN}, {""Cave Corner 02 Lights Type A"", subt::ConnectionHelper::TURN}, {""Cave Corner 04 Lights Type A"", subt::ConnectionHelper::TURN}, {""Cave Elevation Straight Lights Type A"", subt::ConnectionHelper::TURN}, {""Cave Straight Lights Type A"", subt::ConnectionHelper::STRAIGHT}, {""Cave U Turn Elevation Lights Type A"", subt::ConnectionHelper::TURN}, {""Cave Vertical Shaft Straight Bottom Lights Type A"", subt::ConnectionHelper::TURN}, {""Cave Transition Type A to and from Type B"", subt::ConnectionHelper::STRAIGHT}, {""Cave Transition Type A to and from Type B Lights"", subt::ConnectionHelper::STRAIGHT}, {""Jenolan Section 01"", subt::ConnectionHelper::TURN}, {""Jenolan Section 02"", subt::ConnectionHelper::TURN}, {""Jenolan Section 03"", subt::ConnectionHelper::TURN}, {""Jenolan Section 04"", subt::ConnectionHelper::TURN}, {""Jenolan Section 05"", subt::ConnectionHelper::TURN}, {""Jenolan Section 06"", subt::ConnectionHelper::TURN}, {""Jenolan Section 07"", subt::ConnectionHelper::TURN}, {""Jenolan Section 08"", subt::ConnectionHelper::TURN}, {""Jenolan Section 09"", subt::ConnectionHelper::TURN}, {""Jenolan Section 10"", subt::ConnectionHelper::TURN}, {""Jenolan Section 11"", subt::ConnectionHelper::TURN}, {""Edgar Mine Virtual STIX Staging"", subt::ConnectionHelper::STRAIGHT}, {""Edgar Mine Virtual STIX 1"", subt::ConnectionHelper::STRAIGHT}, {""Edgar Mine Virtual STIX 2"", subt::ConnectionHelper::TURN}, {""Edgar Mine Virtual STIX 3"", subt::ConnectionHelper::TURN}, {""Edgar Mine Virtual STIX 4"", subt::ConnectionHelper::TURN}, {""Edgar Mine Virtual STIX 5"", subt::ConnectionHelper::STRAIGHT}, {""Edgar Mine Virtual STIX 6"", subt::ConnectionHelper::STRAIGHT}, {""Edgar Mine Virtual STIX 7"", subt::ConnectionHelper::TURN}, {""Edgar Mine Virtual STIX 8"", subt::ConnectionHelper::TURN}, {""Edgar Mine Virtual STIX 9"", subt::ConnectionHelper::TURN}, {""Edgar Mine Virtual STIX 10"", subt::ConnectionHelper::STRAIGHT}, {""Universal Straight 10"", subt::ConnectionHelper::STRAIGHT}, {""Universal Straight 5"", subt::ConnectionHelper::STRAIGHT}, {""Universal Straight 2.5"", subt::ConnectionHelper::STRAIGHT}, {""Universal Shift 5x5"", subt::ConnectionHelper::STRAIGHT}, {""Universal Shift 2.5x2.5"", subt::ConnectionHelper::STRAIGHT}, {""Cave Tunnel Transition"", subt::ConnectionHelper::STRAIGHT}, {""Cave Tunnel Transition Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Cave Transition"", subt::ConnectionHelper::STRAIGHT}, {""Urban Cave Transition Lights"", subt::ConnectionHelper::STRAIGHT}, {""Urban Cave Transition 2"", subt::ConnectionHelper::STRAIGHT}, {""Urban Cave Transition Straight"", subt::ConnectionHelper::STRAIGHT}, {""Urban Cave Transition Straight Large"", subt::ConnectionHelper::STRAIGHT}, {""Urban Tunnel Transition Straight"", subt::ConnectionHelper::STRAIGHT}, {""Urban Tunnel Transition"", subt::ConnectionHelper::STRAIGHT}, {""Urban Tunnel Transition 2"", subt::ConnectionHelper::STRAIGHT}, {""Finals Staging Area"", subt::ConnectionHelper::STRAIGHT}, {""4-Way Finals Transition"", subt::ConnectionHelper::TURN}, {""4-Way Finals Transition 2"", subt::ConnectionHelper::TURN}, {""4-Way Finals Transition 2 Lights"", subt::ConnectionHelper::TURN}, {""NIOSH Staging Connector Finals"", subt::ConnectionHelper::STRAIGHT}, }; std::map subt::ConnectionHelper::circuitTypes = { {""Constrained Tunnel Tile Short"", subt::ConnectionHelper::TUNNEL}, {""Constrained Tunnel Tile Tall"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Bend Right"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Corner Left"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Corner Right"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Elevation"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Intersection"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Intersection T"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Straight"", subt::ConnectionHelper::TUNNEL}, {""subt_tunnel_staging_area"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 1"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 1 Lights"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 2"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 2 Lights"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 3"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 3 Lights"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 4"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 4 Lights"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 5"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 5 Lights"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 6"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 6 Lights"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 7"", subt::ConnectionHelper::TUNNEL}, {""Tunnel Tile 7 Lights"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile 90-degree Turn"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile 90-degree Turn Lights"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile Ramp"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile Ramp Lights"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile Straight"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile Straight Lights"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile Vertical Shaft"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile 4-way Intersection"", subt::ConnectionHelper::TUNNEL}, {""Rough Tunnel Tile 4-way Intersection Lights"", subt::ConnectionHelper::TUNNEL}, {""Urban Straight"", subt::ConnectionHelper::URBAN}, {""Urban Straight Lights"", subt::ConnectionHelper::URBAN}, {""Urban Bend Right"", subt::ConnectionHelper::URBAN}, {""Urban Bend Left"", subt::ConnectionHelper::URBAN}, {""Urban Bend Left Lights"", subt::ConnectionHelper::URBAN}, {""Urban Superpose"", subt::ConnectionHelper::URBAN}, {""Urban 3-Way Right Intersection"", subt::ConnectionHelper::URBAN}, {""Urban Straight Door Right"", subt::ConnectionHelper::URBAN}, {""Urban Straight Door Left"", subt::ConnectionHelper::URBAN}, {""Urban Straight Door Right Flipped"", subt::ConnectionHelper::URBAN}, {""Urban Straight Door Right Flipped Lights"", subt::ConnectionHelper::URBAN}, {""Urban Straight Door Left Flipped"", subt::ConnectionHelper::URBAN}, {""Urban Straight Door Right Extension"", subt::ConnectionHelper::URBAN}, {""Urban Straight Door Right Extension Lights"", subt::ConnectionHelper::URBAN}, {""Urban Service Room Centered"", subt::ConnectionHelper::URBAN}, {""Urban Service Room Centered Lights"", subt::ConnectionHelper::URBAN}, {""Urban Service Room"", subt::ConnectionHelper::URBAN}, {""Urban Service Room Lights"", subt::ConnectionHelper::URBAN}, {""Urban Service Room Straight"", subt::ConnectionHelper::URBAN}, {""Urban Service Room Straight Lights"", subt::ConnectionHelper::URBAN}, {""Urban Platform"", subt::ConnectionHelper::URBAN}, {""Urban Platform Open"", subt::ConnectionHelper::URBAN}, {""Urban Stairwell Platform"", subt::ConnectionHelper::URBAN}, {""Urban Stairwell Platform Lights"", subt::ConnectionHelper::URBAN}, {""Urban Stairwell Platform Centered"", subt::ConnectionHelper::URBAN}, {""Urban Stairwell Platform Centered Lights"", subt::ConnectionHelper::URBAN}, {""Urban Starting Area"", subt::ConnectionHelper::URBAN}, {""Urban Elevation Up"", subt::ConnectionHelper::URBAN}, {""Urban Elevation Up Lights"", subt::ConnectionHelper::URBAN}, {""Urban Elevation Down"", subt::ConnectionHelper::URBAN}, {""Urban 2 Story"", subt::ConnectionHelper::URBAN}, {""Urban 2 Story Lights"", subt::ConnectionHelper::URBAN}, {""Urban 2 Story Large Side 1 Lights"", subt::ConnectionHelper::URBAN}, {""Urban 2 Story Large Side 2 Lights"", subt::ConnectionHelper::URBAN}, {""Urban 2 Story Large Side 1"", subt::ConnectionHelper::URBAN}, {""Urban 2 Story Large Side 2"", subt::ConnectionHelper::URBAN}, {""Urban Large Room Split"", subt::ConnectionHelper::URBAN}, {""Urban Large Room Split Lights"", subt::ConnectionHelper::URBAN}, {""Urban Straight Door Left Extension"", subt::ConnectionHelper::URBAN}, {""Urban Bend Mixed"", subt::ConnectionHelper::URBAN}, {""Cave Starting Area Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 01"", subt::ConnectionHelper::CAVE}, {""Cave Straight 01 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 01 Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 02 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 02 Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 03 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 04 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 04 Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 05 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Straight 05 Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 01 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 01 Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 02 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 02 Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave 3 Way 01 Type B"", subt::ConnectionHelper::CAVE}, {""Cave 3 Way 01 Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Elevation Type B"", subt::ConnectionHelper::CAVE}, {""Cave Elevation Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Vertical Shaft Type B"", subt::ConnectionHelper::CAVE}, {""Cave Vertical Shaft Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Cavern Split 01 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Cavern Split 02 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 30 Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 30F Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 30 D Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 30 D Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 30F D Type B"", subt::ConnectionHelper::CAVE}, {""Cave Corner 30F D Lights Type B"", subt::ConnectionHelper::CAVE}, {""Cave 2 Way 01 Type A"", subt::ConnectionHelper::CAVE}, {""Cave 3 Way 01 Type A"", subt::ConnectionHelper::CAVE}, {""Cave 3 Way 02 Type A"", subt::ConnectionHelper::CAVE}, {""Cave 3 Way Elevation 01 Type A"", subt::ConnectionHelper::CAVE}, {""Cave 3 Way Elevation 02 Type A"", subt::ConnectionHelper::CAVE}, {""Cave 3 Way Elevation 03 Type A"", subt::ConnectionHelper::CAVE}, {""Cave 4 Way 01 Type A"", subt::ConnectionHelper::CAVE}, {""Cave Cavern Type A"", subt::ConnectionHelper::CAVE}, {""Cave Corner 01 Type A"", subt::ConnectionHelper::CAVE}, {""Cave Corner 02 Type A"", subt::ConnectionHelper::CAVE}, {""Cave Corner 03 Type A"", subt::ConnectionHelper::CAVE}, {""Cave Corner 03 Type A Lights"", subt::ConnectionHelper::CAVE}, {""Cave Corner 04 Type A"", subt::ConnectionHelper::CAVE}, {""Cave Cap Type A"", subt::ConnectionHelper::CAVE}, {""Cave Elevation 01 Type A"", subt::ConnectionHelper::CAVE}, {""Cave Elevation 02 Type A"", subt::ConnectionHelper::CAVE}, {""Cave Elevation Corner Type A"", subt::ConnectionHelper::CAVE}, {""Cave Elevation Straight Type A"", subt::ConnectionHelper::CAVE}, {""Cave Split Type A"", subt::ConnectionHelper::CAVE}, {""Cave Straight Shift Type A"", subt::ConnectionHelper::CAVE}, {""Cave Straight Type A"", subt::ConnectionHelper::CAVE}, {""Cave U Turn 01 Type A"", subt::ConnectionHelper::CAVE}, {""Cave U Turn Elevation Type A"", subt::ConnectionHelper::CAVE}, {""Cave Vertical Shaft Cantilevered Type A"", subt::ConnectionHelper::CAVE}, {""Cave Vertical Shaft Straight Bottom Type A"", subt::ConnectionHelper::CAVE}, {""Cave Vertical Shaft Straight Top Type A"", subt::ConnectionHelper::CAVE}, {""Cave Vertical Shaft Type A"", subt::ConnectionHelper::CAVE}, {""Cave Vertical Shaft Dead End Type A"", subt::ConnectionHelper::CAVE}, {""Cave 3 Way Elevation 02 Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave 4 Way 01 Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave Corner 01 Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave Corner 02 Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave Corner 04 Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave Elevation Straight Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave Straight Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave U Turn Elevation Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave Vertical Shaft Straight Bottom Lights Type A"", subt::ConnectionHelper::CAVE}, {""Cave Transition Type A to and from Type B"", subt::ConnectionHelper::CAVE}, {""Cave Transition Type A to and from Type B Lights"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 01"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 02"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 03"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 04"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 05"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 06"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 07"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 08"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 09"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 10"", subt::ConnectionHelper::CAVE}, {""Jenolan Section 11"", subt::ConnectionHelper::CAVE}, {""Edgar Mine Virtual STIX Staging"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 1"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 2"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 3"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 4"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 5"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 6"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 7"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 8"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 9"", subt::ConnectionHelper::TUNNEL}, {""Edgar Mine Virtual STIX 10"", subt::ConnectionHelper::TUNNEL}, {""Universal Straight 10"", subt::ConnectionHelper::UNIVERSAL}, {""Universal Straight 5"", subt::ConnectionHelper::UNIVERSAL}, {""Universal Straight 2.5"", subt::ConnectionHelper::UNIVERSAL}, {""Universal Shift 5x5"", subt::ConnectionHelper::UNIVERSAL}, {""Universal Shift 2.5x2.5"", subt::ConnectionHelper::UNIVERSAL}, {""Cave Tunnel Transition"", subt::ConnectionHelper::TRANSITION}, {""Cave Tunnel Transition Lights"", subt::ConnectionHelper::TRANSITION}, {""Urban Cave Transition"", subt::ConnectionHelper::TRANSITION}, {""Urban Cave Transition Lights"", subt::ConnectionHelper::TRANSITION}, {""Urban Cave Transition Straight"", subt::ConnectionHelper::TRANSITION}, {""Urban Tunnel Transition"", subt::ConnectionHelper::TRANSITION}, {""Urban Tunnel Transition 2"", subt::ConnectionHelper::TRANSITION}, {""Urban Tunnel Transition Straight"", subt::ConnectionHelper::TRANSITION}, {""Finals Staging Area"", subt::ConnectionHelper::STAGING_AREA}, {""4-Way Finals Transition"", subt::ConnectionHelper::TRANSITION}, {""4-Way Finals Transition 2"", subt::ConnectionHelper::TRANSITION}, {""4-Way Finals Transition 2 Lights"", subt::ConnectionHelper::TRANSITION}, {""NIOSH Staging Connector Finals"", subt::ConnectionHelper::TRANSITION}, }; using namespace ignition; using namespace subt; ///////////////////////////////////////////////// bool ConnectionHelper::ComputePoint(VertexData *_tile1, VertexData *_tile2, ignition::math::Vector3d& _pt) { std::string conn1, conn2; for (const auto &connection : ConnectionHelper::connectionPoints) { if (ignition::common::lowercase(connection.first) == ignition::common::lowercase(_tile1->tileType)) { conn1 = connection.first; } if (ignition::common::lowercase(connection.first) == ignition::common::lowercase(_tile2->tileType)) { conn2 = connection.first; } } if (conn1.empty()) { ignwarn << ""No connection information for: "" << _tile1->tileType << std::endl; return false; } if (conn2.empty()) { ignwarn << ""No connection information for: "" << _tile2->tileType << std::endl; return false; } for (const auto& pt1 : ConnectionHelper::connectionPoints[conn1]) { auto pt1tf = _tile1->model.RawPose().CoordPositionAdd(pt1); for (const auto& pt2 : ConnectionHelper::connectionPoints[conn2]) { auto pt2tf = _tile2->model.RawPose().CoordPositionAdd(pt2); if (pt1tf.Equal(pt2tf, 1.5)) { _pt = pt1tf; return true; } } } ignwarn << ""Failed to connect: "" << _tile1->tileType << "" "" << _tile2->tileType << std::endl; for (const auto& pt1 : ConnectionHelper::connectionPoints[conn1]) { auto pt1tf = _tile1->model.RawPose().CoordPositionAdd(pt1); for (const auto& pt2 : ConnectionHelper::connectionPoints[conn2]) { auto pt2tf = _tile2->model.RawPose().CoordPositionAdd(pt2); igndbg << _tile1->tileType << "" ["" << _tile1->model.RawPose() << ""] -- "" << _tile2->tileType << "" ["" << _tile2->model.RawPose() << ""]"" << "" ["" << pt1tf << ""] ["" << pt2tf << ""]"" << std::endl; } } return false; } ///////////////////////////////////////////////// std::vector ConnectionHelper::GetConnectionPoints(VertexData *_tile1) { auto ret = std::vector(); std::string conn1; for (const auto &connection : ConnectionHelper::connectionPoints) { if (ignition::common::lowercase(connection.first) == ignition::common::lowercase(_tile1->tileType)) { conn1 = connection.first; } } if (conn1.empty()) { ignwarn << ""No connection information for: "" << _tile1->tileType << std::endl; } else { for (const auto& pt1 : ConnectionHelper::connectionPoints[conn1]) { auto pt1tf = _tile1->model.RawPose().CoordPositionAdd(pt1); ret.push_back(pt1tf); } } return ret; } ",16352,True,3182.5577052028693,median "// // TextureProcessing.cpp // image/src/TextureProcessing // // Created by Clement Brisset on 4/5/2017. // Copyright 2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include ""TextureProcessing.h"" #include #include #include #include #include #include #include #include #include #include #include ""TGAReader.h"" #if !defined(Q_OS_ANDROID) #include ""OpenEXRReader.h"" #endif #include ""ImageLogging.h"" using namespace gpu; #define CPU_MIPMAPS 1 #include #undef _CRT_SECURE_NO_WARNINGS #include #include static const glm::uvec2 SPARSE_PAGE_SIZE(128); static const glm::uvec2 MAX_TEXTURE_SIZE_GLES(2048); static const glm::uvec2 MAX_TEXTURE_SIZE_GL(4096); bool DEV_DECIMATE_TEXTURES = false; std::atomic DECIMATED_TEXTURE_COUNT{ 0 }; std::atomic RECTIFIED_TEXTURE_COUNT{ 0 }; // we use a ref here to work around static order initialization // possibly causing the element not to be constructed yet static const auto& GPU_CUBEMAP_DEFAULT_FORMAT = gpu::Element::COLOR_SRGBA_32; static const auto& GPU_CUBEMAP_HDR_FORMAT = gpu::Element::COLOR_R11G11B10; namespace image { uint rectifyDimension(const uint& dimension) { if (dimension == 0) { return 0; } if (dimension < SPARSE_PAGE_SIZE.x) { uint newSize = SPARSE_PAGE_SIZE.x; while (dimension <= newSize / 2) { newSize /= 2; } return newSize; } else { uint pages = (dimension / SPARSE_PAGE_SIZE.x) + (dimension % SPARSE_PAGE_SIZE.x == 0 ? 0 : 1); return pages * SPARSE_PAGE_SIZE.x; } } glm::uvec2 rectifySize(const glm::uvec2& size) { return { rectifyDimension(size.x), rectifyDimension(size.y) }; } const QStringList getSupportedFormats() { auto formats = QImageReader::supportedImageFormats(); QStringList stringFormats; std::transform(formats.begin(), formats.end(), std::back_inserter(stringFormats), [](QByteArray& format) -> QString { return format; }); return stringFormats; } // On GLES, we don't use HDR skyboxes bool isHDRTextureFormatEnabledForTarget(BackendTarget target) { return target != BackendTarget::GLES32; } gpu::Element getHDRTextureFormatForTarget(BackendTarget target, bool compressed) { if (compressed) { if (target == BackendTarget::GLES32) { return gpu::Element::COLOR_COMPRESSED_ETC2_SRGB; } else { return gpu::Element::COLOR_COMPRESSED_BCX_HDR_RGB; } } else { if (!isHDRTextureFormatEnabledForTarget(target)) { return GPU_CUBEMAP_DEFAULT_FORMAT; } else { return GPU_CUBEMAP_HDR_FORMAT; } } } TextureUsage::TextureLoader TextureUsage::getTextureLoaderForType(Type type, const QVariantMap& options) { switch (type) { case ALBEDO_TEXTURE: return image::TextureUsage::createAlbedoTextureFromImage; case EMISSIVE_TEXTURE: return image::TextureUsage::createEmissiveTextureFromImage; case LIGHTMAP_TEXTURE: return image::TextureUsage::createLightmapTextureFromImage; case CUBE_TEXTURE: if (options.value(""generateIrradiance"", true).toBool()) { return image::TextureUsage::createCubeTextureFromImage; } else { return image::TextureUsage::createCubeTextureFromImageWithoutIrradiance; } case BUMP_TEXTURE: return image::TextureUsage::createNormalTextureFromBumpImage; case NORMAL_TEXTURE: return image::TextureUsage::createNormalTextureFromNormalImage; case ROUGHNESS_TEXTURE: return image::TextureUsage::createRoughnessTextureFromImage; case GLOSS_TEXTURE: return image::TextureUsage::createRoughnessTextureFromGlossImage; case SPECULAR_TEXTURE: return image::TextureUsage::createMetallicTextureFromImage; case STRICT_TEXTURE: return image::TextureUsage::createStrict2DTextureFromImage; case DEFAULT_TEXTURE: default: return image::TextureUsage::create2DTextureFromImage; } } gpu::TexturePointer TextureUsage::createStrict2DTextureFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureColorFromImage(std::move(srcImage), srcImageName, compress, target, true, abortProcessing); } gpu::TexturePointer TextureUsage::create2DTextureFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureColorFromImage(std::move(srcImage), srcImageName, compress, target, false, abortProcessing); } gpu::TexturePointer TextureUsage::createAlbedoTextureFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureColorFromImage(std::move(srcImage), srcImageName, compress, target, false, abortProcessing); } gpu::TexturePointer TextureUsage::createEmissiveTextureFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureColorFromImage(std::move(srcImage), srcImageName, compress, target, false, abortProcessing); } gpu::TexturePointer TextureUsage::createLightmapTextureFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureColorFromImage(std::move(srcImage), srcImageName, compress, target, false, abortProcessing); } gpu::TexturePointer TextureUsage::createNormalTextureFromNormalImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureNormalMapFromImage(std::move(srcImage), srcImageName, compress, target, false, abortProcessing); } gpu::TexturePointer TextureUsage::createNormalTextureFromBumpImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureNormalMapFromImage(std::move(srcImage), srcImageName, compress, target, true, abortProcessing); } gpu::TexturePointer TextureUsage::createRoughnessTextureFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureGrayscaleFromImage(std::move(srcImage), srcImageName, compress, target, false, abortProcessing); } gpu::TexturePointer TextureUsage::createRoughnessTextureFromGlossImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureGrayscaleFromImage(std::move(srcImage), srcImageName, compress, target, true, abortProcessing); } gpu::TexturePointer TextureUsage::createMetallicTextureFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return process2DTextureGrayscaleFromImage(std::move(srcImage), srcImageName, compress, target, false, abortProcessing); } gpu::TexturePointer TextureUsage::createCubeTextureFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return processCubeTextureColorFromImage(std::move(srcImage), srcImageName, compress, target, true, abortProcessing); } gpu::TexturePointer TextureUsage::createCubeTextureFromImageWithoutIrradiance(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, const std::atomic& abortProcessing) { return processCubeTextureColorFromImage(std::move(srcImage), srcImageName, compress, target, false, abortProcessing); } static float denormalize(float value, const float minValue) { return value < minValue ? 0.0f : value; } static uint32 packR11G11B10F(const glm::vec3& color) { // Denormalize else unpacking gives high and incorrect values // See https://www.khronos.org/opengl/wiki/Small_Float_Formats for this min value static const auto minValue = 6.10e-5f; static const auto maxValue = 6.50e4f; glm::vec3 ucolor; ucolor.r = denormalize(color.r, minValue); ucolor.g = denormalize(color.g, minValue); ucolor.b = denormalize(color.b, minValue); ucolor.r = std::min(ucolor.r, maxValue); ucolor.g = std::min(ucolor.g, maxValue); ucolor.b = std::min(ucolor.b, maxValue); return glm::packF2x11_1x10(ucolor); } static std::function getHDRPackingFunction(const gpu::Element& format) { if (format == gpu::Element::COLOR_RGB9E5) { return glm::packF3x9_E1x5; } else if (format == gpu::Element::COLOR_R11G11B10) { return packR11G11B10F; } else { qCWarning(imagelogging) << ""Unknown handler format""; Q_UNREACHABLE(); return nullptr; } } std::function getHDRPackingFunction() { return getHDRPackingFunction(GPU_CUBEMAP_HDR_FORMAT); } std::function getHDRUnpackingFunction() { if (GPU_CUBEMAP_HDR_FORMAT == gpu::Element::COLOR_RGB9E5) { return glm::unpackF3x9_E1x5; } else if (GPU_CUBEMAP_HDR_FORMAT == gpu::Element::COLOR_R11G11B10) { return glm::unpackF2x11_1x10; } else { qCWarning(imagelogging) << ""Unknown HDR encoding format in Image""; Q_UNREACHABLE(); return nullptr; } } Image processRawImageData(QIODevice& content, const std::string& filename) { // Help the Image loader by extracting the image file format from the url filename ext. // Some tga are not created properly without it. auto filenameExtension = filename.substr(filename.find_last_of('.') + 1); // Remove possible query part of the filename if it comes from an URL filenameExtension = filenameExtension.substr(0, filenameExtension.find_first_of('?')); if (!content.isReadable()) { content.open(QIODevice::ReadOnly); } else { content.reset(); } if (filenameExtension == ""tga"") { Image image = image::readTGA(content); if (!image.isNull()) { return image; } content.reset(); } #if !defined(Q_OS_ANDROID) else if (filenameExtension == ""exr"") { Image image = image::readOpenEXR(content, filename); if (!image.isNull()) { return image; } } #endif QImageReader imageReader(&content, filenameExtension.c_str()); if (imageReader.canRead()) { return Image(imageReader.read()); } else { // Extension could be incorrect, try to detect the format from the content QImageReader newImageReader; newImageReader.setDecideFormatFromContent(true); content.reset(); newImageReader.setDevice(&content); if (newImageReader.canRead()) { return Image(newImageReader.read()); } } return Image(); } void mapToRedChannel(Image& image, ColorChannel sourceChannel) { // Change format of image so we know exactly how to process it if (image.getFormat() != Image::Format_ARGB32) { image = image.getConvertedToFormat(Image::Format_ARGB32); } for (glm::uint32 i = 0; i < image.getHeight(); i++) { QRgb* pixel = reinterpret_cast(image.editScanLine(i)); // Past end pointer QRgb* lineEnd = pixel + image.getWidth(); // Transfer channel data from source to target for (; pixel < lineEnd; pixel++) { int colorValue; switch (sourceChannel) { case ColorChannel::RED: colorValue = qRed(*pixel); break; case ColorChannel::GREEN: colorValue = qGreen(*pixel); break; case ColorChannel::BLUE: colorValue = qBlue(*pixel); break; case ColorChannel::ALPHA: colorValue = qAlpha(*pixel); break; default: colorValue = qRed(*pixel); break; } // Dump the color in the red channel, ignore the rest *pixel = qRgba(colorValue, 0, 0, 255); } } } gpu::TexturePointer processImage(std::shared_ptr content, const std::string& filename, ColorChannel sourceChannel, int maxNumPixels, TextureUsage::Type textureType, bool compress, BackendTarget target, const std::atomic& abortProcessing) { Image image = processRawImageData(*content.get(), filename); // Texture content can take up a lot of memory. Here we release our ownership of that content // in case it can be released. content.reset(); int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); // Validate that the image loaded if (imageWidth == 0 || imageHeight == 0 || image.getFormat() == Image::Format_Invalid) { QString reason(image.getFormat() == Image::Format_Invalid ? ""(Invalid Format)"" : ""(Size is invalid)""); qCWarning(imagelogging) << ""Failed to load:"" << qPrintable(reason); return nullptr; } // Validate the image is less than _maxNumPixels, and downscale if necessary if (imageWidth * imageHeight > maxNumPixels) { float scaleFactor = sqrtf(maxNumPixels / (float)(imageWidth * imageHeight)); int originalWidth = imageWidth; int originalHeight = imageHeight; imageWidth = (int)(scaleFactor * (float)imageWidth + 0.5f); imageHeight = (int)(scaleFactor * (float)imageHeight + 0.5f); image = image.getScaled(glm::uvec2(imageWidth, imageHeight), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); qCDebug(imagelogging).nospace() << ""Downscaled "" << "" ("" << QSize(originalWidth, originalHeight) << "" to "" << QSize(imageWidth, imageHeight) << "")""; } // Re-map to image with single red channel texture if requested if (sourceChannel != ColorChannel::NONE) { mapToRedChannel(image, sourceChannel); } auto loader = TextureUsage::getTextureLoaderForType(textureType); auto texture = loader(std::move(image), filename, compress, target, abortProcessing); return texture; } Image processSourceImage(Image&& srcImage, bool cubemap, BackendTarget target) { PROFILE_RANGE(resource_parse, ""processSourceImage""); // Take a local copy to force move construction // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f18-for-consume-parameters-pass-by-x-and-stdmove-the-parameter Image localCopy = std::move(srcImage); const glm::uvec2 srcImageSize = localCopy.getSize(); glm::uvec2 targetSize = srcImageSize; const auto maxTextureSize = target == BackendTarget::GLES32 ? MAX_TEXTURE_SIZE_GLES : MAX_TEXTURE_SIZE_GL; while (glm::any(glm::greaterThan(targetSize, maxTextureSize))) { targetSize /= 2; } if (targetSize != srcImageSize) { ++DECIMATED_TEXTURE_COUNT; } if (!cubemap) { auto rectifiedSize = rectifySize(targetSize); if (rectifiedSize != targetSize) { ++RECTIFIED_TEXTURE_COUNT; targetSize = rectifiedSize; } } if (DEV_DECIMATE_TEXTURES && glm::all(glm::greaterThanEqual(targetSize / SPARSE_PAGE_SIZE, glm::uvec2(2)))) { targetSize /= 2; } if (targetSize != srcImageSize) { PROFILE_RANGE(resource_parse, ""processSourceImage Rectify""); qCDebug(imagelogging) << ""Resizing texture from "" << srcImageSize.x << ""x"" << srcImageSize.y << "" to "" << targetSize.x << ""x"" << targetSize.y; return localCopy.getScaled(targetSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } return localCopy; } #if defined(NVTT_API) struct OutputHandler : public nvtt::OutputHandler { OutputHandler(gpu::Texture* texture, int face) : _texture(texture), _face(face) {} virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel) override { _size = size; _miplevel = miplevel; _data = static_cast(malloc(size)); _current = _data; } virtual bool writeData(const void* data, int size) override { assert(_current + size <= _data + _size); memcpy(_current, data, size); _current += size; return true; } virtual void endImage() override { if (_face >= 0) { _texture->assignStoredMipFace(_miplevel, _face, _size, static_cast(_data)); } else { _texture->assignStoredMip(_miplevel, _size, static_cast(_data)); } free(_data); _data = nullptr; } gpu::Byte* _data{ nullptr }; gpu::Byte* _current{ nullptr }; gpu::Texture* _texture{ nullptr }; int _miplevel = 0; int _size = 0; int _face = -1; }; struct PackedFloatOutputHandler : public OutputHandler { PackedFloatOutputHandler(gpu::Texture* texture, int face, gpu::Element format) : OutputHandler(texture, face) { _packFunc = getHDRPackingFunction(format); } virtual void beginImage(int size, int width, int height, int depth, int face, int miplevel) override { // Divide by 3 because we will compress from 3*floats to 1 uint32 OutputHandler::beginImage(size / 3, width, height, depth, face, miplevel); } virtual bool writeData(const void* data, int size) override { // Expecting to write multiple of floats if (_packFunc) { assert((size % sizeof(float)) == 0); auto floatCount = size / sizeof(float); const float* floatBegin = (const float*)data; const float* floatEnd = floatBegin + floatCount; while (floatBegin < floatEnd) { _pixel[_coordIndex] = *floatBegin; floatBegin++; _coordIndex++; if (_coordIndex == 3) { uint32 packedRGB = _packFunc(_pixel); _coordIndex = 0; OutputHandler::writeData(&packedRGB, sizeof(packedRGB)); } } return true; } return false; } std::function _packFunc; glm::vec3 _pixel; int _coordIndex{ 0 }; }; struct MyErrorHandler : public nvtt::ErrorHandler { virtual void error(nvtt::Error e) override { qCWarning(imagelogging) << ""Texture compression error:"" << nvtt::errorString(e); } }; class SequentialTaskDispatcher : public nvtt::TaskDispatcher { public: SequentialTaskDispatcher(const std::atomic& abortProcessing) : _abortProcessing(abortProcessing) {}; const std::atomic& _abortProcessing; virtual void dispatch(nvtt::Task* task, void* context, int count) override { for (int i = 0; i < count; i++) { if (!_abortProcessing.load()) { task(context, i); } else { break; } } } }; void generateHDRMips(gpu::Texture* texture, Image&& image, BackendTarget target, const std::atomic& abortProcessing, int face) { // Take a local copy to force move construction // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f18-for-consume-parameters-pass-by-x-and-stdmove-the-parameter Image localCopy = std::move(image); assert(localCopy.getFormat() == Image::Format_PACKED_FLOAT); const int width = localCopy.getWidth(), height = localCopy.getHeight(); std::vector data; std::vector::iterator dataIt; auto mipFormat = texture->getStoredMipFormat(); std::function unpackFunc = getHDRUnpackingFunction(); nvtt::InputFormat inputFormat = nvtt::InputFormat_RGBA_32F; nvtt::WrapMode wrapMode = nvtt::WrapMode_Mirror; nvtt::AlphaMode alphaMode = nvtt::AlphaMode_None; nvtt::CompressionOptions compressionOptions; compressionOptions.setQuality(nvtt::Quality_Production); // TODO: gles: generate ETC mips instead? if (mipFormat == gpu::Element::COLOR_COMPRESSED_BCX_HDR_RGB) { compressionOptions.setFormat(nvtt::Format_BC6); } else if (mipFormat == gpu::Element::COLOR_RGB9E5) { compressionOptions.setFormat(nvtt::Format_RGB); compressionOptions.setPixelType(nvtt::PixelType_Float); compressionOptions.setPixelFormat(32, 32, 32, 0); } else if (mipFormat == gpu::Element::COLOR_R11G11B10) { compressionOptions.setFormat(nvtt::Format_RGB); compressionOptions.setPixelType(nvtt::PixelType_Float); compressionOptions.setPixelFormat(32, 32, 32, 0); } else { qCWarning(imagelogging) << ""Unknown mip format""; Q_UNREACHABLE(); return; } data.resize(width * height); dataIt = data.begin(); for (auto lineNb = 0; lineNb < height; lineNb++) { const uint32* srcPixelIt = reinterpret_cast(localCopy.getScanLine(lineNb)); const uint32* srcPixelEnd = srcPixelIt + width; while (srcPixelIt < srcPixelEnd) { *dataIt = glm::vec4(unpackFunc(*srcPixelIt), 1.0f); ++srcPixelIt; ++dataIt; } } assert(dataIt == data.end()); // We're done with the localCopy, free up the memory to avoid bloating the heap localCopy = Image(); // Image doesn't have a clear function, so override it with an empty one. nvtt::OutputOptions outputOptions; outputOptions.setOutputHeader(false); std::unique_ptr outputHandler; MyErrorHandler errorHandler; outputOptions.setErrorHandler(&errorHandler); nvtt::Context context; int mipLevel = 0; if (mipFormat == gpu::Element::COLOR_RGB9E5 || mipFormat == gpu::Element::COLOR_R11G11B10) { // Don't use NVTT (at least version 2.1) as it outputs wrong RGB9E5 and R11G11B10F values from floats outputHandler.reset(new PackedFloatOutputHandler(texture, face, mipFormat)); } else { outputHandler.reset(new OutputHandler(texture, face)); } outputOptions.setOutputHandler(outputHandler.get()); nvtt::Surface surface; surface.setImage(inputFormat, width, height, 1, &(*data.begin())); surface.setAlphaMode(alphaMode); surface.setWrapMode(wrapMode); SequentialTaskDispatcher dispatcher(abortProcessing); nvtt::Compressor compressor; context.setTaskDispatcher(&dispatcher); context.compress(surface, face, mipLevel++, compressionOptions, outputOptions); while (surface.canMakeNextMipmap() && !abortProcessing.load()) { surface.buildNextMipmap(nvtt::MipmapFilter_Box); context.compress(surface, face, mipLevel++, compressionOptions, outputOptions); } } void generateLDRMips(gpu::Texture* texture, Image&& image, BackendTarget target, const std::atomic& abortProcessing, int face) { // Take a local copy to force move construction // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f18-for-consume-parameters-pass-by-x-and-stdmove-the-parameter Image localCopy = std::move(image); assert(localCopy.getFormat() != Image::Format_PACKED_FLOAT); if (localCopy.getFormat() != Image::Format_ARGB32) { localCopy = localCopy.getConvertedToFormat(Image::Format_ARGB32); } const int width = localCopy.getWidth(), height = localCopy.getHeight(); auto mipFormat = texture->getStoredMipFormat(); if (target != BackendTarget::GLES32) { const void* data = static_cast(localCopy.getBits()); nvtt::TextureType textureType = nvtt::TextureType_2D; nvtt::InputFormat inputFormat = nvtt::InputFormat_BGRA_8UB; nvtt::WrapMode wrapMode = nvtt::WrapMode_Mirror; nvtt::RoundMode roundMode = nvtt::RoundMode_None; nvtt::AlphaMode alphaMode = nvtt::AlphaMode_None; float inputGamma = 2.2f; float outputGamma = 2.2f; nvtt::InputOptions inputOptions; inputOptions.setTextureLayout(textureType, width, height); inputOptions.setMipmapData(data, width, height); // setMipmapData copies the memory, so free up the memory afterward to avoid bloating the heap data = nullptr; localCopy = Image(); // Image doesn't have a clear function, so override it with an empty one. inputOptions.setFormat(inputFormat); inputOptions.setGamma(inputGamma, outputGamma); inputOptions.setAlphaMode(alphaMode); inputOptions.setWrapMode(wrapMode); inputOptions.setRoundMode(roundMode); inputOptions.setMipmapGeneration(true); inputOptions.setMipmapFilter(nvtt::MipmapFilter_Box); nvtt::CompressionOptions compressionOptions; compressionOptions.setQuality(nvtt::Quality_Production); if (mipFormat == gpu::Element::COLOR_COMPRESSED_BCX_SRGB) { compressionOptions.setFormat(nvtt::Format_BC1); } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_BCX_SRGBA_MASK) { alphaMode = nvtt::AlphaMode_Transparency; compressionOptions.setFormat(nvtt::Format_BC1a); } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_BCX_SRGBA) { alphaMode = nvtt::AlphaMode_Transparency; compressionOptions.setFormat(nvtt::Format_BC3); } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_BCX_RED) { compressionOptions.setFormat(nvtt::Format_BC4); } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_BCX_XY) { compressionOptions.setFormat(nvtt::Format_BC5); } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_BCX_SRGBA_HIGH) { alphaMode = nvtt::AlphaMode_Transparency; compressionOptions.setFormat(nvtt::Format_BC7); } else if (mipFormat == gpu::Element::COLOR_RGBA_32) { compressionOptions.setFormat(nvtt::Format_RGBA); compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm); compressionOptions.setPitchAlignment(4); compressionOptions.setPixelFormat(32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); inputGamma = 1.0f; outputGamma = 1.0f; } else if (mipFormat == gpu::Element::COLOR_BGRA_32) { compressionOptions.setFormat(nvtt::Format_RGBA); compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm); compressionOptions.setPitchAlignment(4); compressionOptions.setPixelFormat(32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); inputGamma = 1.0f; outputGamma = 1.0f; } else if (mipFormat == gpu::Element::COLOR_SRGBA_32) { compressionOptions.setFormat(nvtt::Format_RGBA); compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm); compressionOptions.setPitchAlignment(4); compressionOptions.setPixelFormat(32, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); } else if (mipFormat == gpu::Element::COLOR_SBGRA_32) { compressionOptions.setFormat(nvtt::Format_RGBA); compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm); compressionOptions.setPitchAlignment(4); compressionOptions.setPixelFormat(32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); } else if (mipFormat == gpu::Element::COLOR_R_8) { compressionOptions.setFormat(nvtt::Format_RGB); compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm); compressionOptions.setPitchAlignment(4); compressionOptions.setPixelFormat(8, 0, 0, 0); } else if (mipFormat == gpu::Element::VEC2NU8_XY) { inputOptions.setNormalMap(true); compressionOptions.setFormat(nvtt::Format_RGBA); compressionOptions.setPixelType(nvtt::PixelType_UnsignedNorm); compressionOptions.setPitchAlignment(4); compressionOptions.setPixelFormat(8, 8, 0, 0); } else { qCWarning(imagelogging) << ""Unknown mip format""; Q_UNREACHABLE(); return; } nvtt::OutputOptions outputOptions; outputOptions.setOutputHeader(false); OutputHandler outputHandler(texture, face); outputOptions.setOutputHandler(&outputHandler); MyErrorHandler errorHandler; outputOptions.setErrorHandler(&errorHandler); SequentialTaskDispatcher dispatcher(abortProcessing); nvtt::Compressor compressor; compressor.setTaskDispatcher(&dispatcher); compressor.process(inputOptions, compressionOptions, outputOptions); } else { int numMips = 1 + (int)log2(std::max(width, height)); Etc::RawImage *mipMaps = new Etc::RawImage[numMips]; Etc::Image::Format etcFormat = Etc::Image::Format::DEFAULT; if (mipFormat == gpu::Element::COLOR_COMPRESSED_ETC2_RGB) { etcFormat = Etc::Image::Format::RGB8; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_ETC2_SRGB) { etcFormat = Etc::Image::Format::SRGB8; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_ETC2_RGB_PUNCHTHROUGH_ALPHA) { etcFormat = Etc::Image::Format::RGB8A1; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_ETC2_SRGB_PUNCHTHROUGH_ALPHA) { etcFormat = Etc::Image::Format::SRGB8A1; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_ETC2_RGBA) { etcFormat = Etc::Image::Format::RGBA8; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_ETC2_SRGBA) { etcFormat = Etc::Image::Format::SRGBA8; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_EAC_RED) { etcFormat = Etc::Image::Format::R11; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_EAC_RED_SIGNED) { etcFormat = Etc::Image::Format::SIGNED_R11; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_EAC_XY) { etcFormat = Etc::Image::Format::RG11; } else if (mipFormat == gpu::Element::COLOR_COMPRESSED_EAC_XY_SIGNED) { etcFormat = Etc::Image::Format::SIGNED_RG11; } else { qCWarning(imagelogging) << ""Unknown mip format""; Q_UNREACHABLE(); return; } const Etc::ErrorMetric errorMetric = Etc::ErrorMetric::RGBA; const float effort = 1.0f; const int numEncodeThreads = 4; int encodingTime; const float MAX_COLOR = 255.0f; std::vector floatData; floatData.resize(width * height); for (int y = 0; y < height; y++) { QRgb *line = (QRgb *)localCopy.editScanLine(y); for (int x = 0; x < width; x++) { QRgb &pixel = line[x]; floatData[x + y * width] = vec4(qRed(pixel), qGreen(pixel), qBlue(pixel), qAlpha(pixel)) / MAX_COLOR; } } // free up the memory afterward to avoid bloating the heap localCopy = Image(); // Image doesn't have a clear function, so override it with an empty one. Etc::EncodeMipmaps( (float *)floatData.data(), width, height, etcFormat, errorMetric, effort, numEncodeThreads, numEncodeThreads, numMips, Etc::FILTER_WRAP_NONE, mipMaps, &encodingTime ); for (int i = 0; i < numMips; i++) { if (mipMaps[i].paucEncodingBits.get()) { if (face >= 0) { texture->assignStoredMipFace(i, face, mipMaps[i].uiEncodingBitsBytes, static_cast(mipMaps[i].paucEncodingBits.get())); } else { texture->assignStoredMip(i, mipMaps[i].uiEncodingBitsBytes, static_cast(mipMaps[i].paucEncodingBits.get())); } } } delete[] mipMaps; } } #endif void generateMips(gpu::Texture* texture, Image&& image, BackendTarget target, const std::atomic& abortProcessing = false, int face = -1) { #if CPU_MIPMAPS PROFILE_RANGE(resource_parse, ""generateMips""); if (target == BackendTarget::GLES32) { generateLDRMips(texture, std::move(image), target, abortProcessing, face); } else { if (image.getFormat() == Image::Format_PACKED_FLOAT) { generateHDRMips(texture, std::move(image), target, abortProcessing, face); } else { generateLDRMips(texture, std::move(image), target, abortProcessing, face); } } #else texture->setAutoGenerateMips(true); #endif } void processTextureAlpha(const Image& srcImage, bool& validAlpha, bool& alphaAsMask) { PROFILE_RANGE(resource_parse, ""processTextureAlpha""); validAlpha = false; alphaAsMask = true; const uint8 OPAQUE_ALPHA = 255; const uint8 TRANSPARENT_ALPHA = 0; // Figure out if we can use a mask for alpha or not int numOpaques = 0; int numTranslucents = 0; const int NUM_PIXELS = srcImage.getWidth() * srcImage.getHeight(); const int MAX_TRANSLUCENT_PIXELS_FOR_ALPHAMASK = (int)(0.05f * (float)(NUM_PIXELS)); const QRgb* data = reinterpret_cast(srcImage.getBits()); for (int i = 0; i < NUM_PIXELS; ++i) { auto alpha = qAlpha(data[i]); if (alpha == OPAQUE_ALPHA) { numOpaques++; } else if (alpha != TRANSPARENT_ALPHA) { if (++numTranslucents > MAX_TRANSLUCENT_PIXELS_FOR_ALPHAMASK) { alphaAsMask = false; break; } } } validAlpha = (numOpaques != NUM_PIXELS); } gpu::TexturePointer TextureUsage::process2DTextureColorFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, bool isStrict, const std::atomic& abortProcessing) { PROFILE_RANGE(resource_parse, ""process2DTextureColorFromImage""); Image image = processSourceImage(std::move(srcImage), false, target); bool validAlpha = image.hasAlphaChannel(); bool alphaAsMask = false; if (image.getFormat() != Image::Format_ARGB32) { image = image.getConvertedToFormat(Image::Format_ARGB32); } if (validAlpha) { processTextureAlpha(image, validAlpha, alphaAsMask); } gpu::TexturePointer theTexture = nullptr; if ((image.getWidth() > 0) && (image.getHeight() > 0)) { gpu::Element formatMip; gpu::Element formatGPU; if (compress) { if (target == BackendTarget::GLES32) { // GLES does not support GL_BGRA formatGPU = gpu::Element::COLOR_COMPRESSED_ETC2_SRGBA; formatMip = formatGPU; } else { if (validAlpha) { // NOTE: This disables BC1a compression because it was producing odd artifacts on text textures // for the tutorial. Instead we use BC3 (which is larger) but doesn't produce the same artifacts). formatGPU = gpu::Element::COLOR_COMPRESSED_BCX_SRGBA; } else { formatGPU = gpu::Element::COLOR_COMPRESSED_BCX_SRGB; } formatMip = formatGPU; } } else { if (target == BackendTarget::GLES32) { } else { formatGPU = gpu::Element::COLOR_SRGBA_32; formatMip = gpu::Element::COLOR_SBGRA_32; } } if (isStrict) { theTexture = gpu::Texture::createStrict(formatGPU, image.getWidth(), image.getHeight(), gpu::Texture::MAX_NUM_MIPS, gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR)); } else { theTexture = gpu::Texture::create2D(formatGPU, image.getWidth(), image.getHeight(), gpu::Texture::MAX_NUM_MIPS, gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR)); } theTexture->setSource(srcImageName); auto usage = gpu::Texture::Usage::Builder().withColor(); if (validAlpha) { usage.withAlpha(); if (alphaAsMask) { usage.withAlphaMask(); } } theTexture->setUsage(usage.build()); theTexture->setStoredMipFormat(formatMip); theTexture->assignStoredMip(0, image.getByteCount(), image.getBits()); generateMips(theTexture.get(), std::move(image), target, abortProcessing); } return theTexture; } int clampPixelCoordinate(int coordinate, int maxCoordinate) { return coordinate - ((int)(coordinate < 0) * coordinate) + ((int)(coordinate > maxCoordinate) * (maxCoordinate - coordinate)); } const int RGBA_MAX = 255; // transform -1 - 1 to 0 - 255 (from sobel value to rgb) double mapComponent(double sobelValue) { const double factor = RGBA_MAX / 2.0; return (sobelValue + 1.0) * factor; } Image processBumpMap(Image&& image) { // Take a local copy to force move construction // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f18-for-consume-parameters-pass-by-x-and-stdmove-the-parameter Image localCopy = std::move(image); if (localCopy.getFormat() != Image::Format_Grayscale8) { localCopy = localCopy.getConvertedToFormat(Image::Format_Grayscale8); } // PR 5540 by AlessandroSigna integrated here as a specialized TextureLoader for bumpmaps // The conversion is done using the Sobel Filter to calculate the derivatives from the grayscale image const double pStrength = 2.0; int width = localCopy.getWidth(); int height = localCopy.getHeight(); Image result(width, height, Image::Format_ARGB32); for (int i = 0; i < width; i++) { const int iNextClamped = clampPixelCoordinate(i + 1, width - 1); const int iPrevClamped = clampPixelCoordinate(i - 1, width - 1); for (int j = 0; j < height; j++) { const int jNextClamped = clampPixelCoordinate(j + 1, height - 1); const int jPrevClamped = clampPixelCoordinate(j - 1, height - 1); // surrounding pixels const QRgb topLeft = localCopy.getPixel(iPrevClamped, jPrevClamped); const QRgb top = localCopy.getPixel(iPrevClamped, j); const QRgb topRight = localCopy.getPixel(iPrevClamped, jNextClamped); const QRgb right = localCopy.getPixel(i, jNextClamped); const QRgb bottomRight = localCopy.getPixel(iNextClamped, jNextClamped); const QRgb bottom = localCopy.getPixel(iNextClamped, j); const QRgb bottomLeft = localCopy.getPixel(iNextClamped, jPrevClamped); const QRgb left = localCopy.getPixel(i, jPrevClamped); // take their gray intensities // since it's a grayscale image, the value of each component RGB is the same const double tl = qRed(topLeft); const double t = qRed(top); const double tr = qRed(topRight); const double r = qRed(right); const double br = qRed(bottomRight); const double b = qRed(bottom); const double bl = qRed(bottomLeft); const double l = qRed(left); // apply the sobel filter const double dX = (tr + pStrength * r + br) - (tl + pStrength * l + bl); const double dY = (bl + pStrength * b + br) - (tl + pStrength * t + tr); const double dZ = RGBA_MAX / pStrength; glm::vec3 v(dX, dY, dZ); glm::normalize(v); // convert to rgb from the value obtained computing the filter QRgb qRgbValue = qRgba(mapComponent(v.z), mapComponent(v.y), mapComponent(v.x), 1.0); result.setPixel(i, j, qRgbValue); } } return result; } gpu::TexturePointer TextureUsage::process2DTextureNormalMapFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, bool isBumpMap, const std::atomic& abortProcessing) { PROFILE_RANGE(resource_parse, ""process2DTextureNormalMapFromImage""); Image image = processSourceImage(std::move(srcImage), false, target); if (isBumpMap) { image = processBumpMap(std::move(image)); } // Make sure the normal map source image is ARGB32 if (image.getFormat() != Image::Format_ARGB32) { image = image.getConvertedToFormat(Image::Format_ARGB32); } gpu::TexturePointer theTexture = nullptr; if ((image.getWidth() > 0) && (image.getHeight() > 0)) { gpu::Element formatMip; gpu::Element formatGPU; if (compress) { if (target == BackendTarget::GLES32) { formatGPU = gpu::Element::COLOR_COMPRESSED_EAC_XY; } else { formatGPU = gpu::Element::COLOR_COMPRESSED_BCX_XY; } } else { formatGPU = gpu::Element::VEC2NU8_XY; } formatMip = formatGPU; theTexture = gpu::Texture::create2D(formatGPU, image.getWidth(), image.getHeight(), gpu::Texture::MAX_NUM_MIPS, gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR)); theTexture->setSource(srcImageName); theTexture->setStoredMipFormat(formatMip); theTexture->assignStoredMip(0, image.getByteCount(), image.getBits()); generateMips(theTexture.get(), std::move(image), target, abortProcessing); } return theTexture; } gpu::TexturePointer TextureUsage::process2DTextureGrayscaleFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, bool isInvertedPixels, const std::atomic& abortProcessing) { PROFILE_RANGE(resource_parse, ""process2DTextureGrayscaleFromImage""); Image image = processSourceImage(std::move(srcImage), false, target); if (image.getFormat() != Image::Format_ARGB32) { image = image.getConvertedToFormat(Image::Format_ARGB32); } if (isInvertedPixels) { // Gloss turned into Rough image.invertPixels(); } gpu::TexturePointer theTexture = nullptr; if ((image.getWidth() > 0) && (image.getHeight() > 0)) { gpu::Element formatMip; gpu::Element formatGPU; if (compress) { if (target == BackendTarget::GLES32) { formatGPU = gpu::Element::COLOR_COMPRESSED_EAC_RED; } else { formatGPU = gpu::Element::COLOR_COMPRESSED_BCX_RED; } } else { formatGPU = gpu::Element::COLOR_R_8; } formatMip = formatGPU; theTexture = gpu::Texture::create2D(formatGPU, image.getWidth(), image.getHeight(), gpu::Texture::MAX_NUM_MIPS, gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR)); theTexture->setSource(srcImageName); theTexture->setStoredMipFormat(formatMip); theTexture->assignStoredMip(0, image.getByteCount(), image.getBits()); generateMips(theTexture.get(), std::move(image), target, abortProcessing); } return theTexture; } class CubeLayout { public: enum SourceProjection { FLAT = 0, EQUIRECTANGULAR, }; int _type = FLAT; int _widthRatio = 1; int _heightRatio = 1; class Face { public: int _x = 0; int _y = 0; bool _horizontalMirror = false; bool _verticalMirror = false; Face() {} Face(int x, int y, bool horizontalMirror, bool verticalMirror) : _x(x), _y(y), _horizontalMirror(horizontalMirror), _verticalMirror(verticalMirror) {} }; Face _faceXPos; Face _faceXNeg; Face _faceYPos; Face _faceYNeg; Face _faceZPos; Face _faceZNeg; CubeLayout(int wr, int hr, Face fXP, Face fXN, Face fYP, Face fYN, Face fZP, Face fZN) : _type(FLAT), _widthRatio(wr), _heightRatio(hr), _faceXPos(fXP), _faceXNeg(fXN), _faceYPos(fYP), _faceYNeg(fYN), _faceZPos(fZP), _faceZNeg(fZN) {} CubeLayout(int wr, int hr) : _type(EQUIRECTANGULAR), _widthRatio(wr), _heightRatio(hr) {} static const CubeLayout CUBEMAP_LAYOUTS[]; static const int NUM_CUBEMAP_LAYOUTS; static int findLayout(int width, int height) { // Find the layout of the cubemap in the 2D image int foundLayout = -1; for (int i = 0; i < NUM_CUBEMAP_LAYOUTS; i++) { if ((height * CUBEMAP_LAYOUTS[i]._widthRatio) == (width * CUBEMAP_LAYOUTS[i]._heightRatio)) { foundLayout = i; break; } } return foundLayout; } static Image extractEquirectangularFace(const Image& source, gpu::Texture::CubeFace face, int faceWidth) { Image image(faceWidth, faceWidth, source.getFormat()); glm::vec2 dstInvSize(1.0f / faceWidth); struct CubeToXYZ { gpu::Texture::CubeFace _face; CubeToXYZ(gpu::Texture::CubeFace face) : _face(face) {} glm::vec3 xyzFrom(const glm::vec2& uv) { auto faceDir = glm::normalize(glm::vec3(-1.0f + 2.0f * uv.x, -1.0f + 2.0f * uv.y, 1.0f)); switch (_face) { case gpu::Texture::CubeFace::CUBE_FACE_BACK_POS_Z: return glm::vec3(-faceDir.x, faceDir.y, faceDir.z); case gpu::Texture::CubeFace::CUBE_FACE_FRONT_NEG_Z: return glm::vec3(faceDir.x, faceDir.y, -faceDir.z); case gpu::Texture::CubeFace::CUBE_FACE_LEFT_NEG_X: return glm::vec3(faceDir.z, faceDir.y, faceDir.x); case gpu::Texture::CubeFace::CUBE_FACE_RIGHT_POS_X: return glm::vec3(-faceDir.z, faceDir.y, -faceDir.x); case gpu::Texture::CubeFace::CUBE_FACE_BOTTOM_NEG_Y: return glm::vec3(-faceDir.x, -faceDir.z, faceDir.y); case gpu::Texture::CubeFace::CUBE_FACE_TOP_POS_Y: default: return glm::vec3(-faceDir.x, faceDir.z, -faceDir.y); } } }; CubeToXYZ cubeToXYZ(face); struct RectToXYZ { RectToXYZ() {} glm::vec2 uvFrom(const glm::vec3& xyz) { auto flatDir = glm::normalize(glm::vec2(xyz.x, xyz.z)); auto uvRad = glm::vec2(atan2(flatDir.x, flatDir.y), asin(xyz.y)); const float LON_TO_RECT_U = 1.0f / (glm::pi()); const float LAT_TO_RECT_V = 2.0f / glm::pi(); return glm::vec2(0.5f * uvRad.x * LON_TO_RECT_U + 0.5f, 0.5f * uvRad.y * LAT_TO_RECT_V + 0.5f); } }; RectToXYZ rectToXYZ; int srcFaceHeight = source.getHeight(); int srcFaceWidth = source.getWidth(); glm::vec2 dstCoord; glm::ivec2 srcPixel; for (int y = 0; y < faceWidth; ++y) { QRgb* destScanLineBegin = reinterpret_cast( image.editScanLine(y) ); QRgb* destPixelIterator = destScanLineBegin; dstCoord.y = 1.0f - (y + 0.5f) * dstInvSize.y; // Fill cube face images from top to bottom for (int x = 0; x < faceWidth; ++x) { dstCoord.x = (x + 0.5f) * dstInvSize.x; auto xyzDir = cubeToXYZ.xyzFrom(dstCoord); auto srcCoord = rectToXYZ.uvFrom(xyzDir); srcPixel.x = floor(srcCoord.x * srcFaceWidth); // Flip the vertical axis to Image going top to bottom srcPixel.y = floor((1.0f - srcCoord.y) * srcFaceHeight); if (((uint32)srcPixel.x < (uint32)source.getWidth()) && ((uint32)srcPixel.y < (uint32)source.getHeight())) { // We can't directly use the pixel() method because that launches a pixel color conversion to output // a correct RGBA8 color. But in our case we may have stored HDR values encoded in a RGB30 format which // are not convertible by Qt. The same goes with the setPixel method, by the way. const QRgb* sourcePixelIterator = reinterpret_cast(source.getScanLine(srcPixel.y)); sourcePixelIterator += srcPixel.x; *destPixelIterator = *sourcePixelIterator; // Keep for debug, this is showing the dir as a color // glm::u8vec4 rgba((xyzDir.x + 1.0)*0.5 * 256, (xyzDir.y + 1.0)*0.5 * 256, (xyzDir.z + 1.0)*0.5 * 256, 256); // unsigned int val = 0xff000000 | (rgba.r) | (rgba.g << 8) | (rgba.b << 16); // *destPixelIterator = val; } ++destPixelIterator; } } return image; } }; const CubeLayout CubeLayout::CUBEMAP_LAYOUTS[] = { // Here is the expected layout for the faces in an image with the 2/1 aspect ratio: // THis is detected as an Equirectangular projection // WIDTH // <---------------------------> // ^ +------+------+------+------+ // H | | | | | // E | | | | | // I | | | | | // G +------+------+------+------+ // H | | | | | // T | | | | | // | | | | | | // v +------+------+------+------+ // // FaceWidth = width = height / 6 { 2, 1 }, // Here is the expected layout for the faces in an image with the 1/6 aspect ratio: // // WIDTH // <------> // ^ +------+ // | | | // | | +X | // | | | // H +------+ // E | | // I | -X | // G | | // H +------+ // T | | // | | +Y | // | | | // | +------+ // | | | // | | -Y | // | | | // H +------+ // E | | // I | +Z | // G | | // H +------+ // T | | // | | -Z | // | | | // V +------+ // // FaceWidth = width = height / 6 { 1, 6, { 0, 0, true, false }, { 0, 1, true, false }, { 0, 2, false, true }, { 0, 3, false, true }, { 0, 4, true, false }, { 0, 5, true, false } }, // Here is the expected layout for the faces in an image with the 3/4 aspect ratio: // // <-----------WIDTH-----------> // ^ +------+------+------+------+ // | | | | | | // | | | +Y | | | // | | | | | | // H +------+------+------+------+ // E | | | | | // I | -X | -Z | +X | +Z | // G | | | | | // H +------+------+------+------+ // T | | | | | // | | | -Y | | | // | | | | | | // V +------+------+------+------+ // // FaceWidth = width / 4 = height / 3 { 4, 3, { 2, 1, true, false }, { 0, 1, true, false }, { 1, 0, false, true }, { 1, 2, false, true }, { 3, 1, true, false }, { 1, 1, true, false } }, // Here is the expected layout for the faces in an image with the 4/3 aspect ratio: // // <-------WIDTH--------> // ^ +------+------+------+ // | | | | | // | | | +Y | | // | | | | | // H +------+------+------+ // E | | | | // I | -X | -Z | +X | // G | | | | // H +------+------+------+ // T | | | | // | | | -Y | | // | | | | | // | +------+------+------+ // | | | | | // | | | +Z! | | <+Z is upside down! // | | | | | // V +------+------+------+ // // FaceWidth = width / 3 = height / 4 { 3, 4, { 2, 1, true, false }, { 0, 1, true, false }, { 1, 0, false, true }, { 1, 2, false, true }, { 1, 3, false, true }, { 1, 1, true, false } } }; const int CubeLayout::NUM_CUBEMAP_LAYOUTS = sizeof(CubeLayout::CUBEMAP_LAYOUTS) / sizeof(CubeLayout); //#define DEBUG_COLOR_PACKING Image convertToLDRFormat(Image&& srcImage, Image::Format format) { // Take a local copy to force move construction // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f18-for-consume-parameters-pass-by-x-and-stdmove-the-parameter Image localCopy = std::move(srcImage); Image ldrImage(localCopy.getWidth(), localCopy.getHeight(), format); auto unpackFunc = getHDRUnpackingFunction(); for (glm::uint32 y = 0; y < localCopy.getHeight(); y++) { const QRgb* srcLineIt = reinterpret_cast(localCopy.getScanLine(y)); const QRgb* srcLineEnd = srcLineIt + localCopy.getWidth(); uint32* ldrLineIt = reinterpret_cast(ldrImage.editScanLine(y)); glm::vec3 color; while (srcLineIt < srcLineEnd) { color = unpackFunc(*srcLineIt); // Apply reverse gamma and clamp color.r = std::pow(color.r, 1.0f / 2.2f); color.g = std::pow(color.g, 1.0f / 2.2f); color.b = std::pow(color.b, 1.0f / 2.2f); color.r = std::min(1.0f, color.r) * 255.0f; color.g = std::min(1.0f, color.g) * 255.0f; color.b = std::min(1.0f, color.b) * 255.0f; *ldrLineIt = qRgb((int)color.r, (int)color.g, (int)color.b); ++srcLineIt; ++ldrLineIt; } } return ldrImage; } Image convertToHDRFormat(Image&& srcImage, gpu::Element format) { // Take a local copy to force move construction // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f18-for-consume-parameters-pass-by-x-and-stdmove-the-parameter Image localCopy = std::move(srcImage); Image hdrImage(localCopy.getWidth(), localCopy.getHeight(), Image::Format_PACKED_FLOAT); std::function packFunc; #ifdef DEBUG_COLOR_PACKING std::function unpackFunc; #endif switch (format.getSemantic()) { case gpu::R11G11B10: packFunc = packR11G11B10F; #ifdef DEBUG_COLOR_PACKING unpackFunc = glm::unpackF2x11_1x10; #endif break; case gpu::RGB9E5: packFunc = glm::packF3x9_E1x5; #ifdef DEBUG_COLOR_PACKING unpackFunc = glm::unpackF3x9_E1x5; #endif break; default: qCWarning(imagelogging) << ""Unsupported HDR format""; Q_UNREACHABLE(); return localCopy; } localCopy = localCopy.getConvertedToFormat(Image::Format_ARGB32); for (glm::uint32 y = 0; y < localCopy.getHeight(); y++) { const QRgb* srcLineIt = reinterpret_cast( localCopy.getScanLine(y) ); const QRgb* srcLineEnd = srcLineIt + localCopy.getWidth(); uint32* hdrLineIt = reinterpret_cast( hdrImage.editScanLine(y) ); glm::vec3 color; while (srcLineIt < srcLineEnd) { color.r = qRed(*srcLineIt); color.g = qGreen(*srcLineIt); color.b = qBlue(*srcLineIt); // Normalize and apply gamma color /= 255.0f; color.r = std::pow(color.r, 2.2f); color.g = std::pow(color.g, 2.2f); color.b = std::pow(color.b, 2.2f); *hdrLineIt = packFunc(color); #ifdef DEBUG_COLOR_PACKING glm::vec3 ucolor = unpackFunc(*hdrLineIt); assert(glm::distance(color, ucolor) <= 5e-2); #endif ++srcLineIt; ++hdrLineIt; } } return hdrImage; } gpu::TexturePointer TextureUsage::processCubeTextureColorFromImage(Image&& srcImage, const std::string& srcImageName, bool compress, BackendTarget target, bool generateIrradiance, const std::atomic& abortProcessing) { PROFILE_RANGE(resource_parse, ""processCubeTextureColorFromImage""); // Take a local copy to force move construction // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f18-for-consume-parameters-pass-by-x-and-stdmove-the-parameter Image localCopy = std::move(srcImage); int originalWidth = localCopy.getWidth(); int originalHeight = localCopy.getHeight(); if ((originalWidth <= 0) && (originalHeight <= 0)) { return nullptr; } gpu::TexturePointer theTexture = nullptr; Image image = processSourceImage(std::move(localCopy), true, target); auto hasTargetHDRFormat = isHDRTextureFormatEnabledForTarget(target); if (hasTargetHDRFormat && image.getFormat() != Image::Format_PACKED_FLOAT) { // If the target format is HDR but the image isn't, we need to convert the // image to HDR. image = convertToHDRFormat(std::move(image), GPU_CUBEMAP_HDR_FORMAT); } else if (!hasTargetHDRFormat && image.getFormat() == Image::Format_PACKED_FLOAT) { // If the target format isn't HDR (such as on GLES) but the image is, we need to // convert the image to LDR image = convertToLDRFormat(std::move(image), Image::Format_ARGB32); } gpu::Element formatGPU = getHDRTextureFormatForTarget(target, compress); gpu::Element formatMip = formatGPU; // Find the layout of the cubemap in the 2D image // Use the original image size since processSourceImage may have altered the size / aspect ratio int foundLayout = CubeLayout::findLayout(originalWidth, originalHeight); if (foundLayout < 0) { qCDebug(imagelogging) << ""Failed to find a known cube map layout from this image:"" << QString(srcImageName.c_str()); return nullptr; } std::vector faces; // If found, go extract the faces as separate images auto& layout = CubeLayout::CUBEMAP_LAYOUTS[foundLayout]; if (layout._type == CubeLayout::FLAT) { int faceWidth = image.getWidth() / layout._widthRatio; faces.push_back(image.getSubImage(QRect(layout._faceXPos._x * faceWidth, layout._faceXPos._y * faceWidth, faceWidth, faceWidth)).getMirrored(layout._faceXPos._horizontalMirror, layout._faceXPos._verticalMirror)); faces.push_back(image.getSubImage(QRect(layout._faceXNeg._x * faceWidth, layout._faceXNeg._y * faceWidth, faceWidth, faceWidth)).getMirrored(layout._faceXNeg._horizontalMirror, layout._faceXNeg._verticalMirror)); faces.push_back(image.getSubImage(QRect(layout._faceYPos._x * faceWidth, layout._faceYPos._y * faceWidth, faceWidth, faceWidth)).getMirrored(layout._faceYPos._horizontalMirror, layout._faceYPos._verticalMirror)); faces.push_back(image.getSubImage(QRect(layout._faceYNeg._x * faceWidth, layout._faceYNeg._y * faceWidth, faceWidth, faceWidth)).getMirrored(layout._faceYNeg._horizontalMirror, layout._faceYNeg._verticalMirror)); faces.push_back(image.getSubImage(QRect(layout._faceZPos._x * faceWidth, layout._faceZPos._y * faceWidth, faceWidth, faceWidth)).getMirrored(layout._faceZPos._horizontalMirror, layout._faceZPos._verticalMirror)); faces.push_back(image.getSubImage(QRect(layout._faceZNeg._x * faceWidth, layout._faceZNeg._y * faceWidth, faceWidth, faceWidth)).getMirrored(layout._faceZNeg._horizontalMirror, layout._faceZNeg._verticalMirror)); } else if (layout._type == CubeLayout::EQUIRECTANGULAR) { // THe face width is estimated from the input image const int EQUIRECT_FACE_RATIO_TO_WIDTH = 4; const int EQUIRECT_MAX_FACE_WIDTH = 2048; int faceWidth = std::min(image.getWidth() / EQUIRECT_FACE_RATIO_TO_WIDTH, EQUIRECT_MAX_FACE_WIDTH); for (int face = gpu::Texture::CUBE_FACE_RIGHT_POS_X; face < gpu::Texture::NUM_CUBE_FACES; face++) { Image faceImage = CubeLayout::extractEquirectangularFace(std::move(image), (gpu::Texture::CubeFace) face, faceWidth); faces.push_back(std::move(faceImage)); } } // free up the memory afterward to avoid bloating the heap image = Image(); // Image doesn't have a clear function, so override it with an empty one. // If the 6 faces have been created go on and define the true Texture if (faces.size() == gpu::Texture::NUM_FACES_PER_TYPE[gpu::Texture::TEX_CUBE]) { theTexture = gpu::Texture::createCube(formatGPU, faces[0].getWidth(), gpu::Texture::MAX_NUM_MIPS, gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR, gpu::Sampler::WRAP_CLAMP)); theTexture->setSource(srcImageName); theTexture->setStoredMipFormat(formatMip); // Generate irradiance while we are at it if (generateIrradiance) { PROFILE_RANGE(resource_parse, ""generateIrradiance""); gpu::Element irradianceFormat; // TODO: we could locally compress the irradiance texture on Android, but we don't need to if (target == BackendTarget::GLES32) { irradianceFormat = gpu::Element::COLOR_SRGBA_32; } else { irradianceFormat = GPU_CUBEMAP_HDR_FORMAT; } auto irradianceTexture = gpu::Texture::createCube(irradianceFormat, faces[0].getWidth(), gpu::Texture::MAX_NUM_MIPS, gpu::Sampler(gpu::Sampler::FILTER_MIN_MAG_MIP_LINEAR, gpu::Sampler::WRAP_CLAMP)); irradianceTexture->setSource(srcImageName); irradianceTexture->setStoredMipFormat(irradianceFormat); for (uint8 face = 0; face < faces.size(); ++face) { irradianceTexture->assignStoredMipFace(0, face, faces[face].getByteCount(), faces[face].getBits()); } irradianceTexture->generateIrradiance(target); auto irradiance = irradianceTexture->getIrradiance(); theTexture->overrideIrradiance(irradiance); } for (uint8 face = 0; face < faces.size(); ++face) { generateMips(theTexture.get(), std::move(faces[face]), target, abortProcessing, face); } } return theTexture; } } // namespace image ",16262,True,2816.625777353346,median "= HL7 Supplied Schemas :page-aliases: connectors::hl7/hl7-schemas.adoc These are the message structures included in the schema definitions for each version of HL7. == Version 2.1 ACK ADR_A19 ADT_A01 ADT_A02 ADT_A03 ADT_A04 ADT_A05 ADT_A06 ADT_A07 ADT_A08 ADT_A09 ADT_A10 ADT_A11 ADT_A12 ADT_A13 ADT_A14 ADT_A15 ADT_A16 ADT_A17 ADT_A18 ADT_A20 ADT_A21 ADT_A22 ADT_A23 ADT_A24 BAR_P01 BAR_P02 DFT_P03 DSR_Q01 DSR_Q03 MCF_Q02 ORM_O01 ORR_O02 ORU_R01 ORU_R03 QRY_A19 QRY_Q01 QRY_Q02 UDM_Q05 == Version 2.2 ACK ADR_A19 ADT_A01 ADT_A02 ADT_A03 ADT_A04 ADT_A05 ADT_A06 ADT_A07 ADT_A08 ADT_A09 ADT_A10 ADT_A11 ADT_A12 ADT_A13 ADT_A14 ADT_A15 ADT_A16 ADT_A17 ADT_A18 ADT_A20 ADT_A21 ADT_A22 ADT_A23 ADT_A24 ADT_A25 ADT_A26 ADT_A27 ADT_A28 ADT_A29 ADT_A30 ADT_A31 ADT_A32 ADT_A33 ADT_A34 ADT_A35 ADT_A36 ADT_A37 BAR_P01 BAR_P02 DFT_P03 DSR_P04 DSR_Q01 DSR_Q03 DSR_R03 MFD_M01 MFD_M02 MFD_M03 MFK_M01 MFK_M02 MFK_M03 MFN_M01 MFN_M02 MFN_M03 MFQ_M01 MFQ_M02 MFQ_M03 MFR_M01 MFR_M02 MFR_M03 NMD_N01 NMQ_N02 NMR_N02 ORD_O02 ORF_R04 ORM_O01 ORN_O02 ORR_O02 ORU_R01 ORU_R03 QRY_A19 QRY_P04 QRY_Q01 QRY_Q02 QRY_R02 UDM_Q05 == Version 2.3 ACK ADR_A19 ADT_A01 ADT_A02 ADT_A03 ADT_A04 ADT_A05 ADT_A06 ADT_A07 ADT_A08 ADT_A09 ADT_A10 ADT_A11 ADT_A12 ADT_A13 ADT_A14 ADT_A15 ADT_A16 ADT_A17 ADT_A18 ADT_A20 ADT_A21 ADT_A22 ADT_A23 ADT_A24 ADT_A25 ADT_A26 ADT_A27 ADT_A28 ADT_A29 ADT_A30 ADT_A31 ADT_A32 ADT_A33 ADT_A34 ADT_A35 ADT_A36 ADT_A37 ADT_A38 ADT_A39 ADT_A40 ADT_A41 ADT_A42 ADT_A43 ADT_A44 ADT_A45 ADT_A46 ADT_A47 ADT_A48 ADT_A49 ADT_A50 ADT_A51 BAR_P01 BAR_P02 BAR_P05 BAR_P06 CRM_C01 CRM_C02 CRM_C03 CRM_C04 CRM_C05 CRM_C06 CRM_C07 CRM_C08 CSU_C09 CSU_C10 CSU_C11 CSU_C12 DFT_P03 DOC_T12 DSR_Q01 DSR_Q02 DSR_Q03 EDR_Q01 EQQ_Q01 ERP_Q01 MDM_T01 MDM_T02 MDM_T03 MDM_T04 MDM_T05 MDM_T06 MDM_T07 MDM_T08 MDM_T09 MDM_T10 MDM_T11 MFK_M01 MFK_M02 MFK_M03 MFK_M04 MFK_M05 MFK_M07 MFN_M01 MFN_M02 MFN_M03 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 OMD_O01 OMN_O01 OMS_O01 ORD_O02 ORF_R02 ORF_R04 ORM_O01 ORN_O02 ORR_O02 ORU_R01 OSQ_Q06 OSR_Q06 PEX_P07 PEX_P08 PGL_PC6 PGL_PC7 PGL_PC8 PIN_I07 PPG_PCG PPG_PCH PPG_PCJ PPP_PCB PPP_PCC PPP_PCD PPR_PC1 PPR_PC2 PPR_PC3 PPT_PCL PPV_PCA PRR_PC5 PTR_PCF QCK_Q02 QRY_A19 QRY_PC4 QRY_PC9 QRY_PCE QRY_PCK QRY_Q01 QRY_Q02 QRY_R02 QRY_T12 RAR_RAR RAS_O01 RAS_O02 RCI_I05 RCL_I06 RDE_O01 RDO_O01 RDR_RDR RDS_O01 REF_I12 REF_I13 REF_I14 REF_I15 RER_RER RGR_RGR RGV_O01 ROR_ROR RPA_I08 RPA_I09 RPA_I10 RPA_I11 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQA_I09 RQA_I10 RQA_I11 RQC_I05 RQC_I06 RQI_I01 RQI_I02 RQI_I03 RQP_I04 RQQ_Q01 RRA_O02 RRD_O02 RRE_O01 RRG_O02 RRI_I12 RRI_I13 RRI_I14 RRI_I15 RRO_O02 SIU_S12 SIU_S13 SIU_S14 SIU_S15 SIU_S16 SIU_S17 SIU_S18 SIU_S19 SIU_S20 SIU_S21 SIU_S22 SIU_S23 SIU_S24 SIU_S26 SPQ_Q01 SQM_S25 SQR_S25 SRM_S01 SRM_S02 SRM_S03 SRM_S04 SRM_S05 SRM_S06 SRM_S07 SRM_S08 SRM_S09 SRM_S10 SRM_S11 SRR_S01 SRR_S02 SRR_S03 SRR_S04 SRR_S05 SRR_S06 SRR_S07 SRR_S08 SRR_S09 SRR_S10 SRR_S11 SUR_P09 TBR_Q01 UDM_Q05 VQQ_Q01 VXQ_V01 VXR_V03 VXU_V04 VXX_V02 == Version 2.3.1 ACK ADR_A19 ADT_A01 ADT_A02 ADT_A03 ADT_A04 ADT_A05 ADT_A06 ADT_A07 ADT_A08 ADT_A09 ADT_A10 ADT_A11 ADT_A12 ADT_A13 ADT_A14 ADT_A15 ADT_A16 ADT_A17 ADT_A18 ADT_A20 ADT_A21 ADT_A22 ADT_A23 ADT_A24 ADT_A25 ADT_A26 ADT_A27 ADT_A28 ADT_A29 ADT_A30 ADT_A31 ADT_A32 ADT_A33 ADT_A34 ADT_A35 ADT_A36 ADT_A37 ADT_A38 ADT_A39 ADT_A40 ADT_A41 ADT_A42 ADT_A43 ADT_A44 ADT_A45 ADT_A46 ADT_A47 ADT_A48 ADT_A49 ADT_A50 ADT_A51 BAR_P01 BAR_P02 BAR_P05 BAR_P06 CRM_C01 CSU_C09 DFT_P03 DOC_T12 DSR_Q01 DSR_Q03 EDR_R07 EQQ_Q04 ERP_R09 MDM_T01 MDM_T02 MDM_T03 MDM_T04 MDM_T05 MDM_T06 MDM_T07 MDM_T08 MDM_T09 MDM_T10 MDM_T11 MFK_M01 MFK_M04 MFK_M05 MFK_M06 MFN_M01 MFN_M02 MFN_M03 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFQ_M01 MFR_M01 NMD_N02 NMQ_N01 NMR_N01 OMD_O01 OMN_O01 OMS_O01 ORD_O02 ORF_R04 ORM_O01 ORN_O02 ORR_O02 ORS_O02 ORU_R01 OSQ_Q06 OSR_Q06 PEX_P07 PGL_PC6 PIN_I07 PPG_PCG PPP_PCB PPR_PC1 PPT_PCL PPV_PCA PRR_PC5 PTR_PCF QCK_Q02 QRY_A19 QRY_PC4 QRY_PC9 QRY_PCE QRY_PCK QRY_Q01 QRY_Q02 QRY_R02 QRY_T12 RAR_RAR RAS_O01 RCI_I05 RCL_I06 RDE_O01 RDO_O01 RDR_RDR RDS_O01 REF_I12 RER_RER RGR_RGR RGV_O01 ROR_R0R ROR_ROR RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQC_I05 RQC_I06 RQI_I01 RQI_I02 RQI_I03 RQP_I04 RQQ_Q09 RRA_O02 RRD_O02 RRE_O02 RRG_O02 RRI_I12 RRO_O02 SIU_S12 SPQ_Q08 SQM_S25 SQR_S25 SRM_S01 SRR_S01 SUR_P09 TBR_R08 UDM_Q05 VQQ_Q07 VXQ_V01 VXR_V03 VXU_V04 VXX_V02 == Version 2.4 ACK ADR_A19 ADT_A01 ADT_A02 ADT_A03 ADT_A05 ADT_A06 ADT_A09 ADT_A15 ADT_A16 ADT_A17 ADT_A18 ADT_A20 ADT_A21 ADT_A24 ADT_A30 ADT_A37 ADT_A38 ADT_A39 ADT_A43 ADT_A45 ADT_A50 ADT_A52 ADT_A54 ADT_A60 ADT_A61 BAR_P01 BAR_P02 BAR_P05 BAR_P06 BAR_P10 CRM_C01 CSU_C09 DFT_P03 DFT_P11 DOC_T12 DSR_Q01 DSR_Q03 EAC_U07 EAN_U09 EAR_U08 EDR_R07 EQQ_Q04 ERP_R09 ESR_U02 ESU_U01 INR_U06 INU_U05 LSU_U12 MDM_T01 MDM_T02 MFK_M01 MFN_M01 MFN_M02 MFN_M03 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFN_M12 MFQ_M01 MFR_M01 NMD_N02 NMQ_N01 NMR_N01 OMD_O03 OMG_O19 OML_O21 OMN_O07 OMP_O09 OMS_O05 ORD_O04 ORF_R04 ORG_O20 ORL_O22 ORM_O01 ORN_O08 ORP_O10 ORR_O02 ORS_O06 ORU_R01 OSQ_Q06 OSR_Q06 OUL_R21 PEX_P07 PGL_PC6 PMU_B01 PMU_B03 PMU_B04 PPG_PCG PPP_PCB PPR_PC1 PPT_PCL PPV_PCA PRR_PC5 PTR_PCF QBP_K13 QBP_Q11 QBP_Q13 QBP_Q15 QBP_Q21 QBP_Qnn QBP_Z73 QCK_Q02 QCN_J01 QRY_A19 QRY_PC4 QRY_Q01 QRY_Q02 QRY_R02 QRY_T12 QSB_Q16 QVR_Q17 RAR_RAR RAS_O17 RCI_I05 RCL_I06 RDE_O11 RDR_RDR RDS_O13 RDY_K15 REF_I12 RER_RER RGR_RGR RGV_O15 ROR_ROR RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQC_I05 RQI_I01 RQP_I04 RQQ_Q09 RRA_O18 RRD_O14 RRE_O12 RRG_O16 RRI_I12 RSP_K11 RSP_K13 RSP_K15 RSP_K21 RSP_K22 RSP_K23 RSP_K24 RSP_K25 RSP_Z82 RSP_Z86 RSP_Z88 RSP_Z90 RTB_K13 RTB_Knn RTB_Q13 RTB_Z74 SIU_S12 SPQ_Q08 SQM_S25 SQR_S25 SRM_S01 SRR_S01 SSR_U04 SSU_U03 SUR_P09 TBR_R08 TCU_U10 UDM_Q05 VQQ_Q07 VXQ_V01 VXR_V03 VXU_V04 VXX_V02 == Version 2.5 ACK ADR_A19 ADT_A01 ADT_A02 ADT_A03 ADT_A05 ADT_A06 ADT_A09 ADT_A12 ADT_A15 ADT_A16 ADT_A17 ADT_A18 ADT_A20 ADT_A21 ADT_A24 ADT_A30 ADT_A37 ADT_A38 ADT_A39 ADT_A43 ADT_A45 ADT_A50 ADT_A52 ADT_A54 ADT_A60 ADT_A61 BAR_P01 BAR_P02 BAR_P05 BAR_P06 BAR_P10 BAR_P12 BPS_O29 BRP_O30 BRT_O32 BTS_O31 CRM_C01 CSU_C09 DFT_P03 DFT_P11 DOC_T12 DSR_Q01 DSR_Q03 EAC_U07 EAN_U09 EAR_U08 EDR_R07 EQQ_Q04 ERP_R09 ESR_U02 ESU_U01 INR_U06 INU_U05 LSU_U12 MDM_T01 MDM_T02 MFK_M01 MFN_M01 MFN_M02 MFN_M03 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFN_M12 MFN_M13 MFN_M15 MFN_Znn MFQ_M01 MFR_M01 MFR_M04 MFR_M05 MFR_M06 MFR_M07 NMD_N02 NMQ_N01 NMR_N01 OMB_O27 OMD_O03 OMG_O19 OMI_O23 OML_O21 OML_O33 OML_O35 OMN_O07 OMP_O09 OMS_O05 ORB_O28 ORD_O04 ORF_R04 ORG_O20 ORI_O24 ORL_O22 ORL_O34 ORL_O36 ORM_O01 ORN_O08 ORP_O10 ORR_O02 ORS_O06 ORU_R01 ORU_R30 OSQ_Q06 OSR_Q06 OUL_R21 OUL_R22 OUL_R23 OUL_R24 PEX_P07 PGL_PC6 PMU_B01 PMU_B03 PMU_B04 PMU_B07 PMU_B08 PPG_PCG PPP_PCB PPR_PC1 PPT_PCL PPV_PCA PRR_PC5 PTR_PCF QBP_K13 QBP_Q11 QBP_Q13 QBP_Q15 QBP_Q21 QBP_Qnn QBP_Z73 QCK_Q02 QCN_J01 QRY QRY_A19 QRY_PC4 QRY_Q01 QRY_Q02 QRY_R02 QSB_Q16 QVR_Q17 RAR_RAR RAS_O17 RCI_I05 RCL_I06 RDE_O11 RDR_RDR RDS_O13 RDY_K15 REF_I12 RER_RER RGR_RGR RGV_O15 ROR_ROR RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQC_I05 RQI_I01 RQP_I04 RQQ_Q09 RRA_O18 RRD_O14 RRE_O12 RRG_O16 RRI_I12 RSP_K11 RSP_K21 RSP_K23 RSP_K25 RSP_K31 RSP_Q11 RSP_Z82 RSP_Z86 RSP_Z88 RSP_Z90 RTB_K13 RTB_Knn RTB_Z74 SIU_S12 SPQ_Q08 SQM_S25 SQR_S25 SRM_S01 SRR_S01 SSR_U04 SSU_U03 SUR_P09 TBR_R08 TCU_U10 UDM_Q05 VQQ_Q07 VXQ_V01 VXR_V03 VXU_V04 VXX_V02 == Version 2.5.1 ACK ADR_A19 ADT_A01 ADT_A02 ADT_A03 ADT_A05 ADT_A06 ADT_A09 ADT_A12 ADT_A15 ADT_A16 ADT_A17 ADT_A18 ADT_A20 ADT_A21 ADT_A24 ADT_A30 ADT_A37 ADT_A38 ADT_A39 ADT_A43 ADT_A45 ADT_A50 ADT_A52 ADT_A54 ADT_A60 ADT_A61 BAR_P01 BAR_P02 BAR_P05 BAR_P06 BAR_P10 BAR_P12 BPS_O29 BRP_O30 BRT_O32 BTS_O31 CRM_C01 CSU_C09 DFT_P03 DFT_P11 DOC_T12 DSR_Q01 DSR_Q03 EAC_U07 EAN_U09 EAR_U08 EDR_R07 EQQ_Q04 ERP_R09 ESR_U02 ESU_U01 INR_U06 INU_U05 LSU_U12 MDM_T01 MDM_T02 MFK_M01 MFN_M01 MFN_M02 MFN_M03 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFN_M12 MFN_M13 MFN_M15 MFN_Znn MFQ_M01 MFR_M01 MFR_M04 MFR_M05 MFR_M06 MFR_M07 NMD_N02 NMQ_N01 NMR_N01 OMB_O27 OMD_O03 OMG_O19 OMI_O23 OML_O21 OML_O33 OML_O35 OMN_O07 OMP_O09 OMS_O05 ORB_O28 ORD_O04 ORF_R04 ORG_O20 ORI_O24 ORL_O22 ORL_O34 ORL_O36 ORM_O01 ORN_O08 ORP_O10 ORR_O02 ORS_O06 ORU_R01 ORU_R30 OSQ_Q06 OSR_Q06 OUL_R21 OUL_R22 OUL_R23 OUL_R24 PEX_P07 PGL_PC6 PMU_B01 PMU_B03 PMU_B04 PMU_B07 PMU_B08 PPG_PCG PPP_PCB PPR_PC1 PPT_PCL PPV_PCA PRR_PC5 PTR_PCF QBP_Q11 QBP_Q13 QBP_Q15 QBP_Q21 QBP_Qnn QBP_Z73 QCK_Q02 QCN_J01 QRY QRY_A19 QRY_PC4 QRY_Q01 QRY_Q02 QRY_R02 QSB_Q16 QVR_Q17 RAR_RAR RAS_O17 RCI_I05 RCL_I06 RDE_O11 RDR_RDR RDS_O13 RDY_K15 REF_I12 RER_RER RGR_RGR RGV_O15 ROR_ROR RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQC_I05 RQI_I01 RQP_I04 RQQ_Q09 RRA_O18 RRD_O14 RRE_O12 RRG_O16 RRI_I12 RSP_K11 RSP_K21 RSP_K23 RSP_K25 RSP_K31 RSP_Q11 RSP_Z82 RSP_Z86 RSP_Z88 RSP_Z90 RTB_K13 RTB_Knn RTB_Z74 SIU_S12 SPQ_Q08 SQM_S25 SQR_S25 SRM_S01 SRR_S01 SSR_U04 SSU_U03 SUR_P09 TBR_R08 TCU_U10 UDM_Q05 VQQ_Q07 VXQ_V01 VXR_V03 VXU_V04 VXX_V02 == Version 2.6 ACK ADR_A19 ADT_A01 ADT_A02 ADT_A03 ADT_A05 ADT_A06 ADT_A09 ADT_A12 ADT_A15 ADT_A16 ADT_A17 ADT_A18 ADT_A20 ADT_A21 ADT_A24 ADT_A30 ADT_A37 ADT_A38 ADT_A39 ADT_A43 ADT_A45 ADT_A50 ADT_A52 ADT_A54 ADT_A60 ADT_A61 BAR_P01 BAR_P02 BAR_P05 BAR_P06 BAR_P10 BAR_P12 BPS_O29 BRP_O30 BRT_O32 BTS_O31 CRM_C01 CSU_C09 DFT_P03 DFT_P11 DOC_T12 DSR_Q01 DSR_Q03 EAC_U07 EAN_U09 EAR_U08 EHC_E01 EHC_E02 EHC_E04 EHC_E10 EHC_E12 EHC_E13 EHC_E15 EHC_E20 EHC_E21 EHC_E24 ESR_U02 ESU_U01 INR_U06 INU_U05 LSU_U12 MDM_T01 MDM_T02 MFK_M01 MFN_M01 MFN_M02 MFN_M03 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFN_M12 MFN_M13 MFN_M15 MFN_M16 MFN_M17 MFN_Znn MFQ_M01 MFR_M01 MFR_M04 MFR_M05 MFR_M06 MFR_M07 NMD_N02 NMQ_N01 NMR_N01 OMB_O27 OMD_O03 OMG_O19 OMI_O23 OML_O21 OML_O33 OML_O35 OMN_O07 OMP_O09 OMS_O05 OPL_O37 OPR_O38 OPU_R25 ORB_O28 ORD_O04 ORF_R04 ORG_O20 ORI_O24 ORL_O22 ORL_O34 ORL_O36 ORM_O01 ORN_O08 ORP_O10 ORR_O02 ORS_O06 ORU_R01 ORU_R30 OSQ_Q06 OSR_Q06 OUL_R21 OUL_R22 OUL_R23 OUL_R24 PEX_P07 PGL_PC6 PMU_B01 PMU_B03 PMU_B04 PMU_B07 PMU_B08 PPG_PCG PPP_PCB PPR_PC1 PPT_PCL PPV_PCA PRR_PC5 PTR_PCF QBP_E03 QBP_E22 QBP_Q11 QBP_Q13 QBP_Q15 QBP_Q21 QBP_Qnn QBP_Z73 QCK_Q02 QCN_J01 QRY_A19 QRY_PC4 QRY_Q01 QRY_Q02 QRY_R02 QRY_T12 QSB_Q16 QVR_Q17 RAR_RAR RAS_O17 RCI_I05 RCL_I06 RDE_O11 RDR_RDR RDS_O13 RDY_K15 REF_I12 RER_RER RGR_RGR RGV_O15 ROR_ROR RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQC_I05 RQI_I01 RQP_I04 RRA_O18 RRD_O14 RRE_O12 RRG_O16 RRI_I12 RSP_E03 RSP_E22 RSP_K11 RSP_K21 RSP_K23 RSP_K25 RSP_K31 RSP_Q11 RSP_Z82 RSP_Z86 RSP_Z88 RSP_Z90 RTB_K13 RTB_Z74 SDR_S31 SDR_S32 SIU_S12 SLR_S28 SQM_S25 SQR_S25 SRM_S01 SRR_S01 SSR_U04 SSU_U03 STC_S33 SUR_P09 TCU_U10 UDM_Q05 VXQ_V01 VXR_V03 VXU_V04 VXX_V02 == Version 2.7 ACK ADT_A01 ADT_A02 ADT_A03 ADT_A05 ADT_A06 ADT_A09 ADT_A12 ADT_A15 ADT_A16 ADT_A17 ADT_A20 ADT_A21 ADT_A24 ADT_A37 ADT_A38 ADT_A39 ADT_A43 ADT_A44 ADT_A45 ADT_A50 ADT_A52 ADT_A54 ADT_A60 ADT_A61 BAR_P01 BAR_P02 BAR_P05 BAR_P06 BAR_P10 BAR_P12 BPS_O29 BRP_O30 BRT_O32 BTS_O31 CCF_I22 CCI_I22 CCM_I21 CCQ_I19 CCR_I16 CCU_I20 CQU_I19 CRM_C01 CSU_C09 DFT_P03 DFT_P11 EAC_U07 EAN_U09 EAR_U08 EHC_E01 EHC_E02 EHC_E04 EHC_E10 EHC_E12 EHC_E13 EHC_E15 EHC_E20 EHC_E21 EHC_E24 ESR_U02 ESU_U01 INR_U06 INU_U05 LSU_U12 MDM_T01 MDM_T02 MFK_M01 MFN_M02 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFN_M12 MFN_M13 MFN_M15 MFN_M16 MFN_M17 MFN_Znn NMD_N02 OMB_O27 OMD_O03 OMG_O19 OMI_O23 OML_O21 OML_O33 OML_O35 OML_O39 OMN_O07 OMP_O09 OMS_O05 OPL_O37 OPR_O38 OPU_R25 ORA_R33 ORB_O28 ORD_O04 ORG_O20 ORI_O24 ORL_O22 ORL_O34 ORL_O36 ORL_O40 ORN_O08 ORP_O10 ORS_O06 ORU_R01 ORU_R30 OSM_R26 OUL_R22 OUL_R23 OUL_R24 PEX_P07 PGL_PC6 PMU_B01 PMU_B03 PMU_B04 PMU_B07 PMU_B08 PPG_PCG PPP_PCB PPR_PC1 PPT_PCL PPV_PCA PRR_PC5 PTR_PCF QBP_E03 QBP_E22 QBP_Q11 QBP_Q13 QBP_Q15 QBP_Q21 QBP_Qnn QBP_Z73 QCN_J01 QRY_PC4 QSB_Q16 QVR_Q17 RAS_O17 RCI_I05 RCL_I06 RDE_O11 RDR_RDR RDS_O13 RDY_K15 REF_I12 RGV_O15 RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQC_I05 RQI_I01 RQP_I04 RRA_O18 RRD_O14 RRE_O12 RRG_O16 RRI_I12 RSP_E03 RSP_E22 RSP_K11 RSP_K21 RSP_K22 RSP_K23 RSP_K25 RSP_K31 RSP_K32 RSP_Z82 RSP_Z86 RSP_Z88 RSP_Z90 RTB_K13 RTB_Knn RTB_Z74 SDR_S31 SDR_S32 SIU_S12 SLR_S28 SRM_S01 SRR_S01 SSR_U04 SSU_U03 STC_S33 TCU_U10 UDM_Q05 VXU_V04 == Version 2.7.1 ACK ADT_A01 ADT_A02 ADT_A03 ADT_A05 ADT_A06 ADT_A09 ADT_A12 ADT_A15 ADT_A16 ADT_A17 ADT_A20 ADT_A21 ADT_A24 ADT_A37 ADT_A38 ADT_A39 ADT_A43 ADT_A44 ADT_A45 ADT_A50 ADT_A52 ADT_A54 ADT_A60 ADT_A61 BAR_P01 BAR_P02 BAR_P05 BAR_P06 BAR_P10 BAR_P12 BPS_O29 BRP_O30 BRT_O32 BTS_O31 CCF_I22 CCI_I22 CCM_I21 CCQ_I19 CCR_I16 CCU_I20 CQU_I19 CRM_C01 CSU_C09 DFT_P03 DFT_P11 EAC_U07 EAN_U09 EAR_U08 EHC_E01 EHC_E02 EHC_E04 EHC_E10 EHC_E12 EHC_E13 EHC_E15 EHC_E20 EHC_E21 EHC_E24 ESR_U02 ESU_U01 INR_U06 INU_U05 LSU_U12 MDM_T01 MDM_T02 MFK_M01 MFN_M02 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFN_M12 MFN_M13 MFN_M15 MFN_M16 MFN_M17 MFN_Znn NMD_N02 OMB_O27 OMD_O03 OMG_O19 OMI_O23 OML_O21 OML_O33 OML_O35 OML_O39 OMN_O07 OMP_O09 OMS_O05 OPL_O37 OPR_O38 OPU_R25 ORA_R33 ORB_O28 ORD_O04 ORG_O20 ORI_O24 ORL_O22 ORL_O34 ORL_O36 ORL_O40 ORN_O08 ORP_O10 ORS_O06 ORU_R01 ORU_R30 OSM_R26 OUL_R22 OUL_R23 OUL_R24 PEX_P07 PGL_PC6 PMU_B01 PMU_B03 PMU_B04 PMU_B07 PMU_B08 PPG_PCG PPP_PCB PPR_PC1 PPT_PCL PPV_PCA PRR_PC5 PTR_PCF QBP_E03 QBP_E22 QBP_Q11 QBP_Q13 QBP_Q15 QBP_Q21 QBP_Qnn QBP_Z73 QCN_J01 QRY_PC4 QSB_Q16 QVR_Q17 RAS_O17 RCI_I05 RCL_I06 RDE_O11 RDR_RDR RDS_O13 RDY_K15 REF_I12 RGV_O15 RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQC_I05 RQI_I01 RQP_I04 RRA_O18 RRD_O14 RRE_O12 RRG_O16 RRI_I12 RSP_E03 RSP_E22 RSP_K11 RSP_K21 RSP_K22 RSP_K23 RSP_K25 RSP_K31 RSP_K32 RSP_Z82 RSP_Z86 RSP_Z88 RSP_Z90 RTB_K13 RTB_Knn RTB_Z74 SDR_S31 SDR_S32 SIU_S12 SLR_S28 SRM_S01 SRR_S01 SSR_U04 SSU_U03 STC_S33 TCU_U10 UDM_Q05 VXU_V04 == Version 2.8 ACK ADT_A01 ADT_A02 ADT_A03 ADT_A05 ADT_A06 ADT_A09 ADT_A12 ADT_A15 ADT_A16 ADT_A17 ADT_A20 ADT_A21 ADT_A24 ADT_A37 ADT_A38 ADT_A39 ADT_A43 ADT_A44 ADT_A45 ADT_A50 ADT_A52 ADT_A54 ADT_A60 ADT_A61 BAR_P01 BAR_P02 BAR_P05 BAR_P06 BAR_P10 BAR_P12 BPS_O29 BRP_O30 BRT_O32 BTS_O31 CCF_I22 CCI_I22 CCM_I21 CCQ_I19 CCR_I16 CCU_I20 CQU_I19 CRM_C01 CSU_C09 DBC_O41 DBC_O42 DEL_O46 DEO_O45 DER_O44 DFT_P03 DFT_P11 DPR_O48 DRC_O47 DRG_O43 EAC_U07 EAN_U09 EAR_U08 EHC_E01 EHC_E02 EHC_E04 EHC_E10 EHC_E12 EHC_E13 EHC_E15 EHC_E20 EHC_E21 EHC_E24 ESR_U02 ESU_U01 INR_U06 INU_U05 LSU_U12 MDM_T01 MDM_T02 MFK_M01 MFN_M02 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFN_M12 MFN_M13 MFN_M15 MFN_M16 MFN_M17 MFN_Znn NMD_N02 OMB_O27 OMD_O03 OMG_O19 OMI_O23 OML_O21 OML_O33 OML_O35 OML_O39 OMN_O07 OMP_O09 OMQ_O42 OMS_O05 OPL_O37 OPR_O38 OPU_R25 ORA_R33 ORA_R41 ORB_O28 ORD_O04 ORG_O20 ORI_O24 ORL_O22 ORL_O34 ORL_O36 ORL_O40 ORN_O08 ORP_O10 ORS_O06 ORU_R01 ORU_R30 ORX_O43 OSM_R26 OSU_O41 OUL_R22 OUL_R23 OUL_R24 PEX_P07 PGL_PC6 PMU_B01 PMU_B03 PMU_B04 PMU_B07 PMU_B08 PPG_PCG PPP_PCB PPR_PC1 QBP_E03 QBP_E22 QBP_O33 QBP_O34 QBP_Q11 QBP_Q13 QBP_Q15 QBP_Q21 QBP_Qnn QBP_Z73 QCN_J01 QSB_Q16 QVR_Q17 RAS_O17 RDE_O11 RDR_RDR RDS_O13 RDY_K15 RDY_Z80 REF_I12 RGV_O15 RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQI_I01 RQP_I04 RRA_O18 RRD_O14 RRE_O12 RRG_O16 RRI_I12 RSP_E03 RSP_E22 RSP_K11 RSP_K21 RSP_K22 RSP_K23 RSP_K25 RSP_K31 RSP_K32 RSP_O33 RSP_O34 RSP_Z82 RSP_Z84 RSP_Z86 RSP_Z88 RSP_Z90 RSP_Znn RTB_K13 RTB_Knn RTB_Z74 SDR_S31 SDR_S32 SIU_S12 SLR_S28 SRM_S01 SRR_S01 SSR_U04 SSU_U03 STC_S33 TCU_U10 UDM_Q05 VXU_V04 == Version 2.8.1 ACK ADT_A01 ADT_A02 ADT_A03 ADT_A05 ADT_A06 ADT_A09 ADT_A12 ADT_A15 ADT_A16 ADT_A17 ADT_A20 ADT_A21 ADT_A24 ADT_A37 ADT_A38 ADT_A39 ADT_A43 ADT_A44 ADT_A45 ADT_A50 ADT_A52 ADT_A54 ADT_A60 ADT_A61 BAR_P01 BAR_P02 BAR_P05 BAR_P06 BAR_P10 BAR_P12 BPS_O29 BRP_O30 BRT_O32 BTS_O31 CCF_I22 CCI_I22 CCM_I21 CCQ_I19 CCR_I16 CCU_I20 CQU_I19 CRM_C01 CSU_C09 DBC_O41 DBC_O42 DEL_O46 DEO_O45 DER_O44 DFT_P03 DFT_P11 DPR_O48 DRC_O47 DRG_O43 EAC_U07 EAN_U09 EAR_U08 EHC_E01 EHC_E02 EHC_E04 EHC_E10 EHC_E12 EHC_E13 EHC_E15 EHC_E20 EHC_E21 EHC_E24 ESR_U02 ESU_U01 INR_U06 INU_U05 LSU_U12 MDM_T01 MDM_T02 MFK_M01 MFN_M02 MFN_M04 MFN_M05 MFN_M06 MFN_M07 MFN_M08 MFN_M09 MFN_M10 MFN_M11 MFN_M12 MFN_M13 MFN_M15 MFN_M16 MFN_M17 MFN_Znn NMD_N02 OMB_O27 OMD_O03 OMG_O19 OMI_O23 OML_O21 OML_O33 OML_O35 OML_O39 OMN_O07 OMP_O09 OMQ_O42 OMS_O05 OPL_O37 OPR_O38 OPU_R25 ORA_R33 ORA_R41 ORB_O28 ORD_O04 ORG_O20 ORI_O24 ORL_O22 ORL_O34 ORL_O36 ORL_O40 ORL_O41 ORL_O42 ORL_O43 ORL_O44 ORN_O08 ORP_O10 ORS_O06 ORU_R01 ORU_R30 ORX_O43 OSM_R26 OSU_O41 OUL_R22 OUL_R23 OUL_R24 PEX_P07 PGL_PC6 PMU_B01 PMU_B03 PMU_B04 PMU_B07 PMU_B08 PPG_PCG PPP_PCB PPR_PC1 QBP_E03 QBP_E22 QBP_O33 QBP_O34 QBP_Q11 QBP_Q13 QBP_Q15 QBP_Q21 QBP_Qnn QBP_Z73 QCN_J01 QSB_Q16 QVR_Q17 RAS_O17 RDE_O11 RDR_RDR RDS_O13 RDY_K15 RDY_Z80 REF_I12 RGV_O15 RPA_I08 RPI_I01 RPI_I04 RPL_I02 RPR_I03 RQA_I08 RQI_I01 RQP_I04 RRA_O18 RRD_O14 RRE_O12 RRG_O16 RRI_I12 RSP_E03 RSP_E22 RSP_K11 RSP_K21 RSP_K22 RSP_K23 RSP_K25 RSP_K31 RSP_K32 RSP_O33 RSP_O34 RSP_Z82 RSP_Z84 RSP_Z86 RSP_Z88 RSP_Z90 RSP_Znn RTB_K13 RTB_Knn RTB_Z74 SDR_S31 SDR_S32 SIU_S12 SLR_S28 SRM_S01 SRR_S01 SSR_U04 SSU_U03 STC_S33 TCU_U10 UDM_Q05 VXU_V04 ",12418,True,3412.131031800479,median "// // Created by mwo on 8/01/17. // #define MYSQLPP_SSQLS_NO_STATICS 1 #include ""OpenMoneroRequests.h"" #include ""src/UniversalIdentifier.hpp"" #include ""db/ssqlses.h"" #include ""version.h"" #include ""../gen/omversion.h"" namespace xmreg { handel_::handel_(const fetch_func_t& callback): request_callback {callback} {} void handel_::operator()(const shared_ptr< Session > session) { const auto request = session->get_request( ); size_t content_length = request->get_header(""Content-Length"", 0); session->fetch(content_length, this->request_callback); } OpenMoneroRequests::OpenMoneroRequests( shared_ptr _acc, shared_ptr _current_bc_status): xmr_accounts {_acc}, current_bc_status {_current_bc_status} { } void OpenMoneroRequests::login(const shared_ptr session, const Bytes & body) { json j_response; json j_request; vector required_values {""address"", ""view_key""}; if (!parse_request(body, required_values, j_request, j_response)) { session_close(session, j_response); return; } string xmr_address; string view_key; // this is true for both newly created accounts // and existing/imported ones bool create_accountt {true}; // client sends generated_localy as true // for new accounts, and false for // adding existing accounts (i.e., importing wallet) bool generated_locally {false}; try { xmr_address = j_request[""address""]; view_key = j_request[""view_key""]; create_accountt = j_request[""create_account""]; if (j_request.count(""generated_locally"")) generated_locally = j_request[""generated_locally""]; } catch (json::exception const& e) { OMERROR << ""json exception: "" << e.what(); session_close(session, j_response); return; } if (create_accountt == false) { j_response = json {{""status"", ""error""}, {""reason"", ""Not making an account""}}; session_close(session, j_response); return; } // a placeholder for exciting or new account data id uint64_t acc_id {0}; // marks if this is new account creation or not bool new_account_created {false}; auto acc = select_account(xmr_address, view_key, false); // first check if new account // select this account if its existing one if (!acc) { // account does not exist, so create new one // for this address if (!(acc = create_account(xmr_address, view_key, generated_locally))) { // if creating account failed j_response = json {{""status"", ""error""}, {""reason"", ""Account creation failed""}}; session_close(session, j_response); return; } // set this flag to indicate that we have just created a // new account in mysql. this information is sent to front-end // as it can disply some greeting window to new users upon // their first entry new_account_created = true; } // if (!acc) j_response[""generated_locally""] = bool {acc->generated_locally}; j_response[""start_height""] = acc->start_height; // so by now new account has been created or it already exists // so we just login into it. if (login_and_start_search_thread(xmr_address, view_key, *acc, j_response)) { // if successfuly logged in and created search thread j_response[""status""] = ""success""; // we overwrite what ever was sent in login_and_start_search_thread // for the j_response[""new_address""]. j_response[""new_address""] = new_account_created; } else { // some error with loggin in or search thread start OMERROR << xmr_address.substr(0,6) << "": "" << ""login_and_start_search_thread failed. "" << j_response.dump(); session_close(session, j_response); return; } // else if (login_and_start_search_thread(xmr_address, session_close(session, j_response); } void OpenMoneroRequests::ping(const shared_ptr session, const Bytes & body) { json j_response; json j_request; vector required_values {""address"", ""view_key""}; if (!parse_request(body, required_values, j_request, j_response)) { session_close(session, j_response); return; } string xmr_address; string view_key; try { xmr_address = j_request[""address""]; view_key = j_request[""view_key""]; } catch (json::exception const& e) { OMERROR << ""json exception: "" << e.what(); session_close(session, j_response, UNPROCESSABLE_ENTITY); return; } if (!current_bc_status->search_thread_exist(xmr_address, view_key)) { OMERROR << xmr_address.substr(0,6) + "": search thread does not exist""; session_close(session, j_response, UNPROCESSABLE_ENTITY); return; } // ping the search thread that we still need it. // otherwise it will finish after some time. if (!current_bc_status->ping_search_thread(xmr_address)) { j_response = json {{""status"", ""error""}, {""reason"", ""Pinging search thread failed.""}}; // some error with loggin in or search thread start session_close(session, j_response); return; } OMINFO << xmr_address.substr(0,6) + "": search thread ping successful""; j_response[""status""] = ""success""; session_close(session, j_response); } void OpenMoneroRequests::get_address_txs( const shared_ptr< Session > session, const Bytes & body) { json j_response; json j_request; vector requested_values {""address"", ""view_key""}; if (!parse_request(body, requested_values, j_request, j_response)) { session_close(session, j_response); return; } string xmr_address; string view_key; try { xmr_address = j_request[""address""]; view_key = j_request[""view_key""]; } catch (json::exception const& e) { OMERROR << ""json exception: "" << e.what(); session_close(session, j_response, UNPROCESSABLE_ENTITY); return; } // make hash of the submited viewkey. we only store // hash of viewkey in database, not acctual viewkey. string viewkey_hash = make_hash(view_key); // initialize json response j_response = json { {""total_received"" , 0}, // calculated in this function {""total_received_unlocked"", 0}, // calculated in this function {""scanned_height"" , 0}, // not used. just to match mymonero {""scanned_block_height"" , 0}, // taken from Accounts table {""scanned_block_timestamp"", 0}, // taken from Accounts table {""start_height"" , 0}, // blockchain height whencreated {""blockchain_height"" , 0}, // current blockchain height {""transactions"" , json::array()} }; // a placeholder for exciting or new account data xmreg::XmrAccount acc; // for this to continue, search thread must have already been // created and still exisits. if (!login_and_start_search_thread(xmr_address, view_key, acc, j_response)) { j_response = json {{""status"", ""error""}, {""reason"", ""Search thread does not exist.""}}; // some error with loggin in or search thread start session_close(session, j_response); return; } // before fetching txs, check if provided view key // is correct. this is simply to ensure that // we cant fetch an account's txs using only address. // knowlage of the viewkey is also needed. uint64_t total_received {0}; uint64_t total_received_unlocked {0}; j_response[""total_received""] = total_received; j_response[""start_height""] = acc.start_height; j_response[""scanned_block_height""] = acc.scanned_block_height; j_response[""scanned_block_timestamp""] = static_cast( acc.scanned_block_timestamp); j_response[""blockchain_height""] = get_current_blockchain_height(); vector txs; xmr_accounts->select(acc.id.data, txs); if (xmr_accounts->select_txs_for_account_spendability_check( acc.id.data, txs)) { json j_txs = json::array(); for (XmrTransaction const& tx: txs) { json j_tx { {""id"" , tx.blockchain_tx_id}, {""coinbase"" , bool {tx.coinbase}}, {""tx_pub_key"" , tx.tx_pub_key}, {""hash"" , tx.hash}, {""height"" , tx.height}, {""mixin"" , tx.mixin}, {""payment_id"" , tx.payment_id}, {""unlock_time"" , tx.unlock_time}, {""total_sent"" , 0}, // to be field when checking for spent_outputs below {""total_received"" , std::to_string(tx.total_received)}, {""timestamp"" , static_cast(tx.timestamp)*1000}, {""mempool"" , false} // tx in database are never from mempool }; vector inputs; if (xmr_accounts->select_for_tx(tx.id.data, inputs)) { json j_spent_outputs = json::array(); uint64_t total_spent {0}; for (XmrInput input: inputs) { XmrOutput out; if (xmr_accounts->select_by_primary_id( input.output_id, out)) { total_spent += input.amount; j_spent_outputs.push_back({ {""amount"" , std::to_string(input.amount)}, {""key_image"" , input.key_image}, {""tx_pub_key"" , out.tx_pub_key}, {""out_index"" , out.out_index}, {""mixin"" , out.mixin}}); } } j_tx[""total_sent""] = std::to_string(total_spent); j_tx[""spent_outputs""] = j_spent_outputs; } // if (xmr_accounts->select_inputs_for_tx(tx.id, inputs)) total_received += tx.total_received; if (bool {tx.spendable}) { total_received_unlocked += tx.total_received; } j_txs.push_back(j_tx); } // for (XmrTransaction tx: txs) j_response[""total_received""] = std::to_string(total_received); j_response[""total_received_unlocked""] = std::to_string(total_received_unlocked); j_response[""transactions""] = j_txs; } // if (xmr_accounts->select_txs_for_ac // append txs found in mempool to the json returned json j_mempool_tx; if (current_bc_status->find_txs_in_mempool( xmr_address, j_mempool_tx)) { if(!j_mempool_tx.empty()) { uint64_t total_received_mempool {0}; uint64_t total_sent_mempool {0}; // get last tx id (i.e., index) so that we can // set some ids for the mempool txs. These ids are // used for sorting in the frontend. Since we want mempool // tx to be first, they need to be higher than last_tx_id_db uint64_t last_tx_id_db {0}; if (!j_response[""transactions""].empty()) { last_tx_id_db = j_response[""transactions""].back()[""id""]; } for (json& j_tx: j_mempool_tx) { //cout << ""mempool j_tx[\\""total_received\\""]: "" // << j_tx[""total_received""] << endl; j_tx[""id""] = ++last_tx_id_db; total_received_mempool += boost::lexical_cast( j_tx[""total_received""].get()); total_sent_mempool += boost::lexical_cast( j_tx[""total_sent""].get()); j_response[""transactions""].push_back(j_tx); } // we account for mempool txs when providing final // unlocked and locked balances. j_response[""total_received""] = std::to_string( boost::lexical_cast( j_response[""total_received""].get()) + total_received_mempool - total_sent_mempool); j_response[""total_received_unlocked""] = std::to_string( boost::lexical_cast( j_response[""total_received_unlocked""].get()) + total_received_mempool - total_sent_mempool); } //if(!j_mempool_tx.empty()) } // current_bc_status->find_txs_in_mempool string response_body = j_response.dump(); auto response_headers = make_headers( {{ ""Content-Length"", to_string(response_body.size()) }}); session->close(OK, response_body, response_headers); } void OpenMoneroRequests::get_address_info( const shared_ptr< Session > session, const Bytes & body) { json j_response; json j_request; vector requested_values {""address"" , ""view_key""}; if (!parse_request(body, requested_values, j_request, j_response)) { session_close(session, j_response); return; } string xmr_address; string view_key; try { xmr_address = j_request[""address""]; view_key = j_request[""view_key""]; } catch (json::exception const& e) { OMERROR << ""json exception: "" << e.what(); session_close(session, j_response); return; } // make hash of the submited viewkey. we only store // hash of viewkey in database, not acctual viewkey. string viewkey_hash = make_hash(view_key); j_response = json { {""locked_funds"" , ""0""}, // locked xmr (e.g., younger than 10 blocks) {""total_received"" , ""0""}, // calculated in this function {""total_sent"" , ""0""}, // calculated in this function {""scanned_height"" , 0}, // not used. it is here to match mymonero {""scanned_block_height"" , 0}, // taken from Accounts table {""scanned_block_timestamp"", 0}, // taken from Accounts table {""start_height"" , 0}, // not used, but available in Accounts table. // it is here to match mymonero {""blockchain_height"" , 0}, // current blockchain height {""spent_outputs"" , nullptr} // list of spent outputs that we think // user has spent. client side will // filter out false positives since // only client has spent key }; // a placeholder for exciting or new account data xmreg::XmrAccount acc; // for this to continue, search thread must have already been // created and still exisits. if (login_and_start_search_thread(xmr_address, view_key, acc, j_response)) { uint64_t total_received {0}; // ping the search thread that we still need it. // otherwise it will finish after some time. current_bc_status->ping_search_thread(xmr_address); uint64_t current_searched_blk_no {0}; if (current_bc_status->get_searched_blk_no( xmr_address, current_searched_blk_no)) { // if current_searched_blk_no is higher than what is in mysql, update it // in the search thread. This may occure when manually editing scanned_block_height // in Accounts table to import txs or rescan txs. // we use the minumum difference of 10 blocks, for this update to happen if (current_searched_blk_no > acc.scanned_block_height + 10) { current_bc_status->set_new_searched_blk_no( xmr_address, acc.scanned_block_height); } } j_response[""total_received""] = std::to_string(total_received); j_response[""start_height""] = acc.start_height; j_response[""scanned_block_height""] = acc.scanned_block_height; j_response[""scanned_block_timestamp""] = static_cast(acc.scanned_block_timestamp); j_response[""blockchain_height""] = get_current_blockchain_height(); uint64_t total_sent {0}; vector txs; // get all txs of for the account xmr_accounts->select(acc.id.data, txs); // now, filter out or updated transactions from txs vector that no // longer exisit in the recent blocks. Update is done to check for their // spendability status. if (xmr_accounts->select_txs_for_account_spendability_check( acc.id.data, txs)) { json j_spent_outputs = json::array(); for (XmrTransaction tx: txs) { vector outs; if (xmr_accounts->select_for_tx(tx.id.data, outs)) { for (XmrOutput &out: outs) { // check if the output, has been spend vector ins; if (xmr_accounts->select_inputs_for_out( out.id.data, ins)) { for (XmrInput& in: ins) { j_spent_outputs.push_back({ {""amount"" , std::to_string(in.amount)}, {""key_image"" , in.key_image}, {""tx_pub_key"" , out.tx_pub_key}, {""out_index"" , out.out_index}, {""mixin"" , out.mixin}, }); total_sent += in.amount; } } total_received += out.amount; } // for (XmrOutput &out: outs) } // if (xmr_accounts->select_outputs_for_tx(tx.id, outs)) } // for (XmrTransaction tx: txs) j_response[""total_received""] = std::to_string(total_received); j_response[""total_sent""] = std::to_string(total_sent); j_response[""spent_outputs""] = j_spent_outputs; } // if (xmr_accounts->select_txs_for_account_spendability_check(acc.id, txs)) } // if (current_bc_status->search_thread_exist(xmr_address)) else { j_response = json {{""status"", ""error""}, {""reason"", ""Search thread does not exist.""}}; // some error with loggin in or search thread start session_close(session, j_response); return; } string response_body = j_response.dump(); auto response_headers = make_headers({{ ""Content-Length"", to_string(response_body.size())}}); session->close( OK, response_body, response_headers); } void OpenMoneroRequests::get_unspent_outs( const shared_ptr< Session > session, const Bytes & body) { json j_response; json j_request; vector requested_values {""address"" , ""view_key"", ""mixin"", ""use_dust"", ""dust_threshold"", ""amount""}; if (!parse_request(body, requested_values, j_request, j_response)) { session_close(session, j_response); return; } string xmr_address; string view_key; uint64_t mixin {48}; bool use_dust {false}; uint64_t dust_threshold {10000000}; uint64_t amount {0}; try { xmr_address = j_request[""address""]; view_key = j_request[""view_key""]; mixin = j_request[""mixin""]; use_dust = j_request[""use_dust""]; dust_threshold = boost::lexical_cast( j_request[""dust_threshold""].get()); amount = boost::lexical_cast( j_request[""amount""].get()); } catch (json::exception const& e) { OMERROR << ""json exception: "" << e.what(); session_close(session, j_response); return; } catch (boost::bad_lexical_cast const& e) { OMERROR << ""Bed lexical cast"" << e.what() << '\\n'; session_close(session, j_response); return; } // make hash of the submited viewkey. we only store // hash of viewkey in database, not acctual viewkey. string viewkey_hash = make_hash(view_key); j_response = json { {""amount"" , ""0""}, // total value of the outputs {""fork_version"", current_bc_status->get_hard_fork_version()}, {""outputs"", json::array()} // list of outputs // exclude those without require // no of confirmation }; // a placeholder for exciting or new account data xmreg::XmrAccount acc; // select this account if its existing one // for this to continue, search thread must have already been // created and still exisits. if (current_bc_status->search_thread_exist(xmr_address)) { // populate acc and check view_key if (!login_and_start_search_thread(xmr_address, view_key, acc, j_response)) { // some error with loggin in or search thread start session_close(session, j_response); return; } uint64_t total_outputs_amount {0}; // uint64_t current_blockchain_height // = current_bc_status->get_current_blockchain_height(); vector txs; // retrieve txs from mysql associated with the given address if (xmr_accounts->select(acc.id.data, txs)) { // we found some txs. json& j_outputs = j_response[""outputs""]; for (XmrTransaction& tx: txs) { // we skip over locked outputs // as they cant be spent anyway. // thus no reason to return them to the frontend // for constructing a tx. if (!current_bc_status->is_tx_unlocked( tx.unlock_time, tx.height)) { continue; } vector outs; if (!xmr_accounts->select_for_tx(tx.id.data, outs)) { continue; } for (XmrOutput &out: outs) { // skip outputs considered as dust if (out.amount < dust_threshold) { continue; } // need to check for rct commintment // coinbase ringct txs dont have // rct filed in them. Thus // we need to make them. uint64_t global_amount_index = out.global_index; // default case. it will cover // rct types 1 (Full) and 2 (Simple) // rct types explained here: // https://monero.stackexchange.com/questions/3348/what-are-3-types-of-ring-ct-transactions string rct = out.get_rct(); // based on // https://github.com/mymonero/mymonero-app-js/issues/277#issuecomment-469395825 if (!tx.is_rct) { // point 1: null/undefined/empty: // non-RingCT output (i.e, from version 1 tx) // covers all pre-ringct outputs rct = """"; } else { // for RingCT: if (tx.rct_type == 0) { // coinbase rct txs require speciall treatment // point 2: string ""coinbase"" (length 8): // RingCT coinbase output rct = ""coinbase""; } else if (tx.rct_type == 3) { // point 3: string length 192: non-coinbase RingCT // version 1 output with 256-bit amount and mask // rct type 3 is Booletproof rct = out.rct_outpk + out.rct_mask + out.rct_amount; } else if (tx.rct_type == 4) { // point 4 string length 80: // non-coinbase RingCT version 2 // output 64 bit amount // rct type 4 is Booletproof2 rct = out.rct_outpk + out.rct_amount.substr(0,16); } } //cout << ""tx hash: "" << tx.hash << "", rtc: "" << rct // << "", rtc size: "" << rct.size() // << "", decrypted mask: "" << out.rct_mask // << endl; json j_out{ {""amount"" , std::to_string(out.amount)}, {""public_key"" , out.out_pub_key}, {""index"" , out.out_index}, {""global_index"" , out.global_index}, {""rct"" , rct}, {""tx_id"" , out.tx_id}, {""tx_hash"" , tx.hash}, {""tx_prefix_hash"" , tx.prefix_hash}, {""tx_pub_key"" , tx.tx_pub_key}, {""timestamp"" , static_cast( out.timestamp*1e3)}, {""height"" , tx.height}, {""spend_key_images"", json::array()} }; vector ins; if (xmr_accounts->select_inputs_for_out( out.id.data, ins)) { json& j_ins = j_out[""spend_key_images""]; for (XmrInput& in: ins) { j_ins.push_back(in.key_image); } } j_outputs.push_back(j_out); total_outputs_amount += out.amount; } //for (XmrOutput &out: outs) } // for (XmrTransaction& tx: txs) } // if (xmr_accounts->select_txs(acc.id, txs)) j_response[""amount""] = std::to_string(total_outputs_amount); // need proper per_kb_fee estimate as // it is already using dynanamic fees. frontend // uses old fixed fees. j_response[""per_byte_fee""] = current_bc_status ->get_dynamic_base_fee_estimate(); } // if (current_bc_status->search_thread_exist(xmr_address)) else { j_response = json {{""status"", ""error""}, {""reason"", ""Search thread does not exist.""}}; // some error with loggin in or search thread start session_close(session, j_response); return; } string response_body = j_response.dump(); auto response_headers = make_headers({{ ""Content-Length"", to_string(response_body.size())}}); session->close( OK, response_body, response_headers); } void OpenMoneroRequests::get_random_outs( const shared_ptr< Session > session, const Bytes & body) { json j_request; json j_response; vector requested_values; if (!parse_request(body, requested_values, j_request, j_response)) { session_close(session, j_response); return; } uint64_t count; try { count = j_request[""count""]; } catch (json::exception const& e) { OMERROR << ""json exception: "" << e.what(); session_close(session, j_response); return; }; if (count > 241) { OMERROR << ""Request ring size too big"" << '\\n'; j_response[""status""] = ""error""; j_response[""error""] = ""Request ring size too large""; session_close(session, j_response); } vector amounts; try { // populate amounts vector so that we can pass it directly to // daeamon to get random outputs for these amounts for (json amount: j_request[""amounts""]) { amounts.push_back(boost::lexical_cast( amount.get())); // amounts.push_back(0); } } catch (boost::bad_lexical_cast& e) { OMERROR << ""Bed lexical cast""; session_close(session, j_response); return; } vector found_outputs; if (current_bc_status->get_random_outputs(amounts, count, found_outputs)) { json& j_amount_outs = j_response[""amount_outs""]; for (const auto& outs: found_outputs) { json j_outs {{""amount"", std::to_string(outs.amount)}, {""outputs"", json::array()}}; json& j_outputs = j_outs[""outputs""]; for (auto const& out: outs.outs) { tuple rct_field = current_bc_status ->construct_output_rct_field( out.global_amount_index, outs.amount); string rct = std::get<0>(rct_field) // rct_pk + std::get<1>(rct_field) // rct_mask + std::get<2>(rct_field); // rct_amount json out_details { {""global_index"", out.global_amount_index}, {""public_key"" , pod_to_hex(out.out_key)}, {""rct"" , rct} }; j_outputs.push_back(out_details); } // for (const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AM j_amount_outs.push_back(j_outs); } // for (const COMMAND_RPC_GET_RANDOM_OUTPUTS_ } // if (current_bc_status->get_random_outputs(amounts, else { j_response[""status""] = ""error""; j_response[""error""] = ""Error getting random "" ""outputs from monero deamon""; } string response_body = j_response.dump(); auto response_headers = make_headers({{ ""Content-Length"", to_string(response_body.size())}}); session->close( OK, response_body, response_headers); } void OpenMoneroRequests::submit_raw_tx( const shared_ptr< Session > session, const Bytes & body) { json j_request = body_to_json(body); string raw_tx_blob = j_request[""tx""]; json j_response; string error_msg; // before we submit the tx into the deamon, we are going to do a few checks. // first, we parse the hexbuffer submmited by the frontend into // binary buffer block // second, we are going to check if we can construct // valid transaction object // fromt that binary buffer. // third, we are going to check if any key image in this tx is // in any of the txs // in the mempool. This allows us to make a clear comment that the tx // uses outputs just spend. This happens we a users submits few txs, // one after another // before previous txs get included in a block and are still // present in the mempool. std::string tx_blob; if(!epee::string_tools::parse_hexstr_to_binbuff(raw_tx_blob, tx_blob)) { error_msg = ""Tx faild parse_hexstr_to_binbuff""; OMERROR << error_msg; session_close(session, j_response, UNPROCESSABLE_ENTITY, error_msg); return; } transaction tx_to_be_submitted; if (!parse_and_validate_tx_from_blob(tx_blob, tx_to_be_submitted)) { error_msg = ""Tx faild parse_and_validate_tx_from_blob""; OMERROR << error_msg; session_close(session, j_response, UNPROCESSABLE_ENTITY, error_msg); return; } if (current_bc_status->find_key_images_in_mempool(tx_to_be_submitted)) { error_msg = ""Tx uses your outputs that area already "" ""in the mempool. "" ""Please wait till your previous tx(s) "" ""get mined""; OMERROR << error_msg; session_close(session, j_response, UNPROCESSABLE_ENTITY, error_msg); return; } if (!current_bc_status->commit_tx( raw_tx_blob, error_msg, current_bc_status->get_bc_setup().do_not_relay)) { OMERROR << error_msg; session_close(session, j_response, UNPROCESSABLE_ENTITY, error_msg); return; } string response_body = j_response.dump(); auto response_headers = make_headers({{ ""Content-Length"", to_string(response_body.size())}}); session->close( OK, response_body, response_headers); } //@todo current import_wallet_request end point // still requires some work. The reason is that // at this moment it is not clear how it is // handled in mymonero-app-js void OpenMoneroRequests::import_wallet_request( const shared_ptr< Session > session, const Bytes & body) { json j_response; json j_request; vector requested_values {""address"" , ""view_key""}; if (!parse_request(body, requested_values, j_request, j_response)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Cant parse json body!""); return; } string xmr_address; string view_key; try { xmr_address = j_request[""address""]; view_key = j_request[""view_key""]; } catch (json::exception const& e) { OMWARN << ""json exception: "" << e.what(); session_close(session, j_response, UNPROCESSABLE_ENTITY, e.what()); return; } j_response[""request_fulfilled""] = false; j_response[""import_fee""] = std::to_string( current_bc_status->get_bc_setup() .import_fee); j_response[""status""] = ""error""; j_response[""error""] = ""Some error occured""; // get account from mysql db if exists auto xmr_account = select_account(xmr_address, view_key); if (!xmr_account) { // if creation failed, just close the session session_close(session, j_response, UNPROCESSABLE_ENTITY, ""The account login or creation failed!""); return; } auto import_fee = current_bc_status->get_bc_setup().import_fee; // if import is free than just upadte mysql and set new // tx search block if (import_fee == 0) { XmrAccount updated_acc = *xmr_account; updated_acc.scanned_block_height = 0; updated_acc.start_height = 0; // set scanned_block_height to 0 to begin // scanning entire blockchain // @todo we will have race condition here // as we updated mysql here, but at the same time // txsearch tread does the same thing // and just few lines blow we update_acc yet again if (!xmr_accounts->update(*xmr_account, updated_acc)) { OMERROR << xmr_address.substr(0,6) + ""Updating scanned_block_height failed!\\n""; session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Updating scanned_block_height failed!""); return; } // change search blk number in the search thread if (!current_bc_status->set_new_searched_blk_no(xmr_address, 0)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Updating searched_blk_no failed!""); return; } if (!current_bc_status ->update_acc(xmr_address, updated_acc)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""updating acc in search thread failed!""); return; } j_response[""request_fulfilled""] = true; j_response[""status""] = ""Import will start shortly""; j_response[""new_request""] = true; j_response[""error""] = """"; session_close(session, j_response); return; } // payment fee is not zero, so we need to // ask for the payment. So we first get payment details // associated with the given account. auto xmr_payment = select_payment(*xmr_account); // something went wrong. if (!xmr_payment) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Selecting payment details failed!""); return; } // payment id is null if (xmr_payment->id == mysqlpp::null) { // no current payment record exist, // so we have to create new one. // payment request is new, so create its entry in // Payments table uint64_t payment_table_id {0}; crypto::hash8 random_payment_id8 = crypto::rand(); string integrated_address = current_bc_status->get_account_integrated_address_as_str( random_payment_id8); xmr_payment->account_id = xmr_account->id.data; xmr_payment->payment_id = pod_to_hex(random_payment_id8); xmr_payment->import_fee = current_bc_status ->get_bc_setup().import_fee; // xmr xmr_payment->request_fulfilled = false; xmr_payment->tx_hash = """"; // no tx_hash yet with the payment xmr_payment->payment_address = integrated_address; if ((payment_table_id = xmr_accounts->insert(*xmr_payment)) == 0) { OMERROR << xmr_address.substr(0, 6) + "": failed to create new payment record!""; session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Failed to create new payment record!""); return; } // payment entry created j_response[""payment_id""] = payment_table_id; j_response[""import_fee""] = std::to_string( xmr_payment->import_fee); j_response[""new_request""] = true; j_response[""request_fulfilled""] = bool {xmr_payment->request_fulfilled}; j_response[""payment_address""] = xmr_payment->payment_address; j_response[""status""] = ""Payment not yet received""; j_response[""error""] = """"; session_close(session, j_response); return; } // if (xmr_payment->id == mysqlpp::null) // payment id is not null, so it means that // we have already payment record in our db for that // account. bool request_fulfilled = bool {xmr_payment->request_fulfilled}; if (request_fulfilled) { // if payment has been made, and we get new request to import txs // indicate that this is new requeest, but request was fulfiled. // front end should give proper message in this case j_response[""request_fulfilled""] = request_fulfilled; j_response[""import_fee""] = 0; j_response[""status""] = ""Wallet already imported or "" ""in the progress.""; j_response[""new_request""] = false; j_response[""error""] = """"; session_close(session, j_response); return; } // payment has not been yet done, so we are going // to check if it has just been done and update // db accordingly string integrated_address = current_bc_status->get_account_integrated_address_as_str( xmr_payment->payment_id); if (integrated_address.empty()) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""get_account_integrated_address_as_str failed!""); return; } j_response[""payment_id""] = xmr_payment->payment_id; j_response[""import_fee""] = std::to_string(xmr_payment->import_fee); j_response[""new_request""] = false; j_response[""request_fulfilled""] = request_fulfilled; j_response[""payment_address""] = integrated_address; j_response[""status""] = ""Payment not yet received""; string tx_hash_with_payment; // if payment has not yet been done // check if it has just been done now // if yes, mark it in mysql if(current_bc_status->search_if_payment_made( xmr_payment->payment_id, xmr_payment->import_fee, tx_hash_with_payment)) { XmrPayment updated_xmr_payment = *xmr_payment; // updated values updated_xmr_payment.request_fulfilled = true; updated_xmr_payment.tx_hash = tx_hash_with_payment; // save to mysql if (!xmr_accounts->update(*xmr_payment, updated_xmr_payment)) { OMERROR << xmr_address.substr(0,6) + ""Updating payment db failed!\\n""; session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Updating payment db failed!""); return; } XmrAccount updated_acc = *xmr_account; updated_acc.scanned_block_height = 0; updated_acc.start_height = 0; // set scanned_block_height to 0 to begin // scanning entire blockchain // @todo we will have race condition here // as we updated mysql here, but at the same time // txsearch tread does the same thing // and just few lines blow we update_acc yet again if (!xmr_accounts->update(*xmr_account, updated_acc)) { OMERROR << xmr_address.substr(0,6) + ""Updating scanned_block_height failed!\\n""; session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Updating scanned_block_height failed!""); return; } // if success, set acc to updated_acc; request_fulfilled = true; // change search blk number in the search thread if (!current_bc_status ->set_new_searched_blk_no(xmr_address, 0)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""updating searched_blk_no failed!""); return; } if (!current_bc_status ->update_acc(xmr_address, updated_acc)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""updating acc in search thread failed!""); return; } j_response[""request_fulfilled""] = request_fulfilled; j_response[""status""] = ""Payment received. Thank you.""; j_response[""new_request""] = true; j_response[""error""] = """"; } // if(current_bc_status->search_if_payment_made( session_close(session, j_response); } void OpenMoneroRequests::import_recent_wallet_request( const shared_ptr< Session > session, const Bytes & body) { json j_response; json j_request; bool request_fulfilled {false}; j_response[""request_fulfilled""] = false; vector requested_values {""address"" , ""view_key"", ""no_blocks_to_import""}; if (!parse_request(body, requested_values, j_request, j_response)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Cant parse json body!""); return; } string xmr_address; string view_key; try { xmr_address = j_request[""address""]; view_key = j_request[""view_key""]; } catch (json::exception const& e) { OMERROR << xmr_address.substr(0,6) << "": json exception: "" << e.what(); session_close(session, j_response, UNPROCESSABLE_ENTITY, e.what()); return; } uint64_t no_blocks_to_import {1000}; try { no_blocks_to_import = boost::lexical_cast( j_request[""no_blocks_to_import""].get()); } catch (std::exception const& e) { string msg = ""Cant parse "" + j_request[""no_blocks_to_import""].get() + "" into number""; session_close(session, j_response, UNPROCESSABLE_ENTITY, msg); return; } // get account from mysql db if exists auto xmr_account = select_account(xmr_address, view_key); if (!xmr_account) { // if creation failed, just close the session session_close(session, j_response, UNPROCESSABLE_ENTITY, ""The account login or creation failed!""); return; } // make sure that we dont import more that the maximum alowed no of blocks no_blocks_to_import = std::min(no_blocks_to_import, current_bc_status->get_bc_setup() .max_number_of_blocks_to_import); auto current_blkchain_height = current_bc_status->get_current_blockchain_height(); no_blocks_to_import = std::min(no_blocks_to_import, current_blkchain_height); XmrAccount& acc = *xmr_account; XmrAccount updated_acc = acc; // make sure scanned_block_height is larger than // no_blocks_to_import so we dont // end up with overflowing uint64_t. if (updated_acc.scanned_block_height < no_blocks_to_import) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""scanned_block_height < no_blocks_to_import!""); return; } // if import fee is zero, than scanned_block_height will // be automatically set to zero. But in case someone does // not want to imporot from scrach, we set it here to // current blockchain height auto import_fee = current_bc_status->get_bc_setup().import_fee; if (import_fee == 0) updated_acc.scanned_block_height = current_blkchain_height; // repetead calls to import_recent_wallet_request will be // moving the scanning backward. // not sure yet if any protection is needed to // make sure that a user does not // go back too much back by importing his/hers // wallet multiple times in a row. updated_acc.scanned_block_height = updated_acc.scanned_block_height - no_blocks_to_import; if (!xmr_accounts->update(acc, updated_acc)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Updating account failed!""); return; } // change search blk number in the search thread if (!current_bc_status ->set_new_searched_blk_no(xmr_address, updated_acc.scanned_block_height)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""Updating searched_blk_no failed!""); return; } if (!current_bc_status ->update_acc(xmr_address, updated_acc)) { session_close(session, j_response, UNPROCESSABLE_ENTITY, ""updating acc in search thread failed!""); return; } j_response[""request_fulfilled""] = true; j_response[""status""] = ""Updating account with for"" "" importing recent txs successeful.""; string response_body = j_response.dump(); auto response_headers = make_headers({{ ""Content-Length"", std::to_string( response_body.size())}}); session->close( OK, response_body, response_headers); } void OpenMoneroRequests::get_tx( const shared_ptr< Session > session, const Bytes & body) { json j_response; json j_request; vector requested_values {""address"" , ""view_key"", ""tx_hash""}; if (!parse_request(body, requested_values, j_request, j_response)) { session_close(session, j_response); return; } string xmr_address; string view_key; string tx_hash_str; try { xmr_address = j_request[""address""]; view_key = j_request[""view_key""]; tx_hash_str = j_request[""tx_hash""]; } catch (json::exception const& e) { OMWARN << ""json exception: "" << e.what(); session_close(session, j_response); return; } j_response[""status""] = ""error""; j_response[""error""] = ""Some error occured""; crypto::hash tx_hash; if (!hex_to_pod(tx_hash_str, tx_hash)) { cerr << ""Cant parse tx hash! : "" << tx_hash_str << '\\n'; j_response[""status""] = ""Cant parse tx hash! : "" + tx_hash_str; session_close(session, j_response); return; } transaction tx; uint64_t default_timestamp {0}; bool tx_found {false}; bool tx_in_mempool {false}; if (!current_bc_status->get_tx(tx_hash, tx)) { // if tx not found in the blockchain, check if its in mempool // recieved_time, tx vector> mempool_txs = current_bc_status->get_mempool_txs(); //cout << ""serach mempool"" << endl; for (auto const& mtx: mempool_txs) { //cout << (get_transaction_hash(mtx.second)) << '\\n'; if (get_transaction_hash(mtx.second) == tx_hash) { tx = mtx.second; tx_found = true; tx_in_mempool = true; default_timestamp = mtx.first; break; } } } else { tx_found = true; } if (!tx_found) { // if creation failed, just close the session session_close(session, j_response, UNPROCESSABLE_ENTITY, "" Cant get tx details for"" + tx_hash_str); return; } // return tx hash. can be used to check if we acctually // delivered the tx that was requested j_response[""tx_hash""] = pod_to_hex(tx_hash); j_response[""pub_key""] = pod_to_hex( xmreg::get_tx_pub_key_from_received_outs(tx)); bool coinbase = is_coinbase(tx); j_response[""coinbase""] = coinbase; // key images of inputs vector input_key_imgs; // public keys and xmr amount of outputs vector> output_pub_keys; uint64_t xmr_inputs; uint64_t xmr_outputs; uint64_t num_nonrct_inputs; uint64_t fee {0}; uint64_t mixin_no; uint64_t size; // sum xmr in inputs and ouputs in the given tx array const& sum_data = xmreg::summary_of_in_out_rct( tx, output_pub_keys, input_key_imgs); xmr_outputs = sum_data[0]; xmr_inputs = sum_data[1]; mixin_no = sum_data[2]; num_nonrct_inputs = sum_data[3]; j_response[""xmr_outputs""] = xmr_outputs; j_response[""xmr_inputs""] = xmr_inputs; j_response[""mixin_no""] = mixin_no; j_response[""num_of_outputs""] = output_pub_keys.size(); j_response[""num_of_inputs""] = input_key_imgs.size(); j_response[""tx_version""] = tx.version; j_response[""rct_type""] = tx.rct_signatures.type; if (!coinbase && tx.vin.size() > 0) { // check if not miner tx // i.e., for blocks without any user transactions if (tx.vin.at(0).type() != typeid(txin_gen)) { // get tx fee fee = get_tx_fee(tx); } } j_response[""fee""] = fee; // get tx size in bytes size = get_object_blobsize(tx); j_response[""size""] = size; // to be field later on using data from OutputInputIdentification j_response[""total_sent""] = ""0""; j_response[""total_received""] = ""0""; int64_t tx_height {-1}; int64_t no_confirmations {-1}; if (current_bc_status->get_tx_block_height(tx_hash, tx_height)) { // get the current blockchain height. Just to check uint64_t bc_height = get_current_blockchain_height(); no_confirmations = bc_height - tx_height; } // Class that is responsible for identification of our outputs // and inputs in a given tx. j_response[""payment_id""] = string {}; j_response[""timestamp""] = default_timestamp; address_parse_info address_info; secret_key viewkey; MicroCoreAdapter mcore_addapter {current_bc_status.get()}; // to get info about recived xmr in this tx, we calculate it from // scrach, i.e., search for outputs. We could get this info // directly from the database, but doing it again here, is a good way // to double check tx data in the frontend, and also maybe try doing // it differently than before. Its not great, since we reinvent // the wheel // but its worth double checking // the mysql data, and also allows for new // implementation in the frontend. if (current_bc_status->get_xmr_address_viewkey( xmr_address, address_info, viewkey)) { auto identifier = make_identifier(tx, make_unique(&address_info, &viewkey)); identifier.identify(); auto const& outputs_identified = identifier.get()->get(); auto total_received = calc_total_xmr(outputs_identified); j_response[""total_received""] = std::to_string(total_received); json j_spent_outputs = json::array(); // to get spendings, we need to have our key_images. but // the backend does not have spendkey, so it cant determine // which key images are really ours or not. this is the task // for the frontend. however, backend can only provide guesses and // nessessery data to the frontend to filter out incorrect // guesses. // // for input identification, we will use our mysql. its just much // faster to use it here, than before. but first we need to // get account id of the user asking for tx details. // a placeholder for exciting or new account data XmrAccount acc; // select this account if its existing one if (xmr_accounts->select(xmr_address, acc)) { // if user exist, get tx data from database // this will work only for tx in the blockchain, // not those in the mempool. if (!tx_in_mempool) { // if not in mempool, but in blockchain, just // get data aout key images from the mysql XmrTransaction xmr_tx; if (xmr_accounts->tx_exists( acc.id.data, tx_hash_str, xmr_tx)) { j_response[""payment_id""] = xmr_tx.payment_id; j_response[""timestamp""] = static_cast(xmr_tx.timestamp*1e3); vector inputs; if (xmr_accounts->select_for_tx( xmr_tx.id.data, inputs)) { json j_spent_outputs = json::array(); uint64_t total_spent {0}; for (XmrInput input: inputs) { XmrOutput out; if (xmr_accounts ->select_by_primary_id( input.output_id, out)) { total_spent += input.amount; j_spent_outputs.push_back({ {""amount"" , std::to_string(input.amount)}, {""key_image"" , input.key_image}, {""tx_pub_key"" , out.tx_pub_key}, {""out_index"" , out.out_index}, {""mixin"" , out.mixin}}); } } // for (XmrInput input: inputs) j_response[""total_sent""] = std::to_string(total_spent); j_response[""spent_outputs""] = j_spent_outputs; } // if (xmr_accounts->select_inputs_ } // if (xmr_accounts->tx_exists(acc.id } // if (!tx_in_mempool) else { // if tx in mempool, mysql will not have this tx, so // we cant pull info about key images from mysql for this tx. // we have to redo this info from basically from scrach. unordered_map known_outputs_keys; if (current_bc_status->get_known_outputs_keys( xmr_address, known_outputs_keys)) { // we got known_outputs_keys from the search thread. // so now we can use OutputInputIdentification to // get info about inputs. // Class that is resposnible for idenficitaction // of our outputs // and inputs in a given tx. auto identifier = make_identifier(tx, make_unique(&address_info, &viewkey, &known_outputs_keys, &mcore_addapter)); identifier.identify(); auto const& inputs_identfied = identifier.get()->get(); json j_spent_outputs = json::array(); uint64_t total_spent {0}; for (auto& in_info: inputs_identfied) { // need to get output info from mysql, as we need // to know output's amount, its orginal // tx public key and its index in that tx XmrOutput out; string out_pub_key = pod_to_hex(in_info.out_pub_key); if (xmr_accounts->output_exists(out_pub_key, out)) { total_spent += out.amount; j_spent_outputs.push_back({ {""amount"" , std::to_string(in_info.amount)}, {""key_image"" , pod_to_hex(in_info.key_img)}, {""tx_pub_key"" , out.tx_pub_key}, {""out_index"" , out.out_index}, {""mixin"" , out.mixin}}); } } // for (auto& in_info: oi_identification j_response[""total_sent""] = std::to_string(total_spent); j_response[""spent_outputs""] = j_spent_outputs; } //if (current_bc_status->get_known_outputs_keys( // xmr_address, known_outputs_keys)) } // else } // if (xmr_accounts->select(xmr_address, acc)) } // if (current_bc_status->get_xmr_add j_response[""tx_height""] = tx_height; j_response[""no_confirmations""] = no_confirmations; j_response[""status""] = ""OK""; j_response[""error""] = """"; string response_body = j_response.dump(); auto response_headers = make_headers({{ ""Content-Length"", to_string(response_body.size())}}); session->close( OK, response_body, response_headers); } void OpenMoneroRequests::get_version( const shared_ptr< Session > session, const Bytes & body) { (void) body; json j_response { {""last_git_commit_hash"", string {GIT_COMMIT_HASH}}, {""last_git_commit_date"", string {GIT_COMMIT_DATETIME}}, {""git_branch_name"" , string {GIT_BRANCH_NAME}}, {""monero_version_full"" , string {SUMOKOIN_VERSION_FULL}}, {""api"" , OPENMONERO_RPC_VERSION}, {""testnet"" , current_bc_status->get_bc_setup().net_type == network_type::TESTNET}, {""network_type"" , current_bc_status->get_bc_setup().net_type}, {""blockchain_height"" , get_current_blockchain_height()} }; string response_body = j_response.dump(); auto response_headers = make_headers({{ ""Content-Length"", to_string(response_body.size())}}); session->close( OK, response_body, response_headers); } shared_ptr OpenMoneroRequests::make_resource( function< void (OpenMoneroRequests&, const shared_ptr< Session >, const Bytes& ) > handle_func, const string& path) { auto a_request = std::bind(handle_func, *this, std::placeholders::_1, std::placeholders::_2); shared_ptr resource_ptr = make_shared(); resource_ptr->set_path(path); resource_ptr->set_method_handler( ""OPTIONS"", generic_options_handler); resource_ptr->set_method_handler( ""POST"" , handel_(a_request) ); return resource_ptr; } void OpenMoneroRequests::generic_options_handler( const shared_ptr< Session > session ) { const auto request = session->get_request( ); size_t content_length = request->get_header( ""Content-Length"", 0); session->fetch(content_length, [](const shared_ptr< Session > session, const Bytes &) { session->close( OK, string{}, make_headers()); }); } multimap OpenMoneroRequests::make_headers( const multimap& extra_headers) { multimap headers { {""Access-Control-Allow-Origin"" , ""*""}, {""Access-Control-Allow-Headers"" , ""Content-Type""}, {""Content-Type"" , ""application/json""} }; headers.insert(extra_headers.begin(), extra_headers.end()); return headers; }; void OpenMoneroRequests::print_json_log(const string& text, const json& j) { cout << text << '\\n' << j.dump(4) << endl; } string OpenMoneroRequests::body_to_string(const Bytes & body) { return string(reinterpret_cast(body.data()), body.size()); } json OpenMoneroRequests::body_to_json(const Bytes & body) { json j = json::parse(body_to_string(body)); return j; } uint64_t OpenMoneroRequests::get_current_blockchain_height() const { return current_bc_status->get_current_blockchain_height(); } bool OpenMoneroRequests::login_and_start_search_thread( const string& xmr_address, const string& view_key, XmrAccount& acc, json& j_response) { // select this account if its existing one if (xmr_accounts->select(xmr_address, acc)) { // we got accunt from the database. we double check // if hash of provided viewkey by the frontend, matches // what we have in database. // make hash of the submited viewkey. we only store // hash of viewkey in database, not acctual viewkey. string viewkey_hash = make_hash(view_key); if (viewkey_hash == acc.viewkey_hash) { // if match, than save the viewkey in account object // and proceed to checking if a search thread exisits // for this account. if not, then create new thread acc.viewkey = view_key; // so we have an account now. Either existing or // newly created. Thus, we can start a thread // which will scan for transactions belonging to // that account, using its address and view key. // the thread will scan the blockchain for txs belonging // to that account and updated mysql database whenever it // will find something. // // The other client (i.e., a webbrowser) will query other // functions to retrieve // any belonging transactions in a loop. // Thus the thread does not need // to do anything except looking for tx and updating mysql // with relevant tx information if (!current_bc_status->search_thread_exist(acc.address)) { std::unique_ptr tx_search; try { tx_search = std::make_unique(acc, current_bc_status); } catch (std::exception const& e) { OMERROR << ""TxSearch construction faild.""; j_response = json {{""status"", ""error""}, {""reason"", ""Failed to construct "" ""TxSearch object""}}; return false; } if (current_bc_status->start_tx_search_thread( acc, std::move(tx_search))) { j_response[""status""] = ""success""; j_response[""new_address""] = false; // thread has been started // everything seems fine. return true; } } else { j_response[""status""] = ""success""; j_response[""new_address""] = false; // thread already exists // everything seems fine. return true; } j_response = json {{""status"", ""error""}, {""reason"", ""Failed created search "" ""thread for this account""}}; } else { j_response = json {{""status"", ""error""}, {""reason"", ""Viewkey provided is incorrect""}}; } } return false; } bool OpenMoneroRequests::parse_request( const Bytes& body, vector& values_map, json& j_request, json& j_response) const { try { j_request = body_to_json(body); // parsing was successful // now check if all required values are there. for (const auto& v: values_map) { if (j_request.count(v) == 0) { cerr << v + "" value not provided"" << endl; j_response[""status""] = ""error""; j_response[""reason""] = v + "" value not provided""; return false; } } return true; } catch (std::exception& e) { cerr << ""OpenMoneroRequests::parse_request: "" << e.what() << endl; j_response[""status""] = ""error""; j_response[""reason""] = ""reqest json parsing failed""; return false; } } boost::optional OpenMoneroRequests::create_account( string const& xmr_address, string const& view_key, bool generated_locally) const { boost::optional acc = XmrAccount{}; if (xmr_accounts->select(xmr_address, *acc)) { // if acc already exist, just return // existing oneo OMINFO << xmr_address.substr(0,6) << "": account already exists. "" << ""Return existing account""; return acc; } uint64_t current_blockchain_height = get_current_blockchain_height(); // initialize current blockchain timestamp with current time // in a moment we will try to get last block timestamp // to replace this value. But if it fails, we just use current // timestamp uint64_t current_blockchain_timestamp = std::time(nullptr); // get last block so we have its timestamp when // createing the account block last_blk; if (current_bc_status->get_block(current_blockchain_height, last_blk)) { current_blockchain_timestamp = last_blk.timestamp; } DateTime blk_timestamp_mysql_format = XmrTransaction::timestamp_to_DateTime( current_blockchain_timestamp); //@todo setting up start_height and scanned_block_height //needs to be revisited as they are needed for importing //wallets. The simples way is when import is free and this //should already work. More problematic is how to set these //fields when import fee is non-zero. It depends //how mymonero is doing this. At the momemnt, I'm not sure. uint64_t start_height = current_blockchain_height; uint64_t scanned_block_height = current_blockchain_height; if (current_bc_status->get_bc_setup().import_fee == 0) { // accounts generated locally (using create account button) // will have start height equal to current blockchain height. // existing accounts, i.e., those imported ones, also called // extenal ones will have start_height of 0 to // indicated that they could // have been created years ago start_height = generated_locally ? current_blockchain_height : 0; // if scan block height is zero (for extranl wallets) // blockchain scanning starts immedietly. scanned_block_height = start_height; } // create new account acc = XmrAccount( mysqlpp::null, xmr_address, make_hash(view_key), scanned_block_height, blk_timestamp_mysql_format, start_height, generated_locally); uint64_t acc_id {0}; // insert the new account into the mysql if ((acc_id = xmr_accounts->insert(*acc)) == 0) { // if creating account failed OMERROR << xmr_address.substr(0,6) << "": account creation failed: "" << (*acc) ; return {}; } // add acc database id acc->id = acc_id; // add also the view_key into acc object. its needs to be done // as we dont store viewkeys in the database acc->viewkey = view_key; return acc; } boost::optional OpenMoneroRequests::select_account( string const& xmr_address, string const& view_key, bool create_if_notfound) const { boost::optional acc = XmrAccount{}; if (!xmr_accounts->select(xmr_address, *acc)) { OMINFO << xmr_address.substr(0,6) + "": address does not exists""; if (!create_if_notfound) { OMINFO << ""create_if_notfound is false""; return {}; } // for this address if (!(acc = create_account(xmr_address, view_key))) { OMERROR << xmr_address.substr(0,6) << "": create_account failed""; return {}; } // once account has been created // make and start a search thread for it if (!make_search_thread(*acc)) { OMERROR << xmr_address.substr(0,6) << "": make_search_thread failed""; return {}; } } // also need to check if view key matches string viewkey_hash = make_hash(view_key); if (viewkey_hash != acc->viewkey_hash) { OMWARN << xmr_address.substr(0,6) + "": viewkey does not match "" + ""the one in database!""; return {}; } return acc; } bool OpenMoneroRequests::make_search_thread( XmrAccount& acc) const { if (current_bc_status->search_thread_exist(acc.address)) { return true; } std::unique_ptr tx_search; try { tx_search = std::make_unique( acc, current_bc_status); } catch (std::exception const& e) { OMERROR << acc.address.substr(0,6) + "": txSearch construction faild.""; return false; } return current_bc_status->start_tx_search_thread( acc, std::move(tx_search)); } boost::optional OpenMoneroRequests::select_payment( XmrAccount const& xmr_account) const { vector xmr_payments; if (!xmr_accounts->select(xmr_account.id.data, xmr_payments)) { OMINFO << xmr_account.address.substr(0,6) + "": no payment record found!""; // so create empty record to be inserted into // db after. XmrPayment xmr_payment; xmr_payment.id = mysqlpp::null; return xmr_payment; } if (xmr_payments.size() > 1) { OMERROR << xmr_account.address.substr(0,6) + "": more than one payment record found!""; return {}; } // if xmr_payments is empty it means // that the given account has no import // paymnet record created. so new // paymnet will be created if (xmr_payments.empty()) { OMINFO << xmr_account.address.substr(0,6) + "": no payment record found!""; // so create empty record to be inserted into // db after. XmrPayment xmr_payment; xmr_payment.id = mysqlpp::null; return xmr_payment; } return xmr_payments.at(0); } void OpenMoneroRequests::session_close( const shared_ptr< Session > session, json& j_response, int return_code, string error_msg) const { if (return_code != OK) { j_response[""Error""] = error_msg; } string response_body = j_response.dump(); auto response_headers = make_headers({{ ""Content-Length"", std::to_string(response_body.size())}}); session->close( return_code, response_body, response_headers); } } ",16327,True,3341.694797658076,median "[[netty-component]] = Netty Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-netty/src/main/docs/netty-component.adoc :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with the Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported *Since Camel {since}* *{component-header}* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 72 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. The value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. The value can be one of: tcp, udp | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. The value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. The value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. The value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== [NOTE] ==== Read below about using non shareable encoders/decoders. ==== === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSLTLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. [TIP] ==== The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. [NOTE] ==== Read further above about using non shareable encoders/decoders. ==== The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- [TIP] ==== For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. [NOTE] ==== We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. ==== You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. include::camel-spring-boot::page$netty-starter.adoc[] ",12367,False,2296.4562425464856,median "// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include ""resmgremulatorunit.hxx"" // Unit test class // ================================================================ class ETLDriverTest : public UNITTEST // ================================================================ { private: static ETLDriverTest s_instance; protected: ETLDriverTest() {} public: ~ETLDriverTest() {} public: const char * SzName() const; const char * SzDescription() const; bool FRunUnderESE98() const; bool FRunUnderESENT() const; bool FRunUnderESE97() const; ERR ErrTest(); private: const static size_t s_cbftrace = 11; BFTRACE m_rgBfTrace[s_cbftrace]; const static size_t s_cetwevt = 14; EtwEvent* m_rgpEtwEvt[s_cetwevt]; private: void SetupTestData_(); void CleanupTestData_(); ERR ErrInitWithInvalidParamsTest_(); ERR ErrTermWithNullPointer_(); ERR ErrGetNextWithInvalidParamsTest_(); ERR ErrBasicInitTermTest_(); ERR ErrBasicInitGetTermTest_(); ERR ErrBasicInitTermMultiPidTest_(); ERR ErrBasicInitGetTermMultiPidTest_(); ERR ErrGetNextSmallBufferTest_(); ERR ErrGetNextSuccessfulTest_( const DWORD cEventsBufferedMax, const INT iPID ); ERR ErrGetNextMediumBufferTest_(); ERR ErrGetNextLargeBufferTest_(); ERR ErrGetNextHugeBufferTest_(); ERR ErrGetNextAllPidsTest_(); ERR ErrGetNextMultiPidsTest_(); ERR ErrCmpEtlTooManyTest_(); ERR ErrCmpFtlTooManyTest_(); ERR ErrCmpTraceMismatchTest_(); ERR ErrCmpSuccessEmptyTest_(); ERR ErrCmpSuccessAllPidsTest_(); ERR ErrCmpSuccessTest_(); ERR ErrStatsByPidAllPidsTest_(); ERR ErrStatsByPidOnePidTest_(); ERR ErrStatsByPidInvalidParamsTest_(); ERR ErrStatsByPidNoStatsTest_(); }; ETLDriverTest ETLDriverTest::s_instance; const char * ETLDriverTest::SzName() const { return ""ETLDriverTest""; }; const char * ETLDriverTest::SzDescription() const { return ""Tests for the BFETL driver.""; } bool ETLDriverTest::FRunUnderESE98() const { return true; } bool ETLDriverTest::FRunUnderESENT() const { return true; } bool ETLDriverTest::FRunUnderESE97() const { return true; } // ================================================================ ERR ETLDriverTest::ErrTest() // ================================================================ { ERR err = JET_errSuccess; TestCall( ErrInitWithInvalidParamsTest_() ); TestCall( ErrTermWithNullPointer_() ); TestCall( ErrGetNextWithInvalidParamsTest_() ); TestCall( ErrBasicInitTermTest_() ); TestCall( ErrBasicInitGetTermTest_() ); TestCall( ErrBasicInitTermMultiPidTest_() ); TestCall( ErrBasicInitGetTermMultiPidTest_() ); TestCall( ErrGetNextSmallBufferTest_() ); TestCall( ErrGetNextMediumBufferTest_() ); TestCall( ErrGetNextLargeBufferTest_() ); TestCall( ErrGetNextHugeBufferTest_() ); TestCall( ErrGetNextAllPidsTest_() ); TestCall( ErrGetNextMultiPidsTest_() ); TestCall( ErrCmpEtlTooManyTest_() ); TestCall( ErrCmpFtlTooManyTest_() ); TestCall( ErrCmpTraceMismatchTest_() ); TestCall( ErrCmpSuccessEmptyTest_() ); TestCall( ErrCmpSuccessAllPidsTest_() ); TestCall( ErrCmpSuccessTest_() ); TestCall( ErrStatsByPidAllPidsTest_() ); TestCall( ErrStatsByPidOnePidTest_() ); TestCall( ErrStatsByPidInvalidParamsTest_() ); TestCall( ErrStatsByPidNoStatsTest_() ); HandleError: return err; } // ================================================================ void ETLDriverTest::SetupTestData_() // ================================================================ { // Setup expectations first. memset( &m_rgBfTrace, 0, sizeof(m_rgBfTrace) ); TestAssert( _countof( m_rgBfTrace ) == s_cbftrace ); size_t cbftrace = 0; m_rgBfTrace[cbftrace].traceid = bftidEvict; m_rgBfTrace[cbftrace].tick = (TICK)0xFFFFFFFA; m_rgBfTrace[cbftrace].bfevict.ifmp = 1; m_rgBfTrace[cbftrace].bfevict.pgno = 123; m_rgBfTrace[cbftrace].bfevict.fCurrentVersion = fTrue; m_rgBfTrace[cbftrace].bfevict.errBF = -1019; m_rgBfTrace[cbftrace].bfevict.bfef = 0x89; m_rgBfTrace[cbftrace].bfevict.pctPri = 44; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidSysResMgrInit; m_rgBfTrace[cbftrace].tick = (TICK)0xFFFFFFFC; m_rgBfTrace[cbftrace].bfinit.K = 3; m_rgBfTrace[cbftrace].bfinit.csecCorrelatedTouch = 0.1234; m_rgBfTrace[cbftrace].bfinit.csecTimeout = 5678.0; m_rgBfTrace[cbftrace].bfinit.csecUncertainty = 432.1; m_rgBfTrace[cbftrace].bfinit.dblHashLoadFactor = 987.6; m_rgBfTrace[cbftrace].bfinit.dblHashUniformity = 123.4; m_rgBfTrace[cbftrace].bfinit.dblSpeedSizeTradeoff = 5.67; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidCache; m_rgBfTrace[cbftrace].tick = (TICK)0xFFFFFFFD; m_rgBfTrace[cbftrace].bfcache.ifmp = 1; m_rgBfTrace[cbftrace].bfcache.pgno = 234; m_rgBfTrace[cbftrace].bfcache.bflt = 0x56; m_rgBfTrace[cbftrace].bfcache.clientType = 0x78; m_rgBfTrace[cbftrace].bfcache.pctPri = 22; m_rgBfTrace[cbftrace].bfcache.fUseHistory = fTrue; m_rgBfTrace[cbftrace].bfcache.fNewPage = fFalse; m_rgBfTrace[cbftrace].bfcache.fDBScan = fFalse; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidTouch; m_rgBfTrace[cbftrace].tick = (TICK)0xFFFFFFFD; m_rgBfTrace[cbftrace].bftouch.ifmp = 2; m_rgBfTrace[cbftrace].bftouch.pgno = 567; m_rgBfTrace[cbftrace].bftouch.bflt = 0x65; m_rgBfTrace[cbftrace].bftouch.clientType = 0x87; m_rgBfTrace[cbftrace].bftouch.pctPri = 33; m_rgBfTrace[cbftrace].bftouch.fUseHistory = fFalse; m_rgBfTrace[cbftrace].bftouch.fNewPage = fTrue; m_rgBfTrace[cbftrace].bftouch.fNoTouch = fFalse; m_rgBfTrace[cbftrace].bftouch.fDBScan = fFalse; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidDirty; m_rgBfTrace[cbftrace].tick = (TICK)0xFFFFFFFD; m_rgBfTrace[cbftrace].bfdirty.ifmp = 2; m_rgBfTrace[cbftrace].bfdirty.pgno = 565; m_rgBfTrace[cbftrace].bfdirty.bfdf = bfdfDirty; m_rgBfTrace[cbftrace].bfdirty.lgenModify = 1; m_rgBfTrace[cbftrace].bfdirty.isecModify = 2; m_rgBfTrace[cbftrace].bfdirty.ibModify = 3; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidSetLgposModify; m_rgBfTrace[cbftrace].tick = (TICK)0xFFFFFFFD; m_rgBfTrace[cbftrace].bfsetlgposmodify.ifmp = 2; m_rgBfTrace[cbftrace].bfsetlgposmodify.pgno = 565; m_rgBfTrace[cbftrace].bfsetlgposmodify.lgenModify = 3; m_rgBfTrace[cbftrace].bfsetlgposmodify.isecModify = 2; m_rgBfTrace[cbftrace].bfsetlgposmodify.ibModify = 1; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidWrite; m_rgBfTrace[cbftrace].tick = (TICK)0xFFFFFFFD; m_rgBfTrace[cbftrace].bfwrite.ifmp = 2; m_rgBfTrace[cbftrace].bfwrite.pgno = 564; m_rgBfTrace[cbftrace].bfwrite.bfdf = bfdfFilthy; m_rgBfTrace[cbftrace].bfwrite.iorp = iorpBFAvailPool; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidSuperCold; m_rgBfTrace[cbftrace].tick = (TICK)0x00000005; m_rgBfTrace[cbftrace].bfevict.ifmp = 2; m_rgBfTrace[cbftrace].bfevict.pgno = 321; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidSysResMgrTerm; m_rgBfTrace[cbftrace].tick = (TICK)0x00000010; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidTouch; m_rgBfTrace[cbftrace].tick = (TICK)0x00000030; m_rgBfTrace[cbftrace].bftouch.ifmp = 3; m_rgBfTrace[cbftrace].bftouch.pgno = 555; m_rgBfTrace[cbftrace].bftouch.bflt = 0x56; m_rgBfTrace[cbftrace].bftouch.clientType = 0x78; m_rgBfTrace[cbftrace].bftouch.pctPri = 44; m_rgBfTrace[cbftrace].bftouch.fUseHistory = fTrue; m_rgBfTrace[cbftrace].bftouch.fNewPage = fTrue; m_rgBfTrace[cbftrace].bftouch.fNoTouch = fTrue; m_rgBfTrace[cbftrace].bftouch.fDBScan = fTrue; cbftrace++; m_rgBfTrace[cbftrace].traceid = bftidInvalid; // Sentinel. cbftrace++; TestAssert( s_cbftrace == cbftrace ); // Setup input traces (intentionally out-of-order, with disacarded events in-between). size_t cetwevt = 0; memset( &m_rgpEtwEvt, 0, sizeof(m_rgpEtwEvt) ); TestAssert( _countof( m_rgpEtwEvt ) == s_cetwevt ); const size_t ibExtraData = roundup( sizeof(EtwEvent), sizeof(void*) ); const size_t cbExtraData = 100; // 100 bytes should be enough to accommodate all ETW trace types. const size_t cbEtwEvent = ibExtraData + cbExtraData; for ( INT i = 0; i < _countof( m_rgpEtwEvt ) - 1; i++ ) // Last one is sentinel. { m_rgpEtwEvt[i] = (EtwEvent*)( new BYTE[cbEtwEvent] ); memset( m_rgpEtwEvt[i], 0, cbEtwEvent ); m_rgpEtwEvt[i]->timestamp = i; m_rgpEtwEvt[i]->ibExtraData = ibExtraData; EventHeader* pEventHeader = (EventHeader*)( (BYTE*)m_rgpEtwEvt[i] + m_rgpEtwEvt[i]->ibExtraData ); pEventHeader->ulProcessId = 333; pEventHeader->ulThreadId = 999; } EseBfCachePage* pEseBfCachePage = (EseBfCachePage*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseBfCachePage; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseBfCachePage); pEseBfCachePage->tick = (TICK)0xFFFFFFFD; pEseBfCachePage->ifmp = 1; pEseBfCachePage->pgno = 234; pEseBfCachePage->bflt = 0x56; pEseBfCachePage->clientType = 0x78; pEseBfCachePage->pctPriority = 22; pEseBfCachePage->bfrtf = BFRequestTraceFlags( bfrtfUseHistory ); cetwevt++; EseTaskManagerRun* pEseTaskManagerRun = (EseTaskManagerRun*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseTaskManagerRun; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseTaskManagerRun); cetwevt++; EseResMgrInit* pEseResMgrInit = (EseResMgrInit*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseResMgrInit; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseResMgrInit); pEseResMgrInit->tick = (TICK)0xFFFFFFFC; pEseResMgrInit->K = 3; pEseResMgrInit->csecCorrelatedTouch = 0.1234; pEseResMgrInit->csecTimeout = 5678.0; pEseResMgrInit->csecUncertainty = 432.1; pEseResMgrInit->dblHashLoadFactor = 987.6; pEseResMgrInit->dblHashUniformity = 123.4; pEseResMgrInit->dblSpeedSizeTradeoff = 5.67; cetwevt++; pEseTaskManagerRun = (EseTaskManagerRun*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseTaskManagerRun; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseTaskManagerRun); cetwevt++; EseBfEvictPage* pEseBfEvictPage = (EseBfEvictPage*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseBfEvictPage; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseBfEvictPage); pEseBfEvictPage->tick = (TICK)0xFFFFFFFA; pEseBfEvictPage->ifmp = 1; pEseBfEvictPage->pgno = 123; pEseBfEvictPage->fCurrentVersion = fTrue; pEseBfEvictPage->errBF = -1019; pEseBfEvictPage->bfef = 0x89; pEseBfEvictPage->pctPriority = 44; cetwevt++; pEseTaskManagerRun = (EseTaskManagerRun*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseTaskManagerRun; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseTaskManagerRun); cetwevt++; EseBfRequestPage* pEseBfRequestPage = (EseBfRequestPage*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseBfRequestPage; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseBfRequestPage); pEseBfRequestPage->tick = (TICK)0xFFFFFFFD; pEseBfRequestPage->ifmp = 2; pEseBfRequestPage->pgno = 567; pEseBfRequestPage->bflt = 0x65; pEseBfRequestPage->clientType = 0x87; pEseBfRequestPage->pctPriority = 33; pEseBfRequestPage->bfrtf = BFRequestTraceFlags( bfrtfNewPage ); cetwevt++; EseBfDirtyPage* pEseBfDirtyPage = (EseBfDirtyPage*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseBfDirtyPage; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseBfDirtyPage); pEseBfDirtyPage->tick = (TICK)0xFFFFFFFD; pEseBfDirtyPage->ifmp = 2; pEseBfDirtyPage->pgno = 565; pEseBfDirtyPage->ulDirtyLevel = bfdfDirty; pEseBfDirtyPage->lgposModify.lGen = 1; pEseBfDirtyPage->lgposModify.isec = 2; pEseBfDirtyPage->lgposModify.ib = 3; cetwevt++; EseBfSetLgposModify* pEseBfSetLgposModify = (EseBfSetLgposModify*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseBfSetLgposModify; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseBfSetLgposModify); pEseBfSetLgposModify->tick = (TICK)0xFFFFFFFD; pEseBfSetLgposModify->ifmp = 2; pEseBfSetLgposModify->pgno = 565; pEseBfSetLgposModify->lgposModify.lGen = 3; pEseBfSetLgposModify->lgposModify.isec = 2; pEseBfSetLgposModify->lgposModify.ib = 1; cetwevt++; EseBfWritePage* pEseBfWritePage = (EseBfWritePage*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseBfWritePage; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseBfWritePage); pEseBfWritePage->tick = (TICK)0xFFFFFFFD; pEseBfWritePage->ifmp = 2; pEseBfWritePage->pgno = 564; pEseBfWritePage->ulDirtyLevel = bfdfFilthy; pEseBfWritePage->tcevtBf.bIorp = iorpBFAvailPool; cetwevt++; EseResMgrTerm* pEseResMgrTerm = (EseResMgrTerm*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseResMgrTerm; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseResMgrTerm); pEseResMgrTerm->tick = (TICK)0x00000010; cetwevt++; EseBfMarkPageAsSuperCold* pEseBfMarkPageAsSuperCold = (EseBfMarkPageAsSuperCold*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseBfMarkPageAsSuperCold; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseBfMarkPageAsSuperCold); pEseBfMarkPageAsSuperCold->tick = (TICK)0x00000005; pEseBfMarkPageAsSuperCold->ifmp = 2; pEseBfMarkPageAsSuperCold->pgno = 321; cetwevt++; pEseBfRequestPage = (EseBfRequestPage*)( (BYTE*)m_rgpEtwEvt[cetwevt] + m_rgpEtwEvt[cetwevt]->ibExtraData ); ( (EventHeader*)pEseBfRequestPage )->ulProcessId = 334; m_rgpEtwEvt[cetwevt]->etwEvtType = etwevttEseBfRequestPage; m_rgpEtwEvt[cetwevt]->cbExtraData = sizeof(EseBfRequestPage); pEseBfRequestPage->tick = (TICK)0x00000030; pEseBfRequestPage->ifmp = 3; pEseBfRequestPage->pgno = 555; pEseBfRequestPage->bflt = 0x56; pEseBfRequestPage->clientType = 0x78; pEseBfRequestPage->pctPriority = 44; pEseBfRequestPage->bfrtf = BFRequestTraceFlags( bfrtfUseHistory | bfrtfNewPage | bfrtfNoTouch | bfrtfDBScan ); cetwevt++; TestAssert( ( s_cetwevt - 1 ) == cetwevt ); for ( INT i = 0; i < _countof( m_rgpEtwEvt ) - 1; i++ ) // Last one is sentinel. { TestAssert( m_rgpEtwEvt[i]->cbExtraData <= cbExtraData ); } } // ================================================================ void ETLDriverTest::CleanupTestData_() // ================================================================ { for ( INT i = 0; i < _countof( m_rgpEtwEvt ); i++ ) { if ( m_rgpEtwEvt[i] ) { delete []( (BYTE*)m_rgpEtwEvt[i] ); m_rgpEtwEvt[i] = NULL; } } } // ================================================================ ERR ETLDriverTest::ErrInitWithInvalidParamsTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; EtwEvent* petwEvent = NULL; EtwEvent** ppetwEvent = &petwEvent; std::set pids; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); printf( ""NULL pvTraceProvider.\\r\\n"" ); TestCheck( ErrBFETLInit( NULL, 1234, 1, fBFETLDriverTestMode, &bffetlc ) == JET_errInvalidParameter ); TestCheck( bffetlc == NULL ); printf( ""NULL BFETLContext.\\r\\n"" ); TestCheck( ErrBFETLInit( ppetwEvent, 1234, 1, fBFETLDriverTestMode, NULL ) == JET_errInvalidParameter ); printf( ""Invalid file name.\\r\\n"" ); TestCheck( ErrBFETLInit( L""AVeryUnlikelyToExistEtlFileName.etl"", 1234, 1, 0, &bffetlc ) == JET_errOutOfMemory ); TestCheck( bffetlc == NULL ); printf( ""Invalid cEventsBufferedMax.\\r\\n"" ); TestCheck( ErrBFETLInit( ppetwEvent, 1234, 0, fBFETLDriverTestMode, &bffetlc ) == JET_errInvalidParameter ); TestCheck( bffetlc == NULL ); printf( ""Invalid PID set (empty).\\r\\n"" ); pids.clear(); TestCheck( ErrBFETLInit( ppetwEvent, pids, 1, fBFETLDriverTestMode, &bffetlc ) == JET_errInvalidParameter ); TestCheck( bffetlc == NULL ); printf( ""Invalid PID set (PID zero with other PIDs).\\r\\n"" ); pids.clear(); pids.insert( 1234 ); pids.insert( 0 ); TestCheck( ErrBFETLInit( ppetwEvent, pids, 1, fBFETLDriverTestMode, &bffetlc ) == JET_errInvalidParameter ); TestCheck( bffetlc == NULL ); HandleError: return err; } // ================================================================ ERR ETLDriverTest::ErrTermWithNullPointer_() // ================================================================ { printf( ""\\t%s\\r\\n"", __FUNCTION__ ); printf( ""NULL BFETLContext\\r\\n"" ); BFETLTerm( NULL ); return JET_errSuccess; } // ================================================================ ERR ETLDriverTest::ErrGetNextWithInvalidParamsTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; EtwEvent* petwEvent = NULL; EtwEvent** ppetwEvent = &petwEvent; BFTRACE bftrace; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); TestCheckErr( ErrBFETLInit( ppetwEvent, 1234, 1, fBFETLDriverTestMode, &bffetlc ) ); TestCheck( bffetlc != NULL ); printf( ""NULL BFETLContext.\\r\\n"" ); TestCheck( ErrBFETLGetNext( NULL, &bftrace ) == JET_errInvalidParameter ); printf( ""NULL BFTRACE.\\r\\n"" ); TestCheck( ErrBFETLGetNext( NULL, NULL ) == JET_errInvalidParameter ); HandleError: BFETLTerm( bffetlc ); return err; } // ================================================================ ERR ETLDriverTest::ErrBasicInitTermTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; EtwEvent* petwEvent = NULL; EtwEvent** ppetwEvent = &petwEvent; BFTRACE bftrace; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); TestCheckErr( ErrBFETLInit( ppetwEvent, 1234, 1, fBFETLDriverTestMode, &bffetlc ) ); TestCheck( bffetlc != NULL ); TestCheck( bffetlc->cTracesOutOfOrder == 0 ); TestCheck( bffetlc->cTracesProcessed == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 0 ); TestCheck( bffetlc->bftstats.cCache == 0 ); TestCheck( bffetlc->bftstats.cRequest == 0 ); TestCheck( bffetlc->bftstats.cDirty == 0 ); TestCheck( bffetlc->bftstats.cWrite == 0 ); TestCheck( bffetlc->bftstats.cSetLgposModify == 0 ); TestCheck( bffetlc->bftstats.cEvict == 0 ); TestCheck( bffetlc->bftstats.cSuperCold == 0 ); TestCheck( bffetlc->bfftlPostProcHdr().le_cifmp == 0 ); HandleError: BFETLTerm( bffetlc ); return err; } // ================================================================ ERR ETLDriverTest::ErrBasicInitGetTermTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; EtwEvent* petwEvent = NULL; EtwEvent** ppetwEvent = &petwEvent; BFTRACE bftrace; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); TestCheckErr( ErrBFETLInit( ppetwEvent, 1234, 1, fBFETLDriverTestMode, &bffetlc ) ); TestCheck( ErrBFETLGetNext( bffetlc, &bftrace ) == errNotFound ); TestCheck( bffetlc != NULL ); TestCheck( bffetlc->cTracesOutOfOrder == 0 ); TestCheck( bffetlc->cTracesProcessed == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 0 ); TestCheck( bffetlc->bftstats.cCache == 0 ); TestCheck( bffetlc->bftstats.cRequest == 0 ); TestCheck( bffetlc->bftstats.cDirty == 0 ); TestCheck( bffetlc->bftstats.cWrite == 0 ); TestCheck( bffetlc->bftstats.cSetLgposModify == 0 ); TestCheck( bffetlc->bftstats.cEvict == 0 ); TestCheck( bffetlc->bftstats.cSuperCold == 0 ); TestCheck( bffetlc->bfftlPostProcHdr().le_cifmp == 0 ); HandleError: BFETLTerm( bffetlc ); return err; } // ================================================================ ERR ETLDriverTest::ErrBasicInitTermMultiPidTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; EtwEvent* petwEvent = NULL; EtwEvent** ppetwEvent = &petwEvent; BFTRACE bftrace; std::set pids; pids.insert( 1234 ); pids.insert( 5678 ); printf( ""\\t%s\\r\\n"", __FUNCTION__ ); TestCheckErr( ErrBFETLInit( ppetwEvent, pids, 1, fBFETLDriverTestMode, &bffetlc ) ); TestCheck( bffetlc != NULL ); TestCheck( bffetlc->cTracesOutOfOrder == 0 ); TestCheck( bffetlc->cTracesProcessed == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 0 ); TestCheck( bffetlc->bftstats.cCache == 0 ); TestCheck( bffetlc->bftstats.cRequest == 0 ); TestCheck( bffetlc->bftstats.cDirty == 0 ); TestCheck( bffetlc->bftstats.cWrite == 0 ); TestCheck( bffetlc->bftstats.cSetLgposModify == 0 ); TestCheck( bffetlc->bftstats.cEvict == 0 ); TestCheck( bffetlc->bftstats.cSuperCold == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 1234 ).le_cifmp == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 5678 ).le_cifmp == 0 ); HandleError: BFETLTerm( bffetlc ); return err; } // ================================================================ ERR ETLDriverTest::ErrBasicInitGetTermMultiPidTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; EtwEvent* petwEvent = NULL; EtwEvent** ppetwEvent = &petwEvent; BFTRACE bftrace; std::set pids; pids.insert( 1234 ); pids.insert( 5678 ); printf( ""\\t%s\\r\\n"", __FUNCTION__ ); TestCheckErr( ErrBFETLInit( ppetwEvent, pids, 1, fBFETLDriverTestMode, &bffetlc ) ); TestCheck( ErrBFETLGetNext( bffetlc, &bftrace ) == errNotFound ); TestCheck( bffetlc != NULL ); TestCheck( bffetlc->cTracesOutOfOrder == 0 ); TestCheck( bffetlc->cTracesProcessed == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 0 ); TestCheck( bffetlc->bftstats.cCache == 0 ); TestCheck( bffetlc->bftstats.cRequest == 0 ); TestCheck( bffetlc->bftstats.cDirty == 0 ); TestCheck( bffetlc->bftstats.cWrite == 0 ); TestCheck( bffetlc->bftstats.cSetLgposModify == 0 ); TestCheck( bffetlc->bftstats.cEvict == 0 ); TestCheck( bffetlc->bftstats.cSuperCold == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 1234 ).le_cifmp == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 5678 ).le_cifmp == 0 ); HandleError: BFETLTerm( bffetlc ); return err; } // ================================================================ ERR ETLDriverTest::ErrGetNextSmallBufferTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; BFTRACE bftrace; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); SetupTestData_(); TestCheckErr( ErrBFETLInit( m_rgpEtwEvt, 333, 1, fBFETLDriverTestMode, &bffetlc ) ); TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace ) ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[1], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == 1 ); TestCheck( bffetlc->cTracesProcessed == 1 ); TestCheck( bffetlc->bfftlPostProcHdr().le_cifmp == 0 ); TestCheck( ErrBFETLGetNext( bffetlc, &bftrace ) == JET_errInternalError ); TestCheck( bffetlc->cTracesOutOfOrder == 2 ); TestCheck( bffetlc->cTracesProcessed == 1 ); HandleError: BFETLTerm( bffetlc ); CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrGetNextSuccessfulTest_( const DWORD cEventsBufferedMax, const INT iPID ) // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; BFTRACE bftrace; DWORD dwPIDActual; const bool fMultiPid = ( iPID < 0 ); DWORD dwPIDQuery = fMultiPid ? 333 : (DWORD)iPID; const __int64 cTracesOutOfOrder1 = ( cEventsBufferedMax < 6 ) ? 2 : 3; const __int64 cTracesOutOfOrder2 = ( cEventsBufferedMax < 5 ) ? 2 : 3; const __int64 cTracesOutOfOrder3 = 3; SetupTestData_(); if ( !fMultiPid ) { TestCheckErr( ErrBFETLInit( m_rgpEtwEvt, (DWORD)iPID, cEventsBufferedMax, fBFETLDriverTestMode, &bffetlc ) ); } else { std::set pids; pids.insert( 333 ); pids.insert( 334 ); pids.insert( 335 ); TestCheckErr( ErrBFETLInit( m_rgpEtwEvt, pids, cEventsBufferedMax, fBFETLDriverTestMode, &bffetlc ) ); } size_t cbftrace = 0; TestCheck( bffetlc->bftstats.cEvict == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cEvict == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder1 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 2 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 123 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder1 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 2 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 123 ); TestCheck( bffetlc->bftstats.cCache == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cCache == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder1 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 2 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bftstats.cRequest == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cRequest == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder2 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bftstats.cDirty == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cDirty == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bftstats.cSetLgposModify == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cSetLgposModify == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bftstats.cWrite == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cWrite == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bftstats.cSuperCold == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cSuperCold == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 0 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 333 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr( dwPIDQuery ).le_mpifmpcpg[2] == 567 ); if ( !fMultiPid ) { if ( iPID == 0 ) { TestCheck( bffetlc->bftstats.cRequest == 1 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 334 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cRequest == 2 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr().le_cifmp == 4 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[3] == 555 ); TestAssert( ( s_cbftrace - 1 ) == cbftrace ); dwPIDActual = 0; TestCheck( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) == errNotFound ); TestCheck( dwPIDActual == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 1 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 1 ); TestCheck( bffetlc->bftstats.cCache == 1 ); TestCheck( bffetlc->bftstats.cRequest == 2 ); TestCheck( bffetlc->bftstats.cEvict == 1 ); TestCheck( bffetlc->bftstats.cSuperCold == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr().le_cifmp == 4 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[3] == 555 ); } else { TestAssert( ( s_cbftrace - 2 ) == cbftrace ); dwPIDActual = 0; TestCheck( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) == errNotFound ); TestCheck( dwPIDActual == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 1 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 1 ); TestCheck( bffetlc->bftstats.cCache == 1 ); TestCheck( bffetlc->bftstats.cRequest == 1 ); TestCheck( bffetlc->bftstats.cEvict == 1 ); TestCheck( bffetlc->bftstats.cSuperCold == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr().le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr().le_mpifmpcpg[2] == 567 ); } } else { TestCheck( bffetlc->bftstats.cRequest == 1 ); dwPIDActual = 0; TestCheckErr( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) ); TestCheck( dwPIDActual == 334 ); TestCheck( memcmp( &bftrace, &m_rgBfTrace[cbftrace++], sizeof(bftrace) ) == 0 ); TestCheck( bffetlc->bftstats.cRequest == 2 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( 333 ).le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr( 333 ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 333 ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr( 333 ).le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_cifmp == 4 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_mpifmpcpg[1] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_mpifmpcpg[2] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_mpifmpcpg[3] == 555 ); TestCheck( bffetlc->bfftlPostProcHdr( 335 ).le_cifmp == 0 ); TestAssert( ( s_cbftrace - 1 ) == cbftrace ); dwPIDActual = 0; TestCheck( ErrBFETLGetNext( bffetlc, &bftrace, &dwPIDActual ) == errNotFound ); TestCheck( dwPIDActual == 0 ); TestCheck( bffetlc->bftstats.cSysResMgrInit == 1 ); TestCheck( bffetlc->bftstats.cSysResMgrTerm == 1 ); TestCheck( bffetlc->bftstats.cCache == 1 ); TestCheck( bffetlc->bftstats.cRequest == 2 ); TestCheck( bffetlc->bftstats.cEvict == 1 ); TestCheck( bffetlc->bftstats.cSuperCold == 1 ); TestCheck( bffetlc->cTracesOutOfOrder == cTracesOutOfOrder3 ); TestCheck( bffetlc->cTracesProcessed == (__int64)cbftrace ); TestCheck( bffetlc->bfftlPostProcHdr( 333 ).le_cifmp == 3 ); TestCheck( bffetlc->bfftlPostProcHdr( 333 ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 333 ).le_mpifmpcpg[1] == 234 ); TestCheck( bffetlc->bfftlPostProcHdr( 333 ).le_mpifmpcpg[2] == 567 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_cifmp == 4 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_mpifmpcpg[0] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_mpifmpcpg[1] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_mpifmpcpg[2] == 0 ); TestCheck( bffetlc->bfftlPostProcHdr( 334 ).le_mpifmpcpg[3] == 555 ); TestCheck( bffetlc->bfftlPostProcHdr( 335 ).le_cifmp == 0 ); } HandleError: BFETLTerm( bffetlc ); CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrGetNextMediumBufferTest_() // ================================================================ { printf( ""\\t%s\\r\\n"", __FUNCTION__ ); return ErrGetNextSuccessfulTest_( 4, 333 ); } // ================================================================ ERR ETLDriverTest::ErrGetNextLargeBufferTest_() // ================================================================ { printf( ""\\t%s\\r\\n"", __FUNCTION__ ); return ErrGetNextSuccessfulTest_( 9, 333 ); } // ================================================================ ERR ETLDriverTest::ErrGetNextHugeBufferTest_() // ================================================================ { printf( ""\\t%s\\r\\n"", __FUNCTION__ ); return ErrGetNextSuccessfulTest_( 13, 333 ); } // ================================================================ ERR ETLDriverTest::ErrGetNextAllPidsTest_() // ================================================================ { printf( ""\\t%s\\r\\n"", __FUNCTION__ ); return ErrGetNextSuccessfulTest_( 5, 0 ); } // ================================================================ ERR ETLDriverTest::ErrGetNextMultiPidsTest_() // ================================================================ { printf( ""\\t%s\\r\\n"", __FUNCTION__ ); return ErrGetNextSuccessfulTest_( 5, -1 ); } // ================================================================ ERR ETLDriverTest::ErrCmpEtlTooManyTest_() // ================================================================ { ERR err = JET_errSuccess; __int64 cTracesProcessed = 0; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); SetupTestData_(); m_rgBfTrace[3].traceid = bftidInvalid; TestCheck( ErrBFETLFTLCmp( m_rgpEtwEvt, m_rgBfTrace, 0, fTrue, &cTracesProcessed ) == JET_errDatabaseCorrupted ); TestCheck( cTracesProcessed == 3 ); HandleError: CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrCmpFtlTooManyTest_() // ================================================================ { ERR err = JET_errSuccess; __int64 cTracesProcessed = 0; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); SetupTestData_(); delete []( (BYTE*)m_rgpEtwEvt[10] ); m_rgpEtwEvt[10] = NULL; TestCheck( ErrBFETLFTLCmp( m_rgpEtwEvt, m_rgBfTrace, 0, fTrue, &cTracesProcessed ) == JET_errDatabaseCorrupted ); TestCheck( cTracesProcessed == 7 ); HandleError: CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrCmpTraceMismatchTest_() // ================================================================ { ERR err = JET_errSuccess; __int64 cTracesProcessed = 0; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); SetupTestData_(); m_rgBfTrace[2].tick++; TestCheck( ErrBFETLFTLCmp( m_rgpEtwEvt, m_rgBfTrace, 0, fTrue, &cTracesProcessed ) == JET_errDatabaseCorrupted ); TestCheck( cTracesProcessed == 2 ); HandleError: CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrCmpSuccessEmptyTest_() // ================================================================ { ERR err = JET_errSuccess; __int64 cTracesProcessed = 0; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); SetupTestData_(); m_rgBfTrace[0].traceid = bftidInvalid; delete []( (BYTE*)m_rgpEtwEvt[0] ); m_rgpEtwEvt[0] = NULL; TestCheckErr( ErrBFETLFTLCmp( m_rgpEtwEvt, m_rgBfTrace, 0, fTrue, &cTracesProcessed ) ); TestCheck( cTracesProcessed == 0 ); HandleError: CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrCmpSuccessAllPidsTest_() // ================================================================ { ERR err = JET_errSuccess; __int64 cTracesProcessed = 0; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); SetupTestData_(); TestCheckErr( ErrBFETLFTLCmp( m_rgpEtwEvt, m_rgBfTrace, 0, fTrue, &cTracesProcessed ) ); TestCheck( cTracesProcessed == (__int64)( s_cbftrace - 1 ) ); HandleError: CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrCmpSuccessTest_() // ================================================================ { ERR err = JET_errSuccess; __int64 cTracesProcessed = 0; printf( ""\\t%s\\r\\n"", __FUNCTION__ ); SetupTestData_(); m_rgBfTrace[s_cbftrace - 2].traceid = bftidInvalid; TestCheckErr( ErrBFETLFTLCmp( m_rgpEtwEvt, m_rgBfTrace, 333, fTrue, &cTracesProcessed ) ); TestCheck( cTracesProcessed == (__int64)( s_cbftrace - 2 ) ); HandleError: CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrStatsByPidAllPidsTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; BFTRACE bftrace; SetupTestData_(); TestCheckErr( ErrBFETLInit( m_rgpEtwEvt, 0, s_cetwevt / 2, fBFETLDriverTestMode | fBFETLDriverCollectBFStats, &bffetlc ) ); while ( ( err = ErrBFETLGetNext( bffetlc, &bftrace ) ) == JET_errSuccess ); TestAssert( err == errNotFound ); err = JET_errSuccess; const BFTraceStats* bfts = NULL; DWORD dwPID; dwPID = 0; bfts = PbftsBFETLStatsByPID( bffetlc, &dwPID ); TestCheck( bfts != NULL ); TestCheck( dwPID == 333 ); TestCheck( bfts->cSysResMgrInit == 1 ); TestCheck( bfts->cSysResMgrTerm == 1 ); TestCheck( bfts->cCache == 1 ); TestCheck( bfts->cRequest == 1 ); TestCheck( bfts->cDirty == 1 ); TestCheck( bfts->cWrite == 1 ); TestCheck( bfts->cSetLgposModify == 1 ); TestCheck( bfts->cEvict == 1 ); TestCheck( bfts->cSuperCold == 1 ); dwPID = 1; bfts = PbftsBFETLStatsByPID( bffetlc, &dwPID ); TestCheck( bfts != NULL ); TestCheck( dwPID == 334 ); TestCheck( bfts->cSysResMgrInit == 0 ); TestCheck( bfts->cSysResMgrTerm == 0 ); TestCheck( bfts->cCache == 0 ); TestCheck( bfts->cRequest == 1 ); TestCheck( bfts->cEvict == 0 ); TestCheck( bfts->cSuperCold == 0 ); dwPID = 2; bfts = PbftsBFETLStatsByPID( bffetlc, &dwPID ); TestCheck( bfts == NULL ); TestCheck( dwPID == 0 ); HandleError: BFETLTerm( bffetlc ); CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrStatsByPidOnePidTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; BFTRACE bftrace; SetupTestData_(); TestCheckErr( ErrBFETLInit( m_rgpEtwEvt, 333, s_cetwevt / 2, fBFETLDriverTestMode | fBFETLDriverCollectBFStats, &bffetlc ) ); while ( ( err = ErrBFETLGetNext( bffetlc, &bftrace ) ) == JET_errSuccess ); TestAssert( err == errNotFound ); err = JET_errSuccess; const BFTraceStats* bfts = NULL; DWORD dwPID; dwPID = 0; bfts = PbftsBFETLStatsByPID( bffetlc, &dwPID ); TestCheck( bfts != NULL ); TestCheck( dwPID == 333 ); TestCheck( bfts->cSysResMgrInit == 1 ); TestCheck( bfts->cSysResMgrTerm == 1 ); TestCheck( bfts->cCache == 1 ); TestCheck( bfts->cRequest == 1 ); TestCheck( bfts->cDirty == 1 ); TestCheck( bfts->cWrite == 1 ); TestCheck( bfts->cSetLgposModify == 1 ); TestCheck( bfts->cEvict == 1 ); TestCheck( bfts->cSuperCold == 1 ); dwPID = 1; bfts = PbftsBFETLStatsByPID( bffetlc, &dwPID ); TestCheck( bfts == NULL ); TestCheck( dwPID == 0 ); HandleError: BFETLTerm( bffetlc ); CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrStatsByPidInvalidParamsTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; BFTRACE bftrace; SetupTestData_(); TestCheckErr( ErrBFETLInit( m_rgpEtwEvt, 333, s_cetwevt / 2, fBFETLDriverTestMode | fBFETLDriverCollectBFStats, &bffetlc ) ); while ( ( err = ErrBFETLGetNext( bffetlc, &bftrace ) ) == JET_errSuccess ); TestAssert( err == errNotFound ); err = JET_errSuccess; const BFTraceStats* bfts = NULL; DWORD dwPID; dwPID = 0; bfts = PbftsBFETLStatsByPID( NULL, &dwPID ); TestCheck( bfts == NULL ); TestCheck( dwPID == 0 ); HandleError: BFETLTerm( bffetlc ); CleanupTestData_(); return err; } // ================================================================ ERR ETLDriverTest::ErrStatsByPidNoStatsTest_() // ================================================================ { ERR err = JET_errSuccess; BFETLContext* bffetlc = NULL; BFTRACE bftrace; SetupTestData_(); TestCheckErr( ErrBFETLInit( m_rgpEtwEvt, 333, s_cetwevt / 2, fBFETLDriverTestMode, &bffetlc ) ); while ( ( err = ErrBFETLGetNext( bffetlc, &bftrace ) ) == JET_errSuccess ); TestAssert( err == errNotFound ); err = JET_errSuccess; const BFTraceStats* bfts = NULL; DWORD dwPID; dwPID = 0; bfts = PbftsBFETLStatsByPID( bffetlc, &dwPID ); TestCheck( bfts == NULL ); TestCheck( dwPID == 0 ); HandleError: BFETLTerm( bffetlc ); CleanupTestData_(); return err; } ",16317,True,3333.295240400427,median "/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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. ==============================================================================*/ #include #include #include #include #include #include #include ""tensorflow/lite/c/builtin_op_data.h"" #include ""tensorflow/lite/c/common.h"" #include ""tensorflow/lite/kernels/cpu_backend_context.h"" #include ""tensorflow/lite/kernels/internal/common.h"" #include ""tensorflow/lite/kernels/internal/compatibility.h"" #include ""tensorflow/lite/kernels/internal/cppmath.h"" #include ""tensorflow/lite/kernels/internal/optimized/optimized_ops.h"" #include ""tensorflow/lite/kernels/internal/quantization_util.h"" #include ""tensorflow/lite/kernels/internal/reference/binary_function.h"" #include ""tensorflow/lite/kernels/internal/reference/integer_ops/log_softmax.h"" #include ""tensorflow/lite/kernels/internal/reference/integer_ops/logistic.h"" #include ""tensorflow/lite/kernels/internal/reference/integer_ops/tanh.h"" #include ""tensorflow/lite/kernels/internal/reference/logistic.h"" #include ""tensorflow/lite/kernels/internal/reference/prelu.h"" #include ""tensorflow/lite/kernels/internal/reference/reference_ops.h"" #include ""tensorflow/lite/kernels/internal/reference/softmax.h"" #include ""tensorflow/lite/kernels/internal/reference/tanh.h"" #include ""tensorflow/lite/kernels/internal/tensor.h"" #include ""tensorflow/lite/kernels/internal/tensor_ctypes.h"" #include ""tensorflow/lite/kernels/internal/types.h"" #include ""tensorflow/lite/kernels/kernel_util.h"" #if __aarch64__ && __clang__ #include #endif namespace tflite { namespace ops { namespace builtin { namespace activations { // TODO(b/142762739): We should figure out a multi-threading plan for most of // the activation ops below. enum KernelType { kReference, kGenericOptimized, kFixedPointOptimized, }; struct OpData { int32_t input_multiplier = 0; int input_left_shift = 0; int32_t input_range_radius = 0; int diff_min = 0; uint8_t table[256] = {0}; }; struct SoftmaxOpData { struct SoftmaxParams params = {}; float table[256]; #ifdef TFLITE_SOFTMAX_USE_UINT16_LUT uint8_t uint8_table1[256]; uint8_t uint8_table2[256]; #endif static constexpr int kInt16LUTArraySize = 513; int16_t exp_lut[kInt16LUTArraySize]; // int16 LUT for exp(x), where x uniform // distributed between [-10.0 , 0.0] int16_t one_over_one_plus_x_lut[kInt16LUTArraySize]; // int16 LUT for 1 / // (1 + x), where x // uniform distributed // between [0.0 , 1.0] }; struct LogSoftmaxOpData : public OpData { int32_t reverse_scaling_divisor = 0; int32_t reverse_scaling_right_shift = 0; struct SoftmaxParams params = {}; float f_table[256]; }; struct LeakyReluOpData : public OpData { int32_t output_multiplier_alpha = 0; int32_t output_shift_alpha = 0; int32_t output_multiplier_identity = 0; int32_t output_shift_identity = 0; }; struct PreluOpData : public OpData { int32_t output_multiplier_1 = 0; int32_t output_shift_1 = 0; int32_t output_multiplier_2 = 0; int32_t output_shift_2 = 0; bool requires_broadcast; }; struct HardSwishData { HardSwishParams params; }; struct ReluOpData : public OpData { int32_t output_multiplier = 0; int output_shift = 0; }; namespace { template void PopulateLookupTable(struct OpData* data, const TfLiteTensor* input, TfLiteTensor* output, const std::function& transform) { static_assert(sizeof(T) == 1, ""Lookup table valid only for 8bit""); const float inverse_scale = 1 / output->params.scale; int32_t maxval = std::numeric_limits::max(); int32_t minval = std::numeric_limits::min(); for (int32_t val = minval; val <= maxval; ++val) { const float dequantized = input->params.scale * (val - input->params.zero_point); const float transformed = transform(dequantized); const float rescaled = std::round(transformed * inverse_scale); const int32_t quantized = static_cast(rescaled + output->params.zero_point); data->table[static_cast(static_cast(val))] = static_cast( static_cast(std::max(std::min(maxval, quantized), minval))); } } // TODO(b/143696793): move this to optimized_ops. void EvalUsingLookupTable(struct OpData* data, const TfLiteTensor* input, TfLiteTensor* output) { const int size = MatchingFlatSize(GetTensorShape(input), GetTensorShape(output)); uint8_t* output_data = GetTensorData(output); const uint8_t* input_data = GetTensorData(input); int i = 0; #if __aarch64__ && __clang__ // This code uses ARM64-only instructions. // TODO(b/143709993): Port to ARMv7 // Load the tables into registers. (4*4 128-bit registers) uint8x16x4_t table[4]; table[0] = vld1q_u8_x4(data->table + 16 * 4 * 0); table[1] = vld1q_u8_x4(data->table + 16 * 4 * 1); table[2] = vld1q_u8_x4(data->table + 16 * 4 * 2); table[3] = vld1q_u8_x4(data->table + 16 * 4 * 3); // Vectorized loop; process uint8x16_t (16 elements) at a time. constexpr int vectorized_16_loop_step = 16; const int vectorized_16_loop_end = size / vectorized_16_loop_step * vectorized_16_loop_step; for (; i < vectorized_16_loop_end; i += vectorized_16_loop_step) { uint8x16_t input = vld1q_u8(input_data + i); uint8x16_t output = optimized_ops::aarch64_lookup_vector(table, input); vst1q_u8(output_data + i, output); } // Postamble and non-ARM64 code: simple for loop. #endif for (; i < size; ++i) { output_data[i] = data->table[input_data[i]]; } } template void QuantizedReluX(float act_min, float act_max, const TfLiteTensor* input, TfLiteTensor* output, const ReluOpData* data) { ReluParams params; params.quantized_activation_min = std::max(static_cast(std::numeric_limits::min()), output->params.zero_point + static_cast(roundf(act_min / output->params.scale))); params.quantized_activation_max = act_max == std::numeric_limits::infinity() ? static_cast(std::numeric_limits::max()) : std::min( static_cast(std::numeric_limits::max()), output->params.zero_point + static_cast(roundf(act_max / output->params.scale))); params.input_offset = input->params.zero_point; params.output_offset = output->params.zero_point; params.output_multiplier = data->output_multiplier; params.output_shift = data->output_shift; optimized_ops::ReluX(params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } } // namespace void* Init(TfLiteContext* context, const char* buffer, size_t length) { // This is a builtin op, so we don't use the contents in 'buffer', if any. // Instead, we allocate a new object to carry information from Prepare() to // Eval(). return new OpData; } void* SoftmaxInit(TfLiteContext* context, const char* buffer, size_t length) { return new SoftmaxOpData; } void SoftmaxFree(TfLiteContext* context, void* buffer) { delete reinterpret_cast(buffer); } void* LogSoftmaxInit(TfLiteContext* context, const char* buffer, size_t length) { return new LogSoftmaxOpData; } void* PreluInit(TfLiteContext* context, const char* buffer, size_t length) { return new PreluOpData; } void Free(TfLiteContext* context, void* buffer) { delete reinterpret_cast(buffer); } void LogSoftmaxFree(TfLiteContext* context, void* buffer) { delete reinterpret_cast(buffer); } void PreluFree(TfLiteContext* context, void* buffer) { delete reinterpret_cast(buffer); } void* HardSwishInit(TfLiteContext* context, const char* buffer, size_t length) { return new HardSwishData; } TfLiteStatus GenericPrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); } void* ReluInit(TfLiteContext* context, const char* buffer, size_t length) { return new ReluOpData; } void ReluFree(TfLiteContext* context, void* buffer) { delete reinterpret_cast(buffer); } TfLiteStatus ReluPrepare(TfLiteContext* context, TfLiteNode* node) { ReluOpData* data = reinterpret_cast(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); if (input->type == kTfLiteInt8 || input->type == kTfLiteUInt8 || input->type == kTfLiteInt16) { double real_multiplier = input->params.scale / output->params.scale; QuantizeMultiplier(real_multiplier, &data->output_multiplier, &data->output_shift); } if (input->type == kTfLiteInt16) { TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0); TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); } return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); } void* LeakyReluInit(TfLiteContext* context, const char* buffer, size_t length) { return new LeakyReluOpData; } void LeakyReluFree(TfLiteContext* context, void* buffer) { delete reinterpret_cast(buffer); } void HardSwishFree(TfLiteContext* context, void* buffer) { delete static_cast(buffer); } TfLiteStatus HardSwishPrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_STATUS(GenericPrepare(context, node)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { HardSwishData* data = static_cast(node->user_data); HardSwishParams* params = &data->params; const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); params->input_zero_point = input->params.zero_point; params->output_zero_point = output->params.zero_point; const float input_scale = input->params.scale; const float hires_input_scale = (1.0f / 128.0f) * input_scale; const float reluish_scale = 3.0f / 32768.0f; const float output_scale = output->params.scale; const float output_multiplier = hires_input_scale / output_scale; int32_t output_multiplier_fixedpoint_int32; QuantizeMultiplier(output_multiplier, &output_multiplier_fixedpoint_int32, ¶ms->output_multiplier_exponent); DownScaleInt32ToInt16Multiplier( output_multiplier_fixedpoint_int32, ¶ms->output_multiplier_fixedpoint_int16); TF_LITE_ENSURE(context, params->output_multiplier_exponent <= 0); const float reluish_multiplier = hires_input_scale / reluish_scale; int32_t reluish_multiplier_fixedpoint_int32; QuantizeMultiplier(reluish_multiplier, &reluish_multiplier_fixedpoint_int32, ¶ms->reluish_multiplier_exponent); DownScaleInt32ToInt16Multiplier( reluish_multiplier_fixedpoint_int32, ¶ms->reluish_multiplier_fixedpoint_int16); } return kTfLiteOk; } TfLiteStatus LeakyReluPrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); LeakyReluOpData* data = reinterpret_cast(node->user_data); if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8 || output->type == kTfLiteInt16) { const auto* params = reinterpret_cast(node->builtin_data); double alpha_multiplier = input->params.scale * params->alpha / output->params.scale; QuantizeMultiplier(alpha_multiplier, &data->output_multiplier_alpha, &data->output_shift_alpha); double identity_multiplier = input->params.scale / output->params.scale; QuantizeMultiplier(identity_multiplier, &data->output_multiplier_identity, &data->output_shift_identity); } if (input->type == kTfLiteInt16 && output->type == kTfLiteInt16) { TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0); TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); } return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); } template TfLiteStatus TanhPrepare(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); if (kernel_type == kFixedPointOptimized) { if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) { static constexpr int kInputIntegerBits = 4; const double input_real_multiplier = input->params.scale * static_cast(1 << (15 - kInputIntegerBits)); const double q = std::frexp(input_real_multiplier, &data->input_left_shift); auto q_fixed = static_cast(TfLiteRound(q * (1ll << 15))); data->input_multiplier = static_cast(q_fixed); int16_t input_range_radius = CalculateInputRadius(kInputIntegerBits, data->input_left_shift, 15); data->input_range_radius = input_range_radius; } } if (kernel_type == kGenericOptimized || kernel_type == kReference) { if (input->type == kTfLiteUInt8) { PopulateLookupTable( data, input, output, [](float value) { return std::tanh(value); }); } else if (input->type == kTfLiteInt8) { PopulateLookupTable(data, input, output, [](float value) { return std::tanh(value); }); } } if (input->type == kTfLiteInt16) { static constexpr int kInputIntegerBits = 3; static constexpr int kOutputFractionalBits = 15; // These operators are implemented in fixed-point arithmetic, // which intrinsically wants symmetric ranges (zero_point==0) // and power-of-two scales (power-of-two is abbreviated below as POT). // While more general support would be possible by means of rescaling, // that would add some overhead and some loss of accuracy and wouldn't // be used at the moment as current quantized LSTM applications are // happy with symmetric, power-of-two-scales quantization. So we just // implement that narrow case only for now. TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0); TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); int input_scale_log2_rounded; bool param_scale_pot = CheckedLog2(input->params.scale, &input_scale_log2_rounded); data->input_left_shift = (15 - kInputIntegerBits) + input_scale_log2_rounded; param_scale_pot &= (data->input_left_shift == 0 || data->input_left_shift == 1); if (!param_scale_pot) { // Calculate multiplier to change input scale to 1/(3*4096) // as required by the table lookup. // The number 3.0 in the multiplier comes from here, // because the interval is [-10.7, 10.7] instead of [-8, 8]. // So, in this scaling +/-2^17 represents +/-10.7. double multiplier = input->params.scale * 4096.0 * 3.0; data->input_left_shift = 0; while (multiplier <= 32767.0 / 2.0 && data->input_left_shift <= 30) { data->input_left_shift++; multiplier = multiplier * 2.0; } data->input_multiplier = static_cast(multiplier); } int output_scale_log2_rounded; TF_LITE_ENSURE( context, CheckedLog2(output->params.scale, &output_scale_log2_rounded)); TF_LITE_ENSURE_EQ(context, output_scale_log2_rounded, -kOutputFractionalBits); } return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); } template TfLiteStatus SigmoidPrepare(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); if (kernel_type == kFixedPointOptimized) { if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) { if (input->type == kTfLiteUInt8) { TF_LITE_ENSURE_EQ(context, output->params.zero_point, std::numeric_limits::min()); } if (input->type == kTfLiteInt8) { TF_LITE_ENSURE_EQ(context, output->params.zero_point, std::numeric_limits::min()); } TF_LITE_ENSURE(context, output->params.scale == 1. / 256); static constexpr int kInputIntegerBits = 4; const double input_real_multiplier = input->params.scale * static_cast(1 << (15 - kInputIntegerBits)); const double q = std::frexp(input_real_multiplier, &data->input_left_shift); auto q_fixed = static_cast(TfLiteRound(q * (1ll << 15))); data->input_multiplier = static_cast(q_fixed); int16_t input_range_radius = CalculateInputRadius(kInputIntegerBits, data->input_left_shift, 15); data->input_range_radius = input_range_radius; } } if (kernel_type == kGenericOptimized || kernel_type == kReference) { if (input->type == kTfLiteUInt8) { TF_LITE_ENSURE(context, output->params.scale == 1. / 256); PopulateLookupTable(data, input, output, [](float value) { return 1.0f / (1.0f + std::exp(-value)); }); } else if (input->type == kTfLiteInt8) { TF_LITE_ENSURE(context, output->params.scale == 1. / 256); PopulateLookupTable(data, input, output, [](float value) { return 1.0f / (1.0f + std::exp(-value)); }); } else if (input->type == kTfLiteInt16) { TF_LITE_ENSURE(context, output->params.scale == 1. / 32768); TF_LITE_ENSURE(context, output->params.zero_point == 0); } } if (input->type == kTfLiteInt16) { static constexpr int kInputIntegerBits = 3; static constexpr int kOutputFractionalBits = 15; // See comments in TanhPrepare about requiring zero_point==0 // and a power-of-two (""POT"") scale. TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0); TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); int input_scale_log2_rounded; bool param_scale_pot = CheckedLog2(input->params.scale, &input_scale_log2_rounded); data->input_left_shift = (15 - kInputIntegerBits) + input_scale_log2_rounded; param_scale_pot &= (data->input_left_shift == 0); if (!param_scale_pot) { // Calculate multiplier to change input scale to 1/(3*4096) // as required by the table lookup. // In this scaling +/-2^17 represents +/-10.7 double multiplier = input->params.scale * 4096.0 * 3.0; data->input_left_shift = 0; while (multiplier <= 32767.0 / 2.0 && data->input_left_shift <= 30) { data->input_left_shift++; multiplier = multiplier * 2.0; } data->input_multiplier = static_cast(multiplier); } int output_scale_log2_rounded; TF_LITE_ENSURE( context, CheckedLog2(output->params.scale, &output_scale_log2_rounded)); TF_LITE_ENSURE_EQ(context, output_scale_log2_rounded, -kOutputFractionalBits); } return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); } TfLiteStatus SoftmaxPrepare(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast(node->builtin_data); SoftmaxOpData* data = reinterpret_cast(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); if (output->type == kTfLiteInt16) { TF_LITE_ENSURE(context, input->type == kTfLiteInt8 || input->type == kTfLiteUInt8 || input->type == kTfLiteInt16); } else { TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); } TF_LITE_ENSURE(context, NumDimensions(input) >= 1); if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) { switch (output->type) { case kTfLiteUInt8: case kTfLiteInt8: #ifdef TFLITE_SOFTMAX_USE_UINT16_LUT // Only apply when both input & output are uint8/int8 & build with clang // on aarch64. // TODO(b/143709993): Port to ARMv7 and other platforms. data->params.uint8_table1 = data->uint8_table1; data->params.uint8_table2 = data->uint8_table2; optimized_ops::PopulateSoftmaxUInt8LookupTable( &data->params, input->params.scale, params->beta); break; #endif case kTfLiteInt16: default: data->params.table = data->table; optimized_ops::PopulateSoftmaxLookupTable( &data->params, input->params.scale, params->beta); } data->params.zero_point = output->params.zero_point; data->params.scale = output->params.scale; } if (input->type == kTfLiteInt16) { TF_LITE_ENSURE_EQ(context, input->params.zero_point, 0); TF_LITE_ENSURE_EQ(context, output->params.zero_point, 0); data->params.exp_lut = data->exp_lut; // exp LUT only used on nagative values // we consider exp(-10.0) is insignificant to accumulation gen_lut([](double value) { return std::exp(value); }, -10.0, 0.0, data->params.exp_lut, data->kInt16LUTArraySize); data->params.one_over_one_plus_x_lut = data->one_over_one_plus_x_lut; gen_lut([](double value) { return 1.0 / (1.0 + value); }, 0.0, 1.0, data->params.one_over_one_plus_x_lut, data->kInt16LUTArraySize); data->params.zero_point = output->params.zero_point; data->params.scale = output->params.scale; double input_scale_beta_rescale = input->params.scale * params->beta / (10.0 / 65535.0); // scale the input_diff such that [-65535, 0] // correspond to [-10.0, 0.0] QuantizeMultiplier(input_scale_beta_rescale, &data->params.input_multiplier, &data->params.input_left_shift); } return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); } template TfLiteStatus LogSoftmaxPrepare(TfLiteContext* context, TfLiteNode* node) { LogSoftmaxOpData* data = reinterpret_cast(node->user_data); TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); if (input->type == kTfLiteUInt8 || input->type == kTfLiteInt8) { TF_LITE_ENSURE_EQ(context, output->params.scale, 16.0 / 256); static const double kBeta = 1.0; if (input->type == kTfLiteUInt8) { TF_LITE_ENSURE_EQ(context, output->params.zero_point, 255); } if (input->type == kTfLiteInt8) { TF_LITE_ENSURE_EQ(context, output->params.zero_point, 127); } if (kernel_type == kReference) { const int kScaledDiffIntegerBits = 5; int input_left_shift; int reverse_scaling_right_shift; tflite::PreprocessLogSoftmaxScalingExp( kBeta, static_cast(input->params.scale), kScaledDiffIntegerBits, &data->params.input_multiplier, &input_left_shift, &data->params.reverse_scaling_divisor, &reverse_scaling_right_shift); reverse_scaling_right_shift *= -1; data->params.input_left_shift = input_left_shift; data->params.reverse_scaling_right_shift = reverse_scaling_right_shift; data->params.diff_min = -tflite::CalculateInputRadius( kScaledDiffIntegerBits, input_left_shift); } else { data->params.table = data->f_table; optimized_ops::PopulateSoftmaxLookupTable(&data->params, input->params.scale, kBeta); data->params.zero_point = output->params.zero_point; data->params.scale = output->params.scale; } } return context->ResizeTensor(context, output, TfLiteIntArrayCopy(input->dims)); } TfLiteStatus PreluPrepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const TfLiteTensor* alpha; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &alpha)); PreluOpData* data = reinterpret_cast(node->user_data); TF_LITE_ENSURE_TYPES_EQ(context, input->type, alpha->type); output->type = input->type; if (output->type == kTfLiteUInt8 || output->type == kTfLiteInt8) { // prelu(x) = x if x >= 0 else x * alpha. // So if we translate that for quantized computation: // // input_float = (input_q - input_zp) * input_scale // output_float = (output_q - output_zp) * output_scale // alpha_float = (alpha_q - alpha_zp) * alpha_scale // // When input_q - input_zp >= 0: // ouput_q = (input_q - input_zp) * input_scale / output_scale + output_q // else: // output_q = (input_q - input_zp) * (alpha_q - alpha_zp) * input_scale // * alpha_scale / output_scale + output_q // // So for input_q - input_zp >= 0: // output real multiplier 1 is input_scale / output_scale; // for input_q - input_zp < 0: // output real multiplier 2 is input_scale * alpha_scale/ output_scale. double real_multiplier_1 = input->params.scale / output->params.scale; double real_multiplier_2 = input->params.scale * alpha->params.scale / output->params.scale; QuantizeMultiplier(real_multiplier_1, &data->output_multiplier_1, &data->output_shift_1); QuantizeMultiplier(real_multiplier_2, &data->output_multiplier_2, &data->output_shift_2); } data->requires_broadcast = !HaveSameShapes(input, alpha); // PRelu (parameteric Relu) shares the same alpha value on ""shared axis"". // This means it's always required to ""broadcast"" alpha values in PRelu. TfLiteIntArray* output_size = nullptr; TF_LITE_ENSURE_OK( context, CalculateShapeForBroadcast(context, input, alpha, &output_size)); TF_LITE_ENSURE_OK(context, context->ResizeTensor(context, output, output_size)); // After broadcasting, the output shape should always be the same as the // input shape. TF_LITE_ENSURE(context, HaveSameShapes(input, output)); return kTfLiteOk; } TfLiteStatus ReluEval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const ReluOpData* data = reinterpret_cast(node->user_data); switch (input->type) { case kTfLiteFloat32: { optimized_ops::Relu(GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } break; // TODO(renjieliu): We may revisit the quantization calculation logic, // the unbounded upper limit is actually hard to quantize. case kTfLiteUInt8: { QuantizedReluX(0.0f, std::numeric_limits::infinity(), input, output, data); } break; case kTfLiteInt8: { QuantizedReluX(0.0f, std::numeric_limits::infinity(), input, output, data); } break; case kTfLiteInt16: { QuantizedReluX(0.0f, std::numeric_limits::infinity(), input, output, data); } break; default: TF_LITE_KERNEL_LOG(context, ""Only float32, uint8, int8 and int16 are supported "" ""currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } TfLiteStatus Relu1Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const ReluOpData* data = reinterpret_cast(node->user_data); switch (input->type) { case kTfLiteFloat32: { optimized_ops::Relu1(GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); return kTfLiteOk; } break; case kTfLiteUInt8: { QuantizedReluX(-1.0f, 1.0f, input, output, data); return kTfLiteOk; } break; case kTfLiteInt8: { QuantizedReluX(-1, 1, input, output, data); return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG(context, ""Only float32, uint8, int8 supported "" ""currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } template TfLiteStatus HardSwishEval(TfLiteContext* context, TfLiteNode* node) { HardSwishData* data = static_cast(node->user_data); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); switch (input->type) { case kTfLiteFloat32: { if (kernel_type == kReference) { reference_ops::HardSwish( GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { optimized_ops::HardSwish( GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } break; case kTfLiteUInt8: { HardSwishParams& params = data->params; if (kernel_type == kReference) { reference_ops::HardSwish( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { optimized_ops::HardSwish( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } break; case kTfLiteInt8: { HardSwishParams& params = data->params; if (kernel_type == kReference) { reference_ops::HardSwish( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { optimized_ops::HardSwish( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG( context, ""Only float32, uint8 and int8 are supported currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } TfLiteStatus Relu6Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); ReluOpData* data = reinterpret_cast(node->user_data); switch (input->type) { case kTfLiteFloat32: { size_t elements = input->bytes / sizeof(float); const float* in = GetTensorData(input); const float* in_end = in + elements; float* out = GetTensorData(output); for (; in < in_end; in++, out++) *out = std::min(std::max(0.f, *in), 6.f); return kTfLiteOk; } break; case kTfLiteUInt8: QuantizedReluX(0.0f, 6.0f, input, output, data); return kTfLiteOk; case kTfLiteInt8: { QuantizedReluX(0.0f, 6.0f, input, output, data); return kTfLiteOk; } break; case kTfLiteInt16: { QuantizedReluX(0.0f, 6.0f, input, output, data); return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG(context, ""Only float32, uint8, int8 and int16 are supported "" ""currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } template TfLiteStatus TanhEval(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast(node->user_data); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); switch (input->type) { case kTfLiteFloat32: { if (kernel_type == kReference) { reference_ops::Tanh(GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { optimized_ops::Tanh(GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } break; case kTfLiteInt16: { TanhParams params; params.input_left_shift = data->input_left_shift; if (kernel_type == kReference || (data->input_multiplier > 0)) { reference_integer_ops::Tanh( data->input_multiplier, data->input_left_shift, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { optimized_ops::Tanh( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } break; case kTfLiteUInt8: { if (kernel_type == kFixedPointOptimized) { TanhParams params; params.input_zero_point = input->params.zero_point; params.input_range_radius = data->input_range_radius; params.input_multiplier = data->input_multiplier; params.input_left_shift = data->input_left_shift; optimized_ops::Tanh16bitPrecision( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { EvalUsingLookupTable(data, input, output); } return kTfLiteOk; } break; case kTfLiteInt8: { if (kernel_type == kFixedPointOptimized) { TanhParams params; params.input_zero_point = input->params.zero_point; params.input_range_radius = data->input_range_radius; params.input_multiplier = data->input_multiplier; params.input_left_shift = data->input_left_shift; optimized_ops::Tanh16bitPrecision( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { EvalUsingLookupTable(data, input, output); } return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG(context, ""Only float32, uint8, int16 and int8 are supported "" ""currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } // Sigmoid is also know as ""Logistic"". template TfLiteStatus SigmoidEval(TfLiteContext* context, TfLiteNode* node) { OpData* data = reinterpret_cast(node->user_data); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); switch (input->type) { case kTfLiteFloat32: { if (kernel_type == kReference) { reference_ops::Logistic( GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { optimized_ops::Logistic( GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } break; } case kTfLiteInt16: { LogisticParams params; if (kernel_type == kReference || (data->input_multiplier > 0)) { const int size = MatchingFlatSize(GetTensorShape(input), GetTensorShape(output)); reference_integer_ops::Logistic( data->input_multiplier, data->input_left_shift, size, GetTensorData(input), GetTensorData(output)); } else { optimized_ops::Logistic( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } break; } case kTfLiteUInt8: { if (kernel_type == kFixedPointOptimized) { LogisticParams params; params.input_zero_point = input->params.zero_point; params.input_range_radius = data->input_range_radius; params.input_multiplier = data->input_multiplier; params.input_left_shift = data->input_left_shift; optimized_ops::Logistic16bitPrecision( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { EvalUsingLookupTable(data, input, output); } break; } case kTfLiteInt8: { if (kernel_type == kFixedPointOptimized) { LogisticParams params; params.input_zero_point = input->params.zero_point; params.input_range_radius = data->input_range_radius; params.input_multiplier = data->input_multiplier; params.input_left_shift = data->input_left_shift; optimized_ops::Logistic16bitPrecision( params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { EvalUsingLookupTable(data, input, output); } break; } default: TF_LITE_KERNEL_LOG(context, ""Only float32, uint8, int16 and int8 are supported "" ""currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } return kTfLiteOk; } TfLiteStatus SoftmaxFloat(TfLiteContext* context, const TfLiteTensor* input, TfLiteTensor* output, TfLiteSoftmaxParams* params) { SoftmaxParams op_params; op_params.beta = params->beta; optimized_ops::Softmax(op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output), CpuBackendContext::GetFromContext(context)); return kTfLiteOk; } template TfLiteStatus SoftmaxQuantized(TfLiteContext* context, const TfLiteTensor* input, TfLiteTensor* output, SoftmaxOpData* data) { optimized_ops::Softmax(data->params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); return kTfLiteOk; } template <> TfLiteStatus SoftmaxQuantized(TfLiteContext* context, const TfLiteTensor* input, TfLiteTensor* output, SoftmaxOpData* data) { #ifdef TFLITE_SOFTMAX_USE_UINT16_LUT optimized_ops::SoftmaxInt8LUT( data->params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); #else optimized_ops::Softmax(data->params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); #endif return kTfLiteOk; } template <> TfLiteStatus SoftmaxQuantized(TfLiteContext* context, const TfLiteTensor* input, TfLiteTensor* output, SoftmaxOpData* data) { #ifdef TFLITE_SOFTMAX_USE_UINT16_LUT optimized_ops::SoftmaxInt8LUT( data->params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); #else optimized_ops::Softmax(data->params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); #endif return kTfLiteOk; } template <> TfLiteStatus SoftmaxQuantized(TfLiteContext* context, const TfLiteTensor* input, TfLiteTensor* output, SoftmaxOpData* data) { if (NumDimensions(input) >= 1 && NumDimensions(input) <= 4) { reference_ops::SoftmaxInt16( data->params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); return kTfLiteOk; } else { TF_LITE_KERNEL_LOG(context, ""Only 1D, 2D, 3D and 4D tensors supported for int16 "" ""input with int16 output, got %dD."", NumDimensions(input)); return kTfLiteError; } } TfLiteStatus SoftmaxEval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast(node->builtin_data); SoftmaxOpData* data = reinterpret_cast(node->user_data); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); switch (input->type) { case kTfLiteFloat32: { return SoftmaxFloat(context, input, output, params); } case kTfLiteUInt8: { switch (output->type) { case kTfLiteUInt8: return SoftmaxQuantized(context, input, output, data); case kTfLiteInt16: return SoftmaxQuantized(context, input, output, data); default: TF_LITE_KERNEL_LOG(context, ""Only uint8_t and int16_t outputs are supported "" ""with uint8_t inputs currently, got %s."", TfLiteTypeGetName(output->type)); return kTfLiteError; } } case kTfLiteInt8: { switch (output->type) { case kTfLiteInt8: return SoftmaxQuantized(context, input, output, data); case kTfLiteInt16: return SoftmaxQuantized(context, input, output, data); default: TF_LITE_KERNEL_LOG(context, ""Only int8_t and int16_t outputs are supported "" ""with int8_t inputs currently, got %s."", TfLiteTypeGetName(output->type)); return kTfLiteError; } } case kTfLiteInt16: { return SoftmaxQuantized(context, input, output, data); } default: TF_LITE_KERNEL_LOG(context, ""Only float32, uint8_t, Int8_t, Int16_t are supported "" ""currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } template TfLiteStatus LogSoftmaxEval(TfLiteContext* context, TfLiteNode* node) { const LogSoftmaxOpData* data = reinterpret_cast(node->user_data); const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); switch (input->type) { case kTfLiteFloat32: { SoftmaxParams op_params; if (kernel_type == kGenericOptimized) { optimized_ops::LogSoftmax( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { reference_ops::LogSoftmax( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } case kTfLiteUInt8: { const SoftmaxParams& op_params = data->params; if (kernel_type == kGenericOptimized) { optimized_ops::LogSoftmax( op_params, input->params.scale, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { reference_ops::LogSoftmax( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } case kTfLiteInt8: { const SoftmaxParams& op_params = data->params; if (kernel_type == kGenericOptimized) { optimized_ops::LogSoftmax( op_params, input->params.scale, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } else { const auto input_shape = GetTensorShape(input); const auto output_shape = GetTensorShape(output); const int trailing_dim = input_shape.DimensionsCount() - 1; const int outer_size = MatchingFlatSizeSkipDim(input_shape, trailing_dim, output_shape); const int depth = MatchingDim(input_shape, trailing_dim, output_shape, trailing_dim); reference_integer_ops::LogSoftmax( op_params.input_multiplier, op_params.input_left_shift, op_params.reverse_scaling_divisor, op_params.reverse_scaling_right_shift, op_params.diff_min, outer_size, depth, GetTensorData(input), GetTensorData(output)); } return kTfLiteOk; } default: TF_LITE_KERNEL_LOG( context, ""Only float32, uint8 and int8 are supported currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } template T ApplyPrelu(T input, T alpha) { return input >= 0.0 ? input : input * alpha; } template TfLiteStatus PreluEval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); const TfLiteTensor* alpha; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 1, &alpha)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const PreluOpData* data = reinterpret_cast(node->user_data); switch (input->type) { case kTfLiteFloat32: { if (kernel_type == kGenericOptimized) { tflite::ArithmeticParams op_params; bool need_broadcast = optimized_ops::ProcessBroadcastShapes( GetTensorShape(input), GetTensorShape(alpha), &op_params); if (need_broadcast) { optimized_ops::BroadcastPReluDispatch( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(alpha), GetTensorData(alpha), GetTensorShape(output), GetTensorData(output), ApplyPrelu); } else { const int flat_size = MatchingElementsSize(GetTensorShape(input), GetTensorShape(alpha), GetTensorShape(output)); optimized_ops::PReluElementWise( flat_size, op_params, GetTensorData(alpha), GetTensorData(input), GetTensorData(output)); } } else { if (data->requires_broadcast) { reference_ops::BroadcastBinaryFunction4DSlow( GetTensorShape(input), GetTensorData(input), GetTensorShape(alpha), GetTensorData(alpha), GetTensorShape(output), GetTensorData(output), ApplyPrelu); } else { reference_ops::BinaryFunction( GetTensorShape(input), GetTensorData(input), GetTensorShape(alpha), GetTensorData(alpha), GetTensorShape(output), GetTensorData(output), ApplyPrelu); } } return kTfLiteOk; } break; case kTfLiteUInt8: { PreluParams op_params; op_params.input_offset = -input->params.zero_point; op_params.alpha_offset = -alpha->params.zero_point; op_params.output_offset = output->params.zero_point; op_params.output_multiplier_1 = data->output_multiplier_1; op_params.output_shift_1 = data->output_shift_1; op_params.output_multiplier_2 = data->output_multiplier_2; op_params.output_shift_2 = data->output_shift_2; if (data->requires_broadcast) { reference_ops::BroadcastPrelu4DSlow( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(alpha), GetTensorData(alpha), GetTensorShape(output), GetTensorData(output)); } else { reference_ops::Prelu( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(alpha), GetTensorData(alpha), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } break; case kTfLiteInt8: { PreluParams op_params; op_params.input_offset = -input->params.zero_point; op_params.alpha_offset = -alpha->params.zero_point; op_params.output_offset = output->params.zero_point; op_params.output_multiplier_1 = data->output_multiplier_1; op_params.output_shift_1 = data->output_shift_1; op_params.output_multiplier_2 = data->output_multiplier_2; op_params.output_shift_2 = data->output_shift_2; if (data->requires_broadcast) { reference_ops::BroadcastPrelu4DSlow( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(alpha), GetTensorData(alpha), GetTensorShape(output), GetTensorData(output)); } else { reference_ops::Prelu( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(alpha), GetTensorData(alpha), GetTensorShape(output), GetTensorData(output)); } return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG( context, ""Only float32 and uint8 and int8 are supported currently, got %d."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } template void QuantizeLeakyRelu(const TfLiteTensor* input, TfLiteTensor* output, const LeakyReluOpData* data) { LeakyReluParams op_params; op_params.input_offset = input->params.zero_point; op_params.output_offset = output->params.zero_point; op_params.output_multiplier_alpha = data->output_multiplier_alpha; op_params.output_shift_alpha = data->output_shift_alpha; op_params.output_multiplier_identity = data->output_multiplier_identity; op_params.output_shift_identity = data->output_shift_identity; reference_ops::QuantizeLeakyRelu( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); } TfLiteStatus LeakyReluEval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); const auto* params = reinterpret_cast(node->builtin_data); const LeakyReluOpData* data = reinterpret_cast(node->user_data); LeakyReluParams op_params; switch (input->type) { case kTfLiteFloat32: { op_params.alpha = params->alpha; optimized_ops::LeakyRelu( op_params, GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); return kTfLiteOk; } break; case kTfLiteUInt8: { QuantizeLeakyRelu(input, output, data); return kTfLiteOk; } break; case kTfLiteInt8: { QuantizeLeakyRelu(input, output, data); return kTfLiteOk; } break; case kTfLiteInt16: { QuantizeLeakyRelu(input, output, data); return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG( context, ""Only float32, int8, int16 and uint8 is supported currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } TfLiteStatus EluPrepare(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); OpData* data = reinterpret_cast(node->user_data); // Use LUT to handle quantized elu path. if (input->type == kTfLiteInt8) { PopulateLookupTable(data, input, output, [](float value) { return value < 0.0 ? std::exp(value) - 1.0f : value; }); } return GenericPrepare(context, node); } TfLiteStatus EluEval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, 0, &input)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, 0, &output)); switch (input->type) { case kTfLiteFloat32: { optimized_ops::Elu(GetTensorShape(input), GetTensorData(input), GetTensorShape(output), GetTensorData(output)); return kTfLiteOk; } break; case kTfLiteInt8: { OpData* data = reinterpret_cast(node->user_data); EvalUsingLookupTable(data, input, output); return kTfLiteOk; } break; default: TF_LITE_KERNEL_LOG( context, ""Only float32 and int8 is supported currently, got %s."", TfLiteTypeGetName(input->type)); return kTfLiteError; } } } // namespace activations TfLiteRegistration* Register_ELU() { static TfLiteRegistration r = {activations::Init, activations::Free, activations::EluPrepare, activations::EluEval}; return &r; } TfLiteRegistration* Register_RELU() { static TfLiteRegistration r = {activations::ReluInit, activations::ReluFree, activations::ReluPrepare, activations::ReluEval}; return &r; } TfLiteRegistration* Register_RELU_N1_TO_1() { static TfLiteRegistration r = {activations::ReluInit, activations::ReluFree, activations::ReluPrepare, activations::Relu1Eval}; return &r; } TfLiteRegistration* Register_RELU6() { static TfLiteRegistration r = {activations::ReluInit, activations::ReluFree, activations::ReluPrepare, activations::Relu6Eval}; return &r; } TfLiteRegistration* Register_TANH_REF() { static TfLiteRegistration r = { activations::Init, activations::Free, activations::TanhPrepare, activations::TanhEval}; return &r; } TfLiteRegistration* Register_TANH_GENERIC_OPT() { static TfLiteRegistration r = { activations::Init, activations::Free, activations::TanhPrepare, activations::TanhEval}; return &r; } TfLiteRegistration* Register_TANH_FIXED_POINT_OPT() { static TfLiteRegistration r = { activations::Init, activations::Free, activations::TanhPrepare, activations::TanhEval}; return &r; } TfLiteRegistration* Register_TANH() { // TODO(b/134622898): Switch over from the LUT optimized method to the fixed // point optimized method when typical Android hardware performs better on // the latter one. return Register_TANH_GENERIC_OPT(); } TfLiteRegistration* Register_LOGISTIC_REF() { static TfLiteRegistration r = { activations::Init, activations::Free, activations::SigmoidPrepare, activations::SigmoidEval}; return &r; } TfLiteRegistration* Register_LOGISTIC_GENERIC_OPT() { static TfLiteRegistration r = { activations::Init, activations::Free, activations::SigmoidPrepare, activations::SigmoidEval}; return &r; } TfLiteRegistration* Register_LOGISTIC_FIXED_POINT_OPT() { static TfLiteRegistration r = { activations::Init, activations::Free, activations::SigmoidPrepare, activations::SigmoidEval}; return &r; } TfLiteRegistration* Register_LOGISTIC() { // TODO(b/134622898): Switch over from the LUT optimized method to the fixed // point optimized method when typical Android hardware performs better on // the latter one. return Register_LOGISTIC_GENERIC_OPT(); } TfLiteRegistration* Register_SOFTMAX() { static TfLiteRegistration r = { activations::SoftmaxInit, activations::SoftmaxFree, activations::SoftmaxPrepare, activations::SoftmaxEval}; return &r; } TfLiteRegistration* Register_LOG_SOFTMAX_REF() { static TfLiteRegistration r = { activations::LogSoftmaxInit, activations::LogSoftmaxFree, activations::LogSoftmaxPrepare, activations::LogSoftmaxEval}; return &r; } TfLiteRegistration* Register_LOG_SOFTMAX() { static TfLiteRegistration r = { activations::LogSoftmaxInit, activations::LogSoftmaxFree, activations::LogSoftmaxPrepare, activations::LogSoftmaxEval}; return &r; } TfLiteRegistration* Register_PRELU_REF() { static TfLiteRegistration r = { activations::PreluInit, activations::PreluFree, activations::PreluPrepare, activations::PreluEval}; return &r; } TfLiteRegistration* Register_PRELU() { static TfLiteRegistration r = { activations::PreluInit, activations::PreluFree, activations::PreluPrepare, activations::PreluEval}; return &r; } TfLiteRegistration* Register_LEAKY_RELU() { static TfLiteRegistration r = { activations::LeakyReluInit, activations::LeakyReluFree, activations::LeakyReluPrepare, activations::LeakyReluEval}; return &r; } TfLiteRegistration* Register_HARD_SWISH() { static TfLiteRegistration r = { activations::HardSwishInit, activations::HardSwishFree, activations::HardSwishPrepare, activations::HardSwishEval}; return &r; } TfLiteRegistration* Register_HARD_SWISH_REF() { static TfLiteRegistration r = { activations::HardSwishInit, activations::HardSwishFree, activations::HardSwishPrepare, activations::HardSwishEval}; return &r; } } // namespace builtin } // namespace ops } // namespace tflite ",16208,True,3537.961387587754,median "// (c) Copyright 1995-2022 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE ""AS IS"" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, ""Critical // Applications""). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. #include ""video_cp_auto_cc_2_sc.h"" #include ""video_cp_auto_cc_2.h"" #include ""axi_clock_converter.h"" #include #include #ifdef XILINX_SIMULATOR video_cp_auto_cc_2::video_cp_auto_cc_2(const sc_core::sc_module_name& nm) : video_cp_auto_cc_2_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // initialize socket stubs } void video_cp_auto_cc_2::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""S_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'S_AXI' transactor parameters xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); // S_AXI' transactor ports mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // S_AXI' transactor sockets mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""M_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'M_AXI' transactor parameters xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); // M_AXI' transactor ports mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // M_AXI' transactor sockets mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { } } #endif // XILINX_SIMULATOR #ifdef XM_SYSTEMC video_cp_auto_cc_2::video_cp_auto_cc_2(const sc_core::sc_module_name& nm) : video_cp_auto_cc_2_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // initialize socket stubs } void video_cp_auto_cc_2::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""S_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'S_AXI' transactor parameters xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); // S_AXI' transactor ports mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // S_AXI' transactor sockets mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""M_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'M_AXI' transactor parameters xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); // M_AXI' transactor ports mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // M_AXI' transactor sockets mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { } } #endif // XM_SYSTEMC #ifdef RIVIERA video_cp_auto_cc_2::video_cp_auto_cc_2(const sc_core::sc_module_name& nm) : video_cp_auto_cc_2_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // initialize socket stubs } void video_cp_auto_cc_2::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""S_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'S_AXI' transactor parameters xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); // S_AXI' transactor ports mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // S_AXI' transactor sockets mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""M_AXI_TLM_MODE"") != 1) { // Instantiate Socket Stubs // 'M_AXI' transactor parameters xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); // M_AXI' transactor ports mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // M_AXI' transactor sockets mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { } } #endif // RIVIERA #ifdef VCSSYSTEMC video_cp_auto_cc_2::video_cp_auto_cc_2(const sc_core::sc_module_name& nm) : video_cp_auto_cc_2_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // Instantiate Socket Stubs // configure S_AXI_transactor xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // configure M_AXI_transactor xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // initialize transactors stubs S_AXI_transactor_target_wr_socket_stub = nullptr; S_AXI_transactor_target_rd_socket_stub = nullptr; M_AXI_transactor_initiator_wr_socket_stub = nullptr; M_AXI_transactor_initiator_rd_socket_stub = nullptr; } void video_cp_auto_cc_2::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""S_AXI_TLM_MODE"") != 1) { mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { S_AXI_transactor_target_wr_socket_stub = new xtlm::xtlm_aximm_target_stub(""wr_socket"",0); S_AXI_transactor_target_wr_socket_stub->bind(*(mp_S_AXI_transactor->wr_socket)); S_AXI_transactor_target_rd_socket_stub = new xtlm::xtlm_aximm_target_stub(""rd_socket"",0); S_AXI_transactor_target_rd_socket_stub->bind(*(mp_S_AXI_transactor->rd_socket)); mp_S_AXI_transactor->disable_transactor(); } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""M_AXI_TLM_MODE"") != 1) { mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { M_AXI_transactor_initiator_wr_socket_stub = new xtlm::xtlm_aximm_initiator_stub(""wr_socket"",0); M_AXI_transactor_initiator_wr_socket_stub->bind(*(mp_M_AXI_transactor->wr_socket)); M_AXI_transactor_initiator_rd_socket_stub = new xtlm::xtlm_aximm_initiator_stub(""rd_socket"",0); M_AXI_transactor_initiator_rd_socket_stub->bind(*(mp_M_AXI_transactor->rd_socket)); mp_M_AXI_transactor->disable_transactor(); } } #endif // VCSSYSTEMC #ifdef MTI_SYSTEMC video_cp_auto_cc_2::video_cp_auto_cc_2(const sc_core::sc_module_name& nm) : video_cp_auto_cc_2_sc(nm), s_axi_aclk(""s_axi_aclk""), s_axi_aresetn(""s_axi_aresetn""), s_axi_awaddr(""s_axi_awaddr""), s_axi_awprot(""s_axi_awprot""), s_axi_awvalid(""s_axi_awvalid""), s_axi_awready(""s_axi_awready""), s_axi_wdata(""s_axi_wdata""), s_axi_wstrb(""s_axi_wstrb""), s_axi_wvalid(""s_axi_wvalid""), s_axi_wready(""s_axi_wready""), s_axi_bresp(""s_axi_bresp""), s_axi_bvalid(""s_axi_bvalid""), s_axi_bready(""s_axi_bready""), s_axi_araddr(""s_axi_araddr""), s_axi_arprot(""s_axi_arprot""), s_axi_arvalid(""s_axi_arvalid""), s_axi_arready(""s_axi_arready""), s_axi_rdata(""s_axi_rdata""), s_axi_rresp(""s_axi_rresp""), s_axi_rvalid(""s_axi_rvalid""), s_axi_rready(""s_axi_rready""), m_axi_aclk(""m_axi_aclk""), m_axi_aresetn(""m_axi_aresetn""), m_axi_awaddr(""m_axi_awaddr""), m_axi_awprot(""m_axi_awprot""), m_axi_awvalid(""m_axi_awvalid""), m_axi_awready(""m_axi_awready""), m_axi_wdata(""m_axi_wdata""), m_axi_wstrb(""m_axi_wstrb""), m_axi_wvalid(""m_axi_wvalid""), m_axi_wready(""m_axi_wready""), m_axi_bresp(""m_axi_bresp""), m_axi_bvalid(""m_axi_bvalid""), m_axi_bready(""m_axi_bready""), m_axi_araddr(""m_axi_araddr""), m_axi_arprot(""m_axi_arprot""), m_axi_arvalid(""m_axi_arvalid""), m_axi_arready(""m_axi_arready""), m_axi_rdata(""m_axi_rdata""), m_axi_rresp(""m_axi_rresp""), m_axi_rvalid(""m_axi_rvalid""), m_axi_rready(""m_axi_rready"") { // initialize pins mp_impl->s_axi_aclk(s_axi_aclk); mp_impl->s_axi_aresetn(s_axi_aresetn); mp_impl->m_axi_aclk(m_axi_aclk); mp_impl->m_axi_aresetn(m_axi_aresetn); // initialize transactors mp_S_AXI_transactor = NULL; mp_M_AXI_transactor = NULL; // Instantiate Socket Stubs // configure S_AXI_transactor xsc::common_cpp::properties S_AXI_transactor_param_props; S_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); S_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""100000000""); S_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); S_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); S_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); S_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); S_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); S_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); S_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); S_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); S_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); S_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); S_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); S_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK0""); mp_S_AXI_transactor = new xtlm::xaximm_pin2xtlm_t<32,7,1,1,1,1,1,1>(""S_AXI_transactor"", S_AXI_transactor_param_props); mp_S_AXI_transactor->AWADDR(s_axi_awaddr); mp_S_AXI_transactor->AWPROT(s_axi_awprot); mp_S_AXI_transactor->AWVALID(s_axi_awvalid); mp_S_AXI_transactor->AWREADY(s_axi_awready); mp_S_AXI_transactor->WDATA(s_axi_wdata); mp_S_AXI_transactor->WSTRB(s_axi_wstrb); mp_S_AXI_transactor->WVALID(s_axi_wvalid); mp_S_AXI_transactor->WREADY(s_axi_wready); mp_S_AXI_transactor->BRESP(s_axi_bresp); mp_S_AXI_transactor->BVALID(s_axi_bvalid); mp_S_AXI_transactor->BREADY(s_axi_bready); mp_S_AXI_transactor->ARADDR(s_axi_araddr); mp_S_AXI_transactor->ARPROT(s_axi_arprot); mp_S_AXI_transactor->ARVALID(s_axi_arvalid); mp_S_AXI_transactor->ARREADY(s_axi_arready); mp_S_AXI_transactor->RDATA(s_axi_rdata); mp_S_AXI_transactor->RRESP(s_axi_rresp); mp_S_AXI_transactor->RVALID(s_axi_rvalid); mp_S_AXI_transactor->RREADY(s_axi_rready); mp_S_AXI_transactor->CLK(s_axi_aclk); m_S_AXI_transactor_rst_signal.write(1); mp_S_AXI_transactor->RST(m_S_AXI_transactor_rst_signal); // configure M_AXI_transactor xsc::common_cpp::properties M_AXI_transactor_param_props; M_AXI_transactor_param_props.addLong(""DATA_WIDTH"", ""32""); M_AXI_transactor_param_props.addLong(""FREQ_HZ"", ""142857132""); M_AXI_transactor_param_props.addLong(""ID_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ADDR_WIDTH"", ""7""); M_AXI_transactor_param_props.addLong(""AWUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""ARUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""RUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""BUSER_WIDTH"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_LOCK"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_PROT"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_CACHE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_QOS"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_REGION"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_WSTRB"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_BRESP"", ""1""); M_AXI_transactor_param_props.addLong(""HAS_RRESP"", ""1""); M_AXI_transactor_param_props.addLong(""SUPPORTS_NARROW_BURST"", ""0""); M_AXI_transactor_param_props.addLong(""NUM_READ_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_OUTSTANDING"", ""8""); M_AXI_transactor_param_props.addLong(""MAX_BURST_LENGTH"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_READ_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""NUM_WRITE_THREADS"", ""1""); M_AXI_transactor_param_props.addLong(""RUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""WUSER_BITS_PER_BYTE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_SIZE"", ""0""); M_AXI_transactor_param_props.addLong(""HAS_RESET"", ""0""); M_AXI_transactor_param_props.addFloat(""PHASE"", ""0.000""); M_AXI_transactor_param_props.addString(""PROTOCOL"", ""AXI4LITE""); M_AXI_transactor_param_props.addString(""READ_WRITE_MODE"", ""READ_WRITE""); M_AXI_transactor_param_props.addString(""CLK_DOMAIN"", ""video_cp_ps7_0_0_FCLK_CLK1""); mp_M_AXI_transactor = new xtlm::xaximm_xtlm2pin_t<32,7,1,1,1,1,1,1>(""M_AXI_transactor"", M_AXI_transactor_param_props); mp_M_AXI_transactor->AWADDR(m_axi_awaddr); mp_M_AXI_transactor->AWPROT(m_axi_awprot); mp_M_AXI_transactor->AWVALID(m_axi_awvalid); mp_M_AXI_transactor->AWREADY(m_axi_awready); mp_M_AXI_transactor->WDATA(m_axi_wdata); mp_M_AXI_transactor->WSTRB(m_axi_wstrb); mp_M_AXI_transactor->WVALID(m_axi_wvalid); mp_M_AXI_transactor->WREADY(m_axi_wready); mp_M_AXI_transactor->BRESP(m_axi_bresp); mp_M_AXI_transactor->BVALID(m_axi_bvalid); mp_M_AXI_transactor->BREADY(m_axi_bready); mp_M_AXI_transactor->ARADDR(m_axi_araddr); mp_M_AXI_transactor->ARPROT(m_axi_arprot); mp_M_AXI_transactor->ARVALID(m_axi_arvalid); mp_M_AXI_transactor->ARREADY(m_axi_arready); mp_M_AXI_transactor->RDATA(m_axi_rdata); mp_M_AXI_transactor->RRESP(m_axi_rresp); mp_M_AXI_transactor->RVALID(m_axi_rvalid); mp_M_AXI_transactor->RREADY(m_axi_rready); mp_M_AXI_transactor->CLK(m_axi_aclk); m_M_AXI_transactor_rst_signal.write(1); mp_M_AXI_transactor->RST(m_M_AXI_transactor_rst_signal); // initialize transactors stubs S_AXI_transactor_target_wr_socket_stub = nullptr; S_AXI_transactor_target_rd_socket_stub = nullptr; M_AXI_transactor_initiator_wr_socket_stub = nullptr; M_AXI_transactor_initiator_rd_socket_stub = nullptr; } void video_cp_auto_cc_2::before_end_of_elaboration() { // configure 'S_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""S_AXI_TLM_MODE"") != 1) { mp_impl->S_TARGET_rd_socket->bind(*(mp_S_AXI_transactor->rd_socket)); mp_impl->S_TARGET_wr_socket->bind(*(mp_S_AXI_transactor->wr_socket)); } else { S_AXI_transactor_target_wr_socket_stub = new xtlm::xtlm_aximm_target_stub(""wr_socket"",0); S_AXI_transactor_target_wr_socket_stub->bind(*(mp_S_AXI_transactor->wr_socket)); S_AXI_transactor_target_rd_socket_stub = new xtlm::xtlm_aximm_target_stub(""rd_socket"",0); S_AXI_transactor_target_rd_socket_stub->bind(*(mp_S_AXI_transactor->rd_socket)); mp_S_AXI_transactor->disable_transactor(); } // configure 'M_AXI' transactor if (xsc::utils::xsc_sim_manager::getInstanceParameterInt(""video_cp_auto_cc_2"", ""M_AXI_TLM_MODE"") != 1) { mp_impl->M_INITIATOR_rd_socket->bind(*(mp_M_AXI_transactor->rd_socket)); mp_impl->M_INITIATOR_wr_socket->bind(*(mp_M_AXI_transactor->wr_socket)); } else { M_AXI_transactor_initiator_wr_socket_stub = new xtlm::xtlm_aximm_initiator_stub(""wr_socket"",0); M_AXI_transactor_initiator_wr_socket_stub->bind(*(mp_M_AXI_transactor->wr_socket)); M_AXI_transactor_initiator_rd_socket_stub = new xtlm::xtlm_aximm_initiator_stub(""rd_socket"",0); M_AXI_transactor_initiator_rd_socket_stub->bind(*(mp_M_AXI_transactor->rd_socket)); mp_M_AXI_transactor->disable_transactor(); } } #endif // MTI_SYSTEMC video_cp_auto_cc_2::~video_cp_auto_cc_2() { delete mp_S_AXI_transactor; delete mp_M_AXI_transactor; } #ifdef MTI_SYSTEMC SC_MODULE_EXPORT(video_cp_auto_cc_2); #endif #ifdef XM_SYSTEMC XMSC_MODULE_EXPORT(video_cp_auto_cc_2); #endif #ifdef RIVIERA SC_MODULE_EXPORT(video_cp_auto_cc_2); #endif ",16295,True,4797.6463594050465,median "[[azure-storage-blob-component]] = Azure Storage Blob Service Component :docTitle: Azure Storage Blob Service :artifactId: camel-azure-storage-blob :description: Store and retrieve blobs from Azure Storage Blob Service using SDK v12. :since: 3.3 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/azure-storage-blob.adoc[opts=optional] //Manually maintained attributes :group: Azure *Since Camel {since}* *{component-header}* The Azure Storage Blob component is used for storing and retrieving blobs from https://azure.microsoft.com/services/storage/blobs/[Azure Storage Blob] Service using *Azure APIs v12*. However in case of versions above v12, we will see if this component can adopt these changes depending on how much breaking changes can result. Prerequisites You must have a valid Windows Azure Storage account. More information is available at https://docs.microsoft.com/azure/[Azure Documentation Portal]. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-azure-storage-blob x.x.x ------------------------------------------------------------ == URI Format [source,text] ------------------------------ azure-storage-blob://accountName[/containerName][?options] ------------------------------ In case of consumer, accountName, containerName are required. In case of producer, it depends on the operation that being requested, for example if operation is on a container level, e.b: createContainer, accountName and containerName are only required, but in case of operation being requested in blob level, e.g: getBlob, accountName, containerName and blobName are required. The blob will be created if it does not already exist. You can append query options to the URI in the following format, ?options=value&option2=value&... // component-configure options: START == Configuring Options Camel components are configured on two separate levels: - component level - endpoint level === Configuring Component Options The component level is the highest level which holds general and common configurations that are inherited by the endpoints. For example a component may have security settings, credentials for authentication, urls for network connection and so forth. Some components only have a few options, and others may have many. Because components typically have pre configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all. Configuring components can be done with the xref:latest@manual::component-dsl.adoc[Component DSL], in a configuration file (application.properties|yaml), or directly with Java code. === Configuring Endpoint Options Where you find yourself configuring the most is on endpoints, as endpoints often have many options, which allows you to configure what you need the endpoint to do. The options are also categorized into whether the endpoint is used as consumer (from) or as a producer (to), or used for both. Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the xref:latest@manual::Endpoint-dsl.adoc[Endpoint DSL] as a _type safe_ way of configuring endpoints. A good practice when configuring options is to use xref:latest@manual::using-propertyplaceholder.adoc[Property Placeholders], which allows to not hardcode urls, port numbers, sensitive information, and other settings. In other words placeholders allows to externalize the configuration from your code, and gives more flexibility and reuse. The following two sections lists all the options, firstly for the component followed by the endpoint. // component-configure options: END // component options: START == Component Options The Azure Storage Blob Service component supports 30 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *blobName* (common) | The blob name, to consume specific blob from a container. However on producer, is only required for the operations on the blob level | | String | *blobOffset* (common) | Set the blob offset for the upload or download operations, default is 0 | 0 | long | *blobType* (common) | The blob type in order to initiate the appropriate settings for each blob type. There are 3 enums and the value can be one of: blockblob, appendblob, pageblob | blockblob | BlobType | *closeStreamAfterRead* (common) | Close the stream after read or keep it open, default is true | true | boolean | *configuration* (common) | The component configurations | | BlobConfiguration | *credentials* (common) | StorageSharedKeyCredential can be injected to create the azure client, this holds the important authentication information | | StorageSharedKeyCredential | *dataCount* (common) | How many bytes to include in the range. Must be greater than or equal to 0 if specified. | | Long | *fileDir* (common) | The file directory where the downloaded blobs will be saved to, this can be used in both, producer and consumer | | String | *maxResultsPerPage* (common) | Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxResultsPerPage or specifies a value greater than 5,000, the server will return up to 5,000 items. | | Integer | *maxRetryRequests* (common) | Specifies the maximum number of additional HTTP Get requests that will be made while reading the data from a response body. | 0 | int | *prefix* (common) | Filters the results to return only blobs whose names begin with the specified prefix. May be null to return all blobs. | | String | *regex* (common) | Filters the results to return only blobs whose names match the specified regular expression. May be null to return all if both prefix and regex are set, regex takes the priority and prefix is ignored. | | String | *serviceClient* (common) | *Autowired* Client to a storage account. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. It may also be used to construct URLs to blobs and containers. This client contains operations on a service account. Operations on a container are available on BlobContainerClient through BlobServiceClient#getBlobContainerClient(String), and operations on a blob are available on BlobClient through BlobContainerClient#getBlobClient(String). | | BlobServiceClient | *timeout* (common) | An optional timeout value beyond which a RuntimeException will be raised. | | Duration | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *blobSequenceNumber* (producer) | A user-controlled value that you can use to track requests. The value of the sequence number must be between 0 and 263 - 1.The default value is 0. | 0 | Long | *blockListType* (producer) | Specifies which type of blocks to return. There are 3 enums and the value can be one of: committed, uncommitted, all | COMMITTED | BlockListType | *changeFeedContext* (producer) | When using getChangeFeed producer operation, this gives additional context that is passed through the Http pipeline during the service call. | | Context | *changeFeedEndTime* (producer) | When using getChangeFeed producer operation, this filters the results to return events approximately before the end time. Note: A few events belonging to the next hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the end time up by an hour. | | OffsetDateTime | *changeFeedStartTime* (producer) | When using getChangeFeed producer operation, this filters the results to return events approximately after the start time. Note: A few events belonging to the previous hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the start time down by an hour. | | OffsetDateTime | *closeStreamAfterWrite* (producer) | Close the stream after write or keep it open, default is true | true | boolean | *commitBlockListLater* (producer) | When is set to true, the staged blocks will not be committed directly. | true | boolean | *createAppendBlob* (producer) | When is set to true, the append blocks will be created when committing append blocks. | true | boolean | *createPageBlob* (producer) | When is set to true, the page blob will be created when uploading page blob. | true | boolean | *downloadLinkExpiration* (producer) | Override the default expiration (millis) of URL download link. | | Long | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *operation* (producer) | The blob operation that can be used with this component on the producer. There are 19 enums and the value can be one of: listBlobContainers, createBlobContainer, deleteBlobContainer, listBlobs, getBlob, deleteBlob, downloadBlobToFile, downloadLink, uploadBlockBlob, stageBlockBlobList, commitBlobBlockList, getBlobBlockList, createAppendBlob, commitAppendBlob, createPageBlob, uploadPageBlob, resizePageBlob, clearPageBlob, getPageBlobRanges | listBlobContainers | BlobOperationsDefinition | *pageBlobSize* (producer) | Specifies the maximum size for the page blob, up to 8 TB. The page blob size must be aligned to a 512-byte boundary. | 512 | Long | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *accessKey* (security) | Access key for the associated azure account name to be used for authentication with azure blob services | | String |=== // component options: END // endpoint options: START == Endpoint Options The Azure Storage Blob Service endpoint is configured using URI syntax: ---- azure-storage-blob:accountName/containerName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *accountName* | Azure account name to be used for authentication with azure blob services | | String | *containerName* | The blob container name | | String |=== === Query Parameters (47 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *blobName* (common) | The blob name, to consume specific blob from a container. However on producer, is only required for the operations on the blob level | | String | *blobOffset* (common) | Set the blob offset for the upload or download operations, default is 0 | 0 | long | *blobServiceClient* (common) | Client to a storage account. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. It may also be used to construct URLs to blobs and containers. This client contains operations on a service account. Operations on a container are available on BlobContainerClient through getBlobContainerClient(String), and operations on a blob are available on BlobClient through getBlobContainerClient(String).getBlobClient(String). | | BlobServiceClient | *blobType* (common) | The blob type in order to initiate the appropriate settings for each blob type. There are 3 enums and the value can be one of: blockblob, appendblob, pageblob | blockblob | BlobType | *closeStreamAfterRead* (common) | Close the stream after read or keep it open, default is true | true | boolean | *credentials* (common) | StorageSharedKeyCredential can be injected to create the azure client, this holds the important authentication information | | StorageSharedKeyCredential | *dataCount* (common) | How many bytes to include in the range. Must be greater than or equal to 0 if specified. | | Long | *fileDir* (common) | The file directory where the downloaded blobs will be saved to, this can be used in both, producer and consumer | | String | *maxResultsPerPage* (common) | Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxResultsPerPage or specifies a value greater than 5,000, the server will return up to 5,000 items. | | Integer | *maxRetryRequests* (common) | Specifies the maximum number of additional HTTP Get requests that will be made while reading the data from a response body. | 0 | int | *prefix* (common) | Filters the results to return only blobs whose names begin with the specified prefix. May be null to return all blobs. | | String | *regex* (common) | Filters the results to return only blobs whose names match the specified regular expression. May be null to return all if both prefix and regex are set, regex takes the priority and prefix is ignored. | | String | *serviceClient* (common) | *Autowired* Client to a storage account. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. It may also be used to construct URLs to blobs and containers. This client contains operations on a service account. Operations on a container are available on BlobContainerClient through BlobServiceClient#getBlobContainerClient(String), and operations on a blob are available on BlobClient through BlobContainerClient#getBlobClient(String). | | BlobServiceClient | *timeout* (common) | An optional timeout value beyond which a RuntimeException will be raised. | | Duration | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *sendEmptyMessageWhenIdle* (consumer) | If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *pollStrategy* (consumer) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | | PollingConsumerPollStrategy | *blobSequenceNumber* (producer) | A user-controlled value that you can use to track requests. The value of the sequence number must be between 0 and 263 - 1.The default value is 0. | 0 | Long | *blockListType* (producer) | Specifies which type of blocks to return. There are 3 enums and the value can be one of: committed, uncommitted, all | COMMITTED | BlockListType | *changeFeedContext* (producer) | When using getChangeFeed producer operation, this gives additional context that is passed through the Http pipeline during the service call. | | Context | *changeFeedEndTime* (producer) | When using getChangeFeed producer operation, this filters the results to return events approximately before the end time. Note: A few events belonging to the next hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the end time up by an hour. | | OffsetDateTime | *changeFeedStartTime* (producer) | When using getChangeFeed producer operation, this filters the results to return events approximately after the start time. Note: A few events belonging to the previous hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the start time down by an hour. | | OffsetDateTime | *closeStreamAfterWrite* (producer) | Close the stream after write or keep it open, default is true | true | boolean | *commitBlockListLater* (producer) | When is set to true, the staged blocks will not be committed directly. | true | boolean | *createAppendBlob* (producer) | When is set to true, the append blocks will be created when committing append blocks. | true | boolean | *createPageBlob* (producer) | When is set to true, the page blob will be created when uploading page blob. | true | boolean | *downloadLinkExpiration* (producer) | Override the default expiration (millis) of URL download link. | | Long | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *operation* (producer) | The blob operation that can be used with this component on the producer. There are 19 enums and the value can be one of: listBlobContainers, createBlobContainer, deleteBlobContainer, listBlobs, getBlob, deleteBlob, downloadBlobToFile, downloadLink, uploadBlockBlob, stageBlockBlobList, commitBlobBlockList, getBlobBlockList, createAppendBlob, commitAppendBlob, createPageBlob, uploadPageBlob, resizePageBlob, clearPageBlob, getPageBlobRanges | listBlobContainers | BlobOperationsDefinition | *pageBlobSize* (producer) | Specifies the maximum size for the page blob, up to 8 TB. The page blob size must be aligned to a 512-byte boundary. | 512 | Long | *backoffErrorThreshold* (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | | int | *backoffIdleThreshold* (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | | int | *backoffMultiplier* (scheduler) | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | | int | *delay* (scheduler) | Milliseconds before the next poll. | 500 | long | *greedy* (scheduler) | If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean | *initialDelay* (scheduler) | Milliseconds before the first poll starts. | 1000 | long | *repeatCount* (scheduler) | Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long | *runLoggingLevel* (scheduler) | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | TRACE | LoggingLevel | *scheduledExecutorService* (scheduler) | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | | ScheduledExecutorService | *scheduler* (scheduler) | To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler | none | Object | *schedulerProperties* (scheduler) | To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. | | Map | *startScheduler* (scheduler) | Whether the scheduler should be auto started. | true | boolean | *timeUnit* (scheduler) | Time unit for initialDelay and delay options. There are 7 enums and the value can be one of: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS | MILLISECONDS | TimeUnit | *useFixedDelay* (scheduler) | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean | *accessKey* (security) | Access key for the associated azure account name to be used for authentication with azure blob services | | String |=== // endpoint options: END *Required information options:* To use this component, you have 3 options in order to provide the required Azure authentication information: - Provide `accountName` and `accessKey` for your Azure account, this is the simplest way to get started. The accessKey can be generated through your Azure portal. - Provide a https://azuresdkartifacts.blob.core.windows.net/azure-sdk-for-java/staging/apidocs/com/azure/storage/common/StorageSharedKeyCredential.html[StorageSharedKeyCredential] instance which can be provided into `credentials` option. - Provide a https://azuresdkdocs.blob.core.windows.net/$web/java/azure-storage-blob/12.0.0/com/azure/storage/blob/BlobServiceClient.html[BlobServiceClient] instance which can be provided into `blobServiceClient`. Note: You don't need to create a specific client, e.g: BlockBlobClient, the BlobServiceClient represents the upper level which can be used to retrieve lower level clients. == Usage For example in order to download a blob content from the block blob `hello.txt` located on the `container1` in the `camelazure` storage account, use the following snippet: [source,java] -------------------------------------------------------------------------------- from(""azure-storage-blob://camelazure/container1?blobName=hello.txt&accessKey=yourAccessKey""). to(""file://blobdirectory""); -------------------------------------------------------------------------------- === Message headers evaluated by the component producer [width=""100%"",cols=""10%,10%,10%,10%,60%"",options=""header"",] |======================================================================= |Header |Variable Name |Type |Operations |Description |`CamelAzureStorageBlobTimeout` |`BlobConstants.TIMEOUT`|`Duration`|All|An optional timeout value beyond which a {@link RuntimeException} will be raised. |`CamelAzureStorageBlobMetadata`|`BlobConstants.METADATA`|`Map`|Operations related to container and blob| Metadata to associate with the container or blob. |`CamelAzureStorageBlobPublicAccessType`|`BlobConstants.PUBLIC_ACCESS_TYPE`|`PublicAccessType`|`createContainer`|Specifies how the data in this container is available to the public. Pass `null` for no public access. |`CamelAzureStorageBlobRequestCondition`|`BlobConstants.BLOB_REQUEST_CONDITION`|`BlobRequestConditions`|Operations related to container and blob|This contains values which will restrict the successful operation of a variety of requests to the conditions present. These conditions are entirely optional. |`CamelAzureStorageBlobListDetails`|`BlobConstants.BLOB_LIST_DETAILS`|`BlobListDetails`|`listBlobs`|The details for listing specific blobs |`CamelAzureStorageBlobPrefix`|`BlobConstants.PREFIX`|`String`|`listBlobs`,`getBlob`|Filters the results to return only blobs whose names begin with the specified prefix. May be null to return all blobs. |`CamelAzureStorageBlobMaxResultsPerPage`|`BlobConstants.MAX_RESULTS_PER_PAGE`|`Integer`|`listBlobs`| Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxResultsPerPage or specifies a value greater than 5,000, the server will return up to 5,000 items. |`CamelAzureStorageBlobListBlobOptions`|`BlobConstants.LIST_BLOB_OPTIONS`|`ListBlobsOptions`|`listBlobs`|Defines options available to configure the behavior of a call to listBlobsFlatSegment on a {@link BlobContainerClient} object. |`CamelAzureStorageBlobHttpHeaders`|`BlobConstants.BLOB_HTTP_HEADERS`|`BlobHttpHeaders`|`uploadBlockBlob`, `commitBlobBlockList`, `createAppendBlob`, `createPageBlob`| Additional parameters for a set of operations. |`CamelAzureStorageBlobAccessTier`|`BlobConstants.ACCESS_TIER`|`AccessTier`|`uploadBlockBlob`, `commitBlobBlockList`| Defines values for AccessTier. |`CamelAzureStorageBlobContentMD5`|`BlobConstants.CONTENT_MD5`|`byte[]`|Most operations related to upload blob|An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. When this header is specified, the storage service compares the hash of the content that has arrived with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the operation will fail. |`CamelAzureStorageBlobPageBlobRange`|`BlobConstants.PAGE_BLOB_RANGE`|`PageRange`|Operations related to page blob| A {@link PageRange} object. Given that pages must be aligned with 512-byte boundaries, the start offset must be a modulus of 512 and the end offset must be a modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, etc. |`CamelAzureStorageBlobCommitBlobBlockListLater`|`BlobConstants.COMMIT_BLOCK_LIST_LATER`|`boolean`|`stageBlockBlobList`| When is set to `true`, the staged blocks will not be committed directly. |`CamelAzureStorageBlobCreateAppendBlob`|`BlobConstants.CREATE_APPEND_BLOB`|`boolean`|`commitAppendBlob`| When is set to `true`, the append blocks will be created when committing append blocks. |`CamelAzureStorageBlobCreatePageBlob`|`BlobConstants.CREATE_PAGE_BLOB`|`boolean`|`uploadPageBlob`| When is set to `true`, the page blob will be created when uploading page blob. |`CamelAzureStorageBlobBlockListType`|`BlobConstants.BLOCK_LIST_TYPE`|`BlockListType`|`getBlobBlockList`| Specifies which type of blocks to return. |`CamelAzureStorageBlobPageBlobSize`|`BlobConstants.PAGE_BLOB_SIZE`|`Long`|`createPageBlob`, `resizePageBlob`| Specifies the maximum size for the page blob, up to 8 TB. The page blob size must be aligned to a 512-byte boundary. |`CamelAzureStorageBlobSequenceNumber`|`BlobConstants.BLOB_SEQUENCE_NUMBER`|`Long`|`createPageBlob`|A user-controlled value that you can use to track requests. The value of the sequence number must be between 0 and 2^63 - 1.The default value is 0. |`CamelAzureStorageBlobDeleteSnapshotsOptionType`|`BlobConstants.DELETE_SNAPSHOT_OPTION_TYPE`|`DeleteSnapshotsOptionType`|`deleteBlob`| Specifies the behavior for deleting the snapshots on this blob. {@code Include} will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being deleted, you must pass null. |`CamelAzureStorageBlobListBlobContainersOptions`|`BlobConstants.LIST_BLOB_CONTAINERS_OPTIONS`|`ListBlobContainersOptions`|`listBlobContainers`| A {@link ListBlobContainersOptions} which specifies what data should be returned by the service. |`CamelAzureStorageBlobParallelTransferOptions`|`BlobConstants.PARALLEL_TRANSFER_OPTIONS`|`ParallelTransferOptions`|`downloadBlobToFile`| {@link ParallelTransferOptions} to use to download to file. Number of parallel transfers parameter is ignored. |`CamelAzureStorageBlobFileDir`|`BlobConstants.FILE_DIR`|`String`|`downloadBlobToFile`|The file directory where the downloaded blobs will be saved to. |`CamelAzureStorageBlobDownloadLinkExpiration`|`BlobConstants.DOWNLOAD_LINK_EXPIRATION`|`Long`|`downloadLink`| Override the default expiration (millis) of URL download link. |`CamelAzureStorageBlobBlobName`|`BlobConstants.BLOB_NAME`|`String`|Operations related to blob| Override/set the blob name on the exchange headers. |`CamelAzureStorageBlobContainerName`|`BlobConstants.BLOB_CONTAINER_NAME`|`String`|Operations related to container and blob|Override/set the container name on the exchange headers. |`CamelAzureStorageBlobOperation`|`BlobConstants.BLOB_OPERATION`|`BlobOperationsDefinition`|All|Specify the producer operation to execute, please see the doc on this page related to producer operation. |`CamelAzureStorageBlobRegex`|`BlobConstants.REGEX`|`String`|`listBlobs`,`getBlob`|Filters the results to return only blobs whose names match the specified regular expression. May be null to return all. If both prefix and regex are set, regex takes the priority and prefix is ignored. |`CamelAzureStorageBlobChangeFeedStartTime`|`BlobConstants.CHANGE_FEED_START_TIME`|`OffsetDateTime`|`getChangeFeed`| It filters the results to return events approximately after the start time. Note: A few events belonging to the previous hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the start time down by an hour. |`CamelAzureStorageBlobChangeFeedEndTime`|`BlobConstants.CHANGE_FEED_END_TIME`|`OffsetDateTime`|`getChangeFeed`| It filters the results to return events approximately before the end time. Note: A few events belonging to the next hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the end time up by an hour. |`CamelAzureStorageBlobChangeFeedContext`|`BlobConstants.CHANGE_FEED_CONTEXT`|`Context`|`getChangeFeed`| This gives additional context that is passed through the Http pipeline during the service call. |======================================================================= === Message headers set by either component producer or consumer [width=""100%"",cols=""10%,10%,10%,70%"",options=""header"",] |======================================================================= |Header |Variable Name |Type |Description |`CamelAzureStorageBlobAccessTier`|`BlobConstants.ACCESS_TIER`|`AccessTier`| Access tier of the blob. |`CamelAzureStorageBlobAccessTierChangeTime`|`BlobConstants.ACCESS_TIER_CHANGE_TIME`|`OffsetDateTime`| Datetime when the access tier of the blob last changed. |`CamelAzureStorageBlobArchiveStatus`|`BlobConstants.ARCHIVE_STATUS`|`ArchiveStatus`|Archive status of the blob. |`CamelAzureStorageBlobCreationTime`|`BlobConstants.CREATION_TIME`|`OffsetDateTime`|Creation time of the blob. |`CamelAzureStorageBlobSequenceNumber`|`BlobConstants.BLOB_SEQUENCE_NUMBER`|`Long`|The current sequence number for a page blob. |`CamelAzureStorageBlobBlobSize`|`BlobConstants.BLOB_SIZE`|`long`|The size of the blob. |`CamelAzureStorageBlobBlobType`|`BlobConstants.BLOB_TYPE`|`BlobType`|The type of the blob. |`CamelAzureStorageBlobCacheControl`|`BlobConstants.CACHE_CONTROL`|`String`|Cache control specified for the blob. |`CamelAzureStorageBlobCommittedBlockCount`|`BlobConstants.COMMITTED_BLOCK_COUNT`|`Integer`| Number of blocks committed to an append blob |`CamelAzureStorageBlobContentDisposition`|`BlobConstants.CONTENT_DISPOSITION`|`String`|Content disposition specified for the blob. |`CamelAzureStorageBlobContentEncoding`|`BlobConstants.CONTENT_ENCODING`|`String`|Content encoding specified for the blob. |`CamelAzureStorageBlobContentLanguage`|`BlobConstants.CONTENT_LANGUAGE`|`String`|Content language specified for the blob. |`CamelAzureStorageBlobContentMd5`|`BlobConstants.CONTENT_MD5`|`byte[]`|Content MD5 specified for the blob. |`CamelAzureStorageBlobContentType`|`BlobConstants.CONTENT_TYPE`|`String`|Content type specified for the blob. |`CamelAzureStorageBlobCopyCompletionTime`|`BlobConstants.COPY_COMPILATION_TIME`|`OffsetDateTime`|Datetime when the last copy operation on the blob completed. |`CamelAzureStorageBlobCopyDestinationSnapshot`|`BlobConstants.COPY_DESTINATION_SNAPSHOT`|`String`|Snapshot identifier of the last incremental copy snapshot for the blob. |`CamelAzureStorageBlobCopyId`|`BlobConstants.COPY_ID`|`String`|Identifier of the last copy operation performed on the blob. |`CamelAzureStorageBlobCopyProgress`|`BlobConstants.COPY_PROGRESS`|`String`|Progress of the last copy operation performed on the blob. |`CamelAzureStorageBlobCopySource`|`BlobConstants.COPY_SOURCE`|`String`|Source of the last copy operation performed on the blob. |`CamelAzureStorageBlobCopyStatus`|`BlobConstants.COPY_STATUS`|`CopyStatusType`|Status of the last copy operation performed on the blob. |`CamelAzureStorageBlobCopyStatusDescription` | `BlobConstants.COPY_STATUS_DESCRIPTION`|`String`|Description of the last copy operation on the blob. |`CamelAzureStorageBlobETag`|`BlobConstants.E_TAG`|`String`| The E Tag of the blob |`CamelAzureStorageBlobIsAccessTierInferred`|`BlobConstants.IS_ACCESS_TIER_INFRRRED`|`boolean`| Flag indicating if the access tier of the blob was inferred from properties of the blob. |`CamelAzureStorageBlobIsIncrementalCopy`|`BlobConstants.IS_INCREMENTAL_COPY`|`boolean`|Flag indicating if the blob was incrementally copied. |`CamelAzureStorageBlobIsServerEncrypted`|`BlobConstants.IS_SERVER_ENCRYPTED`|`boolean`|Flag indicating if the blob's content is encrypted on the server. |`CamelAzureStorageBlobLastModified`|`BlobConstants.LAST_MODIFIED`|`OffsetDateTime`|Datetime when the blob was last modified. |`CamelAzureStorageBlobLeaseDuration`|`BlobConstants.LEASE_DURATION`|`LeaseDurationType`|Type of lease on the blob. |`CamelAzureStorageBlobLeaseState`|`BlobConstants.LEASE_STATE`|`LeaseStateType`|State of the lease on the blob. |`CamelAzureStorageBlobLeaseStatus`|`BlobConstants.LEASE_STATUS`|`LeaseStatusType`|Status of the lease on the blob. |`CamelAzureStorageBlobMetadata`|`BlobConstants.METADATA`|`Map`| Additional metadata associated with the blob. |`CamelAzureStorageBlobAppendOffset`|`BlobConstants.APPEND_OFFSET`|`String`| The offset at which the block was committed to the block blob. |`CamelAzureStorageBlobFileName`|`BlobConstants.FILE_NAME`|`String`|The downloaded filename from the operation `downloadBlobToFile`. |`CamelAzureStorageBlobDownloadLink`|`BlobConstants.DOWNLOAD_LINK`|`String`|The download link generated by `downloadLink` operation. |`CamelAzureStorageBlobRawHttpHeaders`|`BlobConstants.RAW_HTTP_HEADERS`|`HttpHeaders`|Returns non-parsed httpHeaders that can be used by the user. |======================================================================= === Advanced Azure Storage Blob configuration If your Camel Application is running behind a firewall or if you need to have more control over the `BlobServiceClient` instance configuration, you can create your own instance: [source,java] ----------------------------------------------------------------------- StorageSharedKeyCredential credential = new StorageSharedKeyCredential(""yourAccountName"", ""yourAccessKey""); String uri = String.format(""https://%s.blob.core.windows.net"", ""yourAccountName""); BlobServiceClient client = new BlobServiceClientBuilder() .endpoint(uri) .credential(credential) .buildClient(); // This is camel context context.getRegistry().bind(""client"", client); ----------------------------------------------------------------------- Then refer to this instance in your Camel `azure-storage-blob` component configuration: [source,java] ----------------------------------------------------------------------- from(""azure-storage-blob://cameldev/container1?blobName=myblob&serviceClient=#client"") .to(""mock:result""); ----------------------------------------------------------------------- === Automatic detection of BlobServiceClient client in registry The component is capable of detecting the presence of an BlobServiceClient bean into the registry. If it's the only instance of that type it will be used as client and you won't have to define it as uri parameter, like the example above. This may be really useful for smarter configuration of the endpoint. === Azure Storage Blob Producer operations Camel Azure Storage Blob component provides wide range of operations on the producer side: *Operations on the service level* For these operations, `accountName` is *required*. [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Operation |Description |`listBlobContainers` |Get the content of the blob. You can restrict the output of this operation to a blob range. |`getChangeFeed` | Returns transaction logs of all the changes that occur to the blobs and the blob metadata in your storage account. The change feed provides ordered, guaranteed, durable, immutable, read-only log of these changes. |=== *Operations on the container level* For these operations, `accountName` and `containerName` are *required*. [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Operation |Description |`createBlobContainer` | Creates a new container within a storage account. If a container with the same name already exists, the producer will ignore it. |`deleteBlobContainer` | Deletes the specified container in the storage account. If the container doesn't exist the operation fails. |`listBlobs`| Returns a list of blobs in this container, with folder structures flattened. |=== *Operations on the blob level* For these operations, `accountName`, `containerName` and `blobName` are *required*. [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |=== |Operation |Blob Type|Description |`getBlob` |Common|Get the content of the blob. You can restrict the output of this operation to a blob range. |`deleteBlob` |Common|Delete a blob. |`downloadBlobToFile` |Common|Downloads the entire blob into a file specified by the path.The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} will be thrown. |`downloadLink` |Common| Generates the download link for the specified blob using shared access signatures (SAS). This by default only limit to 1hour of allowed access. However, you can override the default expiration duration through the headers. |`uploadBlockBlob` |BlockBlob|Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the existing blob is overwritten with the new content. |`stageBlockBlobList`|`BlockBlob`|Uploads the specified block to the block blob's ""staging area"" to be later committed by a call to commitBlobBlockList. However in case header `CamelAzureStorageBlobCommitBlobBlockListLater` or config `commitBlockListLater` is set to false, this will commit the blocks immediately after staging the blocks. |`commitBlobBlockList`|`BlockBlob`|Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of a blob, a block must have been successfully written to the server in a prior `stageBlockBlobList` operation. You can call `commitBlobBlockList` to update a blob by uploading only those blocks that have changed, then committing the new and existing blocks together. Any blocks not specified in the block list and permanently deleted. |`getBlobBlockList` |`BlockBlob`|Returns the list of blocks that have been uploaded as part of a block blob using the specified block list filter. |`createAppendBlob` |`AppendBlob`|Creates a 0-length append blob. Call commitAppendBlo`b operation to append data to an append blob. |`commitAppendBlob` |`AppendBlob`|Commits a new block of data to the end of the existing append blob. In case of header `CamelAzureStorageBlobCreateAppendBlob` or config `createAppendBlob` is set to true, it will attempt to create the appendBlob through internal call to `createAppendBlob` operation first before committing. |`createPageBlob`|`PageBlob`|Creates a page blob of the specified length. Call `uploadPageBlob` operation to upload data data to a page blob. |`uploadPageBlob`|`PageBlob`|Writes one or more pages to the page blob. The write size must be a multiple of 512. In case of header `CamelAzureStorageBlobCreatePageBlob` or config `createPageBlob` is set to true, it will attempt to create the appendBlob through internal call to `createPageBlob` operation first before uploading. |`resizePageBlob`|`PageBlob`| Resizes the page blob to the specified size (which must be a multiple of 512). |`clearPageBlob`|`PageBlob`| Frees the specified pages from the page blob. The size of the range must be a multiple of 512. |`getPageBlobRanges`|`PageBlob`|Returns the list of valid page ranges for a page blob or snapshot of a page blob. |=== Refer to the example section in this page to learn how to use these operations into your camel application. === Consumer Examples To consume a blob into a file using file component, this can be done like this: [source,java] -------------------------------------------------------------------------------- from(""azure-storage-blob://camelazure/container1?blobName=hello.txt&accountName=yourAccountName&accessKey=yourAccessKey""). to(""file://blobdirectory""); -------------------------------------------------------------------------------- However, you can also write to file directly without using the file component, you will need to specify `fileDir` folder path in order to save your blob in your machine. [source,java] -------------------------------------------------------------------------------- from(""azure-storage-blob://camelazure/container1?blobName=hello.txt&accountName=yourAccountName&accessKey=yourAccessKey&fileDir=/var/to/awesome/dir""). to(""mock:results""); -------------------------------------------------------------------------------- Also, the component supports batch consumer, hence you can consume multiple blobs with only specifying the container name, the consumer will return multiple exchanges depending on the number of the blobs in the container. Example: [source,java] -------------------------------------------------------------------------------- from(""azure-storage-blob://camelazure/container1?accountName=yourAccountName&accessKey=yourAccessKey&fileDir=/var/to/awesome/dir""). to(""mock:results""); -------------------------------------------------------------------------------- === Producer Operations Examples - `listBlobContainers`: [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.LIST_BLOB_CONTAINERS_OPTIONS, new ListBlobContainersOptions().setMaxResultsPerPage(10)); }) .to(""azure-storage-blob://camelazure?operation=listBlobContainers&client&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `createBlobContainer`: [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_CONTAINER_NAME, ""newContainerName""); }) .to(""azure-storage-blob://camelazure/container1?operation=createBlobContainer&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `deleteBlobContainer`: [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_CONTAINER_NAME, ""overridenName""); }) .to(""azure-storage-blob://camelazure/container1?operation=deleteBlobContainer&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `listBlobs`: [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_CONTAINER_NAME, ""overridenName""); }) .to(""azure-storage-blob://camelazure/container1?operation=listBlobs&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `getBlob`: We can either set an `outputStream` in the exchange body and write the data to it. E.g: [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_CONTAINER_NAME, ""overridenName""); // set our body exchange.getIn().setBody(outputStream); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=getBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- If we don't set a body, then this operation will give us an `InputStream` instance which can proceeded further downstream: [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=getBlob&serviceClient=#client"") .process(exchange -> { InputStream inputStream = exchange.getMessage().getBody(InputStream.class); // We use Apache common IO for simplicity, but you are free to do whatever dealing // with inputStream System.out.println(IOUtils.toString(inputStream, StandardCharsets.UTF_8.name())); }) .to(""mock:result""); -------------------------------------------------------------------------------- - `deleteBlob`: [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_NAME, ""overridenName""); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=deleteBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `downloadBlobToFile`: [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_NAME, ""overridenName""); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=downloadBlobToFile&fileDir=/var/mydir&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `downloadLink` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=downloadLink&serviceClient=#client"") .process(exchange -> { String link = exchange.getMessage().getHeader(BlobConstants.DOWNLOAD_LINK, String.class); System.out.println(""My link "" + link); }) .to(""mock:result""); -------------------------------------------------------------------------------- - `uploadBlockBlob` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // set the header you want the producer to evaluate, refer to the previous // section to learn about the headers that can be set // e.g: exchange.getIn().setHeader(BlobConstants.BLOB_NAME, ""overridenName""); exchange.getIn().setBody(""Block Blob""); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=uploadBlockBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `stageBlockBlobList` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { final List blocks = new LinkedList<>(); blocks.add(BlobBlock.createBlobBlock(new ByteArrayInputStream(""Hello"".getBytes()))); blocks.add(BlobBlock.createBlobBlock(new ByteArrayInputStream(""From"".getBytes()))); blocks.add(BlobBlock.createBlobBlock(new ByteArrayInputStream(""Camel"".getBytes()))); exchange.getIn().setBody(blocks); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=stageBlockBlobList&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `commitBlockBlobList` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { // We assume here you have the knowledge of these blocks you want to commit final List blocksIds = new LinkedList<>(); blocksIds.add(new Block().setName(""id-1"")); blocksIds.add(new Block().setName(""id-2"")); blocksIds.add(new Block().setName(""id-3"")); exchange.getIn().setBody(blocksIds); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=commitBlockBlobList&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `getBlobBlockList` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=getBlobBlockList&serviceClient=#client"") .log(""${body}"") .to(""mock:result""); -------------------------------------------------------------------------------- - `createAppendBlob` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=createAppendBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `commitAppendBlob` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { final String data = ""Hello world from my awesome tests!""; final InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); exchange.getIn().setBody(dataStream); // of course you can set whatever headers you like, refer to the headers section to learn more }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=commitAppendBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `createPageBlob` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=createPageBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `uploadPageBlob` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { byte[] dataBytes = new byte[512]; // we set range for the page from 0-511 new Random().nextBytes(dataBytes); final InputStream dataStream = new ByteArrayInputStream(dataBytes); final PageRange pageRange = new PageRange().setStart(0).setEnd(511); exchange.getIn().setHeader(BlobConstants.PAGE_BLOB_RANGE, pageRange); exchange.getIn().setBody(dataStream); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=uploadPageBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `resizePageBlob` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { final PageRange pageRange = new PageRange().setStart(0).setEnd(511); exchange.getIn().setHeader(BlobConstants.PAGE_BLOB_RANGE, pageRange); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=resizePageBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `clearPageBlob` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { final PageRange pageRange = new PageRange().setStart(0).setEnd(511); exchange.getIn().setHeader(BlobConstants.PAGE_BLOB_RANGE, pageRange); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=clearPageBlob&serviceClient=#client"") .to(""mock:result""); -------------------------------------------------------------------------------- - `getPageBlobRanges` [source,java] -------------------------------------------------------------------------------- from(""direct:start"") .process(exchange -> { final PageRange pageRange = new PageRange().setStart(0).setEnd(511); exchange.getIn().setHeader(BlobConstants.PAGE_BLOB_RANGE, pageRange); }) .to(""azure-storage-blob://camelazure/container1?blobName=blob&operation=getPageBlobRanges&serviceClient=#client"") .log(""${body}"") .to(""mock:result""); -------------------------------------------------------------------------------- === Development Notes (Important) All integration tests use [Testcontainers](https://www.testcontainers.org/) and run by default. Obtaining of Azure accessKey and accountName is needed to be able to run all integration tests using Azure services. In addition to the mocked unit tests you *will need to run the integration tests with every change you make or even client upgrade as the Azure client can break things even on minor versions upgrade.* To run the integration tests, on this component directory, run the following maven command: [source,bash] ---- mvn verify -PfullTests -DaccountName=myacc -DaccessKey=mykey ---- Whereby `accountName` is your Azure account name and `accessKey` is the access key being generated from Azure portal. include::{page-component-version}@camel-spring-boot::page$azure-storage-blob-starter.adoc[] ",12440,False,2187.34806320306,median "// tag::HeaderFullDisplayName[] = property.RepoObjectColumnProperty_sys_repo - V // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--pk_index_guid: :ExistsProperty--pk_indexpatterncolumndatatype: :ExistsProperty--pk_indexpatterncolumnname: :ExistsProperty--referencedobjectlist: :ExistsProperty--sql_modules_definition: :ExistsProperty--FK: :ExistsProperty--AntoraIndexList: :ExistsProperty--Columns: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 5590291C-9D61-EB11-84DC-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] property.RepoObjectColumnProperty_sys_repo // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] V // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] view // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 564913084 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-08-17 18:58:33 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-repoobjectcolumnunderlineguid] === RepoObjectColumn_guid [cols=""d,8a,m,m,m""] |=== |1 |*RepoObjectColumn_guid* |uniqueidentifier |NOT NULL | |=== .Referenced Columns -- * xref:repo.repoobjectcolumn.adoc#column-repoobjectcolumnunderlineguid[+repo.RepoObjectColumn.RepoObjectColumn_guid+] -- [#column-propertyunderlinename] === property_name [cols=""d,8a,m,m,m""] |=== |2 |*property_name* |sysname |NOT NULL | |=== .Referenced Columns -- * xref:repo_sys.extendedproperties.adoc#column-propertyunderlinename[+repo_sys.ExtendedProperties.property_name+] -- [#column-propertyunderlinevalue] === property_value [cols=""d,8a,m,m,m""] |=== | |property_value |sql_variant |NULL | |=== .Referenced Columns -- * xref:repo_sys.extendedproperties.adoc#column-propertyunderlinevalue[+repo_sys.ExtendedProperties.property_value+] -- [#column-repoobjectcolumnpropertyunderlineid] === RepoObjectColumnProperty_id [cols=""d,8a,m,m,m""] |=== | |RepoObjectColumnProperty_id |int |NULL | |=== [#column-repoobjectcolumnpropertyunderlinepropertyunderlinevalue] === RepoObjectColumnProperty_property_value [cols=""d,8a,m,m,m""] |=== | |RepoObjectColumnProperty_property_value |nvarchar(max) |NULL | |=== [#column-sysobjectunderlinename] === SysObject_name [cols=""d,8a,m,m,m""] |=== | |SysObject_name |nvarchar(128) |NULL | |=== .Referenced Columns -- * xref:repo_sys.extendedproperties.adoc#column-sysobjectunderlinename[+repo_sys.ExtendedProperties.SysObject_name+] -- [#column-sysobjectunderlineschemaunderlinename] === SysObject_schema_name [cols=""d,8a,m,m,m""] |=== | |SysObject_schema_name |nvarchar(128) |NULL | |=== .Referenced Columns -- * xref:repo_sys.extendedproperties.adoc#column-sysobjectunderlineschemaunderlinename[+repo_sys.ExtendedProperties.SysObject_schema_name+] -- [#column-sysobjectcolumnunderlinename] === SysObjectColumn_name [cols=""d,8a,m,m,m""] |=== | |SysObjectColumn_name |nvarchar(128) |NULL | |=== .Referenced Columns -- * xref:repo_sys.extendedproperties.adoc#column-entityunderlinecolumnunderlinename[+repo_sys.ExtendedProperties.entity_column_name+] -- // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] |1 |*<>* |uniqueidentifier |NOT NULL | |2 |*<>* |sysname |NOT NULL | // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |sql_variant |NULL | | |<> |int |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(128) |NULL | | |<> |nvarchar(128) |NULL | | |<> |nvarchar(128) |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] [#index-pkunderlinerepoobjectcolumnpropertyunderlinesysunderlinerepo] === PK_RepoObjectColumnProperty_sys_repo * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier * <>; sysname -- * PK, Unique, Real: 1, 1, 0 [#index-idxunderlinerepoobjectcolumnpropertyunderlinesysunderlinerepounderlineunderline2] === idx_RepoObjectColumnProperty_sys_repo++__++2 * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier -- * PK, Unique, Real: 0, 0, 0 // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:property.repoobjectcolumnproperty_sys_repo.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:property.repoobjectcolumnproperty.adoc[] * xref:dhw:sqldb:repo.repoobject.adoc[] * xref:dhw:sqldb:repo.repoobjectcolumn.adoc[] * xref:dhw:sqldb:repo_sys.extendedproperties.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:property.usp_sync_extendedproperties_sys2repo_insertupdate.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] 08D646ED-5E9F-EB11-84F8-A81E8446D5B0 // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] uniqueidentifier,sysname // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] RepoObjectColumn_guid,property_name // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [property].[RepoObjectColumnProperty] * [repo].[RepoObject] * [repo].[RepoObjectColumn] * [repo_sys].[ExtendedProperties] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_sys_repo.adoc[]"" as property.RepoObjectColumnProperty_sys_repo << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (sysname) property_value : (sql_variant) RepoObjectColumnProperty_id : (int) RepoObjectColumnProperty_property_value : (nvarchar(max)) SysObject_name : (nvarchar(128)) SysObject_schema_name : (nvarchar(128)) SysObjectColumn_name : (nvarchar(128)) -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_sys_repo.adoc[]"" as property.RepoObjectColumnProperty_sys_repo << V >> { - **PK_RepoObjectColumnProperty_sys_repo** .. RepoObjectColumn_guid; uniqueidentifier property_name; sysname -- - idx_RepoObjectColumnProperty_sys_repo__2 .. RepoObjectColumn_guid; uniqueidentifier } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty.adoc[]"" as property.RepoObjectColumnProperty << U >> { - **RepoObjectColumnProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_sys_repo.adoc[]"" as property.RepoObjectColumnProperty_sys_repo << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (sysname) -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_sys2repo_insertupdate.adoc[]"" as property.usp_sync_ExtendedProperties_Sys2Repo_InsertUpdate << P >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn.adoc[]"" as repo.RepoObjectColumn << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo_sys.extendedproperties.adoc[]"" as repo_sys.ExtendedProperties << V >> { -- } property.RepoObjectColumnProperty <.. property.RepoObjectColumnProperty_sys_repo property.RepoObjectColumnProperty_sys_repo <.. property.usp_sync_ExtendedProperties_Sys2Repo_InsertUpdate repo.RepoObject <.. property.RepoObjectColumnProperty_sys_repo repo.RepoObjectColumn <.. property.RepoObjectColumnProperty_sys_repo repo_sys.ExtendedProperties <.. property.RepoObjectColumnProperty_sys_repo footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:config.ftv_dwh_database.adoc[]"" as config.ftv_dwh_database << IF >> { -- } entity ""puml-link:dhw:sqldb:config.ftv_get_parameter_value.adoc[]"" as config.ftv_get_parameter_value << IF >> { -- } entity ""puml-link:dhw:sqldb:config.parameter.adoc[]"" as config.Parameter << U >> { - **Parameter_name** : (varchar(100)) - **sub_Parameter** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.parameter_default.adoc[]"" as configT.Parameter_default << V >> { - **Parameter_name** : (varchar(52)) - **sub_Parameter** : (nvarchar(26)) -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectcolumnproperty.adoc[]"" as property.external_RepoObjectColumnProperty << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectproperty.adoc[]"" as property.external_RepoObjectProperty << U >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject.adoc[]"" as property.PropertyName_RepoObject << V >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject_t.adoc[]"" as property.PropertyName_RepoObject_T << U >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty.adoc[]"" as property.RepoObjectColumnProperty << U >> { - **RepoObjectColumnProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_external_src.adoc[]"" as property.RepoObjectColumnProperty_external_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_external_tgt.adoc[]"" as property.RepoObjectColumnProperty_external_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_sys_repo.adoc[]"" as property.RepoObjectColumnProperty_sys_repo << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (sysname) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty.adoc[]"" as property.RepoObjectProperty << U >> { - **RepoObjectProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_src.adoc[]"" as property.RepoObjectProperty_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_tgt.adoc[]"" as property.RepoObjectProperty_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_selectedpropertyname_split.adoc[]"" as property.RepoObjectProperty_SelectedPropertyName_split << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference.adoc[]"" as reference.additional_Reference << U >> { - **Id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_src.adoc[]"" as reference.additional_Reference_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_tgt.adoc[]"" as reference.additional_Reference_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_src.adoc[]"" as reference.additional_Reference_from_ssas_src << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_tgt.adoc[]"" as reference.additional_Reference_from_ssas_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_is_external.adoc[]"" as reference.additional_Reference_is_external << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object.adoc[]"" as reference.additional_Reference_Object << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object_t.adoc[]"" as reference.additional_Reference_Object_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn.adoc[]"" as reference.additional_Reference_ObjectColumn << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) **ColumnName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn_t.adoc[]"" as reference.additional_Reference_ObjectColumn_T << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_src.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_tgt.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_src.adoc[]"" as repo.RepoObject_SSAS_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_tgt.adoc[]"" as repo.RepoObject_SSAS_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn.adoc[]"" as repo.RepoObjectColumn << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_src.adoc[]"" as repo.RepoObjectColumn_external_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_tgt.adoc[]"" as repo.RepoObjectColumn_external_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_src.adoc[]"" as repo.RepoObjectColumn_SSAS_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_tgt.adoc[]"" as repo.RepoObjectColumn_SSAS_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema.adoc[]"" as repo.RepoSchema << U >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_src.adoc[]"" as repo.RepoSchema_ssas_src << V >> { - **RepoSchema_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_tgt.adoc[]"" as repo.RepoSchema_ssas_tgt << V >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo_sys.extendedproperties.adoc[]"" as repo_sys.ExtendedProperties << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.additional_reference_step1.adoc[]"" as ssas.additional_Reference_step1 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json.adoc[]"" as ssas.model_json << U >> { - **databasename** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_10.adoc[]"" as ssas.model_json_10 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_20.adoc[]"" as ssas.model_json_20 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_201_descriptions_multiline.adoc[]"" as ssas.model_json_201_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_2011_descriptions_stragg.adoc[]"" as ssas.model_json_2011_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables.adoc[]"" as ssas.model_json_31_tables << V >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables_t.adoc[]"" as ssas.model_json_31_tables_T << U >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313_tables_partitions.adoc[]"" as ssas.model_json_313_tables_partitions << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131_tables_partitions_source.adoc[]"" as ssas.model_json_3131_tables_partitions_source << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) **tables_partitions_source_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311_tables_partitions_source_posfrom.adoc[]"" as ssas.model_json_31311_tables_partitions_source_PosFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313111_tables_partitions_source_stringfrom.adoc[]"" as ssas.model_json_313111_tables_partitions_source_StringFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131111_tables_partitions_source_posdot.adoc[]"" as ssas.model_json_3131111_tables_partitions_source_PosDot << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311111_tables_partitions_source_part123.adoc[]"" as ssas.model_json_31311111_tables_partitions_source_Part123 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources.adoc[]"" as ssas.model_json_33_dataSources << V >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources_t.adoc[]"" as ssas.model_json_33_dataSources_T << U >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:sys_dwh.columns.adoc[]"" as sys_dwh.columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.extended_properties.adoc[]"" as sys_dwh.extended_properties << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.indexes.adoc[]"" as sys_dwh.indexes << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.objects.adoc[]"" as sys_dwh.objects << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.parameters.adoc[]"" as sys_dwh.parameters << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.schemas.adoc[]"" as sys_dwh.schemas << SN >> { -- } config.ftv_dwh_database <.. repo_sys.ExtendedProperties config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.Parameter <.. property.PropertyName_RepoObject config.Parameter <.. config.ftv_get_parameter_value config.Parameter <.. config.ftv_dwh_database configT.Parameter_default <.. config.Parameter property.external_RepoObjectColumnProperty <.. property.RepoObjectColumnProperty_external_src property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.PropertyName_RepoObject_T <.. property.RepoObjectColumnProperty_external_tgt property.RepoObjectColumnProperty <.. property.RepoObjectColumnProperty_sys_repo property.RepoObjectColumnProperty_external_src <.. property.RepoObjectColumnProperty_external_tgt property.RepoObjectColumnProperty_external_tgt <.. property.RepoObjectColumnProperty property.RepoObjectProperty <.. property.RepoObjectProperty_SelectedPropertyName_split property.RepoObjectProperty <.. property.PropertyName_RepoObject property.RepoObjectProperty_external_src <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty_external_tgt <.. property.RepoObjectProperty property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_from_properties_src property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_wo_columns_from_properties_src reference.additional_Reference <.. reference.additional_Reference_is_external reference.additional_Reference_from_properties_src <.. reference.additional_Reference_from_properties_tgt reference.additional_Reference_from_properties_tgt <.. reference.additional_Reference reference.additional_Reference_from_ssas_src <.. reference.additional_Reference_from_ssas_tgt reference.additional_Reference_from_ssas_tgt <.. reference.additional_Reference reference.additional_Reference_is_external <.. reference.additional_Reference_ObjectColumn reference.additional_Reference_is_external <.. reference.additional_Reference_Object reference.additional_Reference_Object <.. reference.additional_Reference_Object_T reference.additional_Reference_Object_T <.. repo.RepoObject_external_src reference.additional_Reference_Object_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_ObjectColumn <.. reference.additional_Reference_ObjectColumn_T reference.additional_Reference_ObjectColumn_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_wo_columns_from_properties_src <.. reference.additional_Reference_wo_columns_from_properties_tgt reference.additional_Reference_wo_columns_from_properties_tgt <.. reference.additional_Reference repo.RepoObject <.. property.RepoObjectProperty_external_tgt repo.RepoObject <.. repo.RepoObjectColumn_external_src repo.RepoObject <.. property.RepoObjectColumnProperty_external_tgt repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject <.. property.RepoObjectColumnProperty_sys_repo repo.RepoObject_external_src <.. repo.RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.RepoObject repo.RepoObject_external_tgt <.. repo.RepoObjectColumn_external_tgt repo.RepoObject_SSAS_src <.. repo.RepoObject_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObject repo.RepoObject_SSAS_tgt <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObjectColumn <.. property.RepoObjectColumnProperty_sys_repo repo.RepoObjectColumn <.. property.RepoObjectColumnProperty_external_tgt repo.RepoObjectColumn_external_src <.. repo.RepoObjectColumn_external_tgt repo.RepoObjectColumn_external_tgt <.. repo.RepoObjectColumn repo.RepoObjectColumn_SSAS_src <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObjectColumn_SSAS_tgt <.. repo.RepoObjectColumn repo.RepoSchema <.. repo.RepoObject_SSAS_src repo.RepoSchema_ssas_src <.. repo.RepoSchema_ssas_tgt repo.RepoSchema_ssas_tgt <.. repo.RepoSchema repo_sys.ExtendedProperties <.. property.RepoObjectColumnProperty_sys_repo ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. repo.RepoObjectColumn_SSAS_src ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 sys_dwh.columns <.. repo_sys.ExtendedProperties sys_dwh.extended_properties <.. repo_sys.ExtendedProperties sys_dwh.indexes <.. repo_sys.ExtendedProperties sys_dwh.objects <.. repo_sys.ExtendedProperties sys_dwh.parameters <.. repo_sys.ExtendedProperties sys_dwh.schemas <.. repo_sys.ExtendedProperties footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_sys_repo.adoc[]"" as property.RepoObjectColumnProperty_sys_repo << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (sysname) -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_sys2repo_insertupdate.adoc[]"" as property.usp_sync_ExtendedProperties_Sys2Repo_InsertUpdate << P >> { -- } property.RepoObjectColumnProperty_sys_repo <.. property.usp_sync_ExtendedProperties_Sys2Repo_InsertUpdate footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty.adoc[]"" as property.RepoObjectColumnProperty << U >> { - **RepoObjectColumnProperty_id** : (int) inheritance : (tinyint) - property_name : (nvarchar(128)) - property_value : (nvarchar(max)) - RepoObjectColumn_guid : (uniqueidentifier) ~ property_bigint : (bigint) ~ property_float : (float) ~ property_int : (int) ~ property_money : (money) ~ property_real : (real) -- } entity ""puml-link:dhw:sqldb:property.repoobjectcolumnproperty_sys_repo.adoc[]"" as property.RepoObjectColumnProperty_sys_repo << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) - **property_name** : (sysname) property_value : (sql_variant) RepoObjectColumnProperty_id : (int) RepoObjectColumnProperty_property_value : (nvarchar(max)) SysObject_name : (nvarchar(128)) SysObject_schema_name : (nvarchar(128)) SysObjectColumn_name : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.usp_sync_extendedproperties_sys2repo_insertupdate.adoc[]"" as property.usp_sync_ExtendedProperties_Sys2Repo_InsertUpdate << P >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) external_AntoraComponent : (nvarchar(128)) external_AntoraModule : (nvarchar(128)) has_execution_plan_issue : (bit) has_get_referenced_issue : (bit) indent_sql_modules_definition : (tinyint) Inheritance_Source_fullname : (nvarchar(261)) Inheritance_StringAggSeparatorSql : (nvarchar(4000)) InheritanceDefinition : (nvarchar(4000)) InheritanceType : (tinyint) - is_DocsExclude : (bit) - is_external : (bit) is_repo_managed : (bit) is_required_ObjectMerge : (bit) - is_ssas : (bit) is_SysObject_missing : (bit) - modify_dt : (datetime) pk_index_guid : (uniqueidentifier) pk_IndexPatternColumnName_new : (nvarchar(4000)) Repo_history_table_guid : (uniqueidentifier) Repo_temporal_type : (tinyint) - RepoObject_name : (nvarchar(128)) RepoObject_Referencing_Count : (int) - RepoObject_schema_name : (nvarchar(128)) - RepoObject_type : (char(2)) SysObject_id : (int) SysObject_modify_date : (datetime) - SysObject_name : (nvarchar(128)) - SysObject_parent_object_id : (int) - SysObject_schema_name : (nvarchar(128)) SysObject_type : (char(2)) ~ has_different_sys_names : (bit) # is_RepoObject_name_uniqueidentifier : (int) # is_SysObject_name_uniqueidentifier : (int) ~ node_id : (bigint) # RepoObject_fullname : (nvarchar(261)) # RepoObject_fullname2 : (nvarchar(257)) # SysObject_fullname : (nvarchar(261)) # SysObject_fullname2 : (nvarchar(257)) ~ SysObject_query_sql : (nvarchar(406)) ~ usp_persistence_fullname : (nvarchar(273)) # usp_persistence_fullname2 : (nvarchar(269)) # usp_persistence_name : (nvarchar(140)) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn.adoc[]"" as repo.RepoObjectColumn << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) Inheritance_StringAggSeparatorSql : (nvarchar(4000)) InheritanceDefinition : (nvarchar(4000)) InheritanceType : (tinyint) is_persistence_no_check : (bit) is_persistence_no_include : (bit) is_persistence_no_update : (bit) is_query_plan_expression : (bit) is_required_ColumnMerge : (bit) is_SysObjectColumn_missing : (bit) persistence_source_RepoObjectColumn_guid : (uniqueidentifier) Referencing_Count : (int) Repo_default_definition : (nvarchar(max)) Repo_default_is_system_named : (bit) Repo_default_name : (nvarchar(128)) Repo_definition : (nvarchar(max)) - Repo_generated_always_type : (tinyint) Repo_graph_type : (int) Repo_increment_value : (sql_variant) - Repo_is_computed : (bit) - Repo_is_identity : (bit) Repo_is_nullable : (bit) Repo_is_persisted : (bit) Repo_seed_value : (sql_variant) Repo_user_type_fullname : (nvarchar(128)) Repo_user_type_name : (nvarchar(128)) Repo_uses_database_collation : (bit) - RepoObject_guid : (uniqueidentifier) RepoObjectColumn_column_id : (int) - RepoObjectColumn_name : (nvarchar(128)) SysObjectColumn_column_id : (int) - SysObjectColumn_name : (nvarchar(128)) # Column_name : (nvarchar(128)) ~ has_different_sys_names : (bit) # is_RepoObjectColumn_name_uniqueidentifier : (int) # is_SysObjectColumn_name_uniqueidentifier : (int) -- } entity ""puml-link:dhw:sqldb:repo_sys.extendedproperties.adoc[]"" as repo_sys.ExtendedProperties << V >> { - class : (tinyint) class_desc : (nvarchar(60)) entity_column_name : (nvarchar(128)) entity_index_name : (nvarchar(128)) entity_parameter_name : (nvarchar(128)) level2type : (varchar(9)) - major_id : (int) - minor_id : (int) minor_name : (nvarchar(128)) parent_name : (sysname) parent_object_id : (int) parent_type : (char(2)) property_basetype : (sql_variant) - property_name : (sysname) property_nvarchar : (nvarchar(4000)) property_value : (sql_variant) SysObject_name : (nvarchar(128)) SysObject_schema_name : (nvarchar(128)) -- } property.RepoObjectColumnProperty <.. property.RepoObjectColumnProperty_sys_repo property.RepoObjectColumnProperty_sys_repo <.. property.usp_sync_ExtendedProperties_Sys2Repo_InsertUpdate repo.RepoObject <.. property.RepoObjectColumnProperty_sys_repo repo.RepoObjectColumn <.. property.RepoObjectColumnProperty_sys_repo repo_sys.ExtendedProperties <.. property.RepoObjectColumnProperty_sys_repo ""repo.RepoObjectColumn::RepoObjectColumn_guid"" <-- ""property.RepoObjectColumnProperty_sys_repo::RepoObjectColumn_guid"" ""repo_sys.ExtendedProperties::entity_column_name"" <-- ""property.RepoObjectColumnProperty_sys_repo::SysObjectColumn_name"" ""repo_sys.ExtendedProperties::property_name"" <-- ""property.RepoObjectColumnProperty_sys_repo::property_name"" ""repo_sys.ExtendedProperties::property_value"" <-- ""property.RepoObjectColumnProperty_sys_repo::property_value"" ""repo_sys.ExtendedProperties::SysObject_name"" <-- ""property.RepoObjectColumnProperty_sys_repo::SysObject_name"" ""repo_sys.ExtendedProperties::SysObject_schema_name"" <-- ""property.RepoObjectColumnProperty_sys_repo::SysObject_schema_name"" footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- CREATE View property.RepoObjectColumnProperty_sys_repo As -- Select roc.RepoObjectColumn_guid , ses.property_name , ses.property_value , ses.SysObject_schema_name , ses.SysObject_name , SysObjectColumn_name = ses.entity_column_name , link.RepoObjectColumnProperty_id , RepoObjectColumnProperty_property_value = link.property_value From repo_sys.ExtendedProperties As ses Inner Join repo.RepoObject As ro On ses.SysObject_schema_name = ro.SysObject_schema_name And ses.SysObject_name = ro.SysObject_name Inner Join repo.RepoObjectColumn As roc On ro.RepoObject_guid = roc.RepoObject_guid And ses.entity_column_name = roc.SysObjectColumn_name And ses.property_name <> 'RepoObjectColumn_guid' Left Join property.RepoObjectColumnProperty As link On roc.RepoObjectColumn_guid = link.RepoObjectColumn_guid And ses.property_name = link.property_name ---- ======= // end::sql_modules_definition[] ",12497,True,2685.695487291193,median "[[smpp-component]] = SMPP Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-smpp/src/main/docs/smpp-component.adoc :docTitle: SMPP :artifactId: camel-smpp :description: Send and receive SMS messages using a SMSC (Short Message Service Center). :since: 2.2 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/smpp.adoc[opts=optional] *Since Camel {since}* *{component-header}* This component provides access to an SMSC (Short Message Service Center) over the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP] protocol to send and receive SMS. The http://jsmpp.org[JSMPP] library is used for the protocol implementation. The Camel component currently operates as an http://en.wikipedia.org/wiki/ESME[ESME] (External Short Messaging Entity) and not as an SMSC itself. You are also able to execute ReplaceSm, QuerySm, SubmitMulti, CancelSm and DataSm. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-smpp x.x.x ------------------------------------------------------------ == SMS limitations SMS is neither reliable or secure. Users who require reliable and secure delivery may want to consider using the XMPP or SIP components instead, combined with a smartphone app supporting the chosen protocol. * Reliability: although the SMPP standard offers a range of feedback mechanisms to indicate errors, non-delivery and confirmation of delivery it is not uncommon for mobile networks to hide or simulate these responses. For example, some networks automatically send a delivery confirmation for every message even if the destination number is invalid or not switched on. Some networks silently drop messages if they think they are spam. Spam detection rules in the network may be very crude, sometimes more than 100 messages per day from a single sender may be considered spam. * Security: there is basic encryption for the last hop from the radio tower down to the recipient handset. SMS messages are not encrypted or authenticated in any other part of the network. Some operators allow staff in retail outlets or call centres to browse through the SMS message histories of their customers. Message sender identity can be easily forged. Regulators and even the mobile telephone industry itself has cautioned against the use of SMS in two-factor authentication schemes and other purposes where security is important. While the Camel component makes it as easy as possible to send messages to the SMS network, it can not offer an easy solution to these problems. == Data coding, alphabet and international character sets Data coding and alphabet can be specified on a per-message basis. Default values can be specified for the endpoint. It is important to understand the relationship between these options and the way the component acts when more than one value is set. Data coding is an 8 bit field in the SMPP wire format. Alphabet corresponds to bits 0-3 of the data coding field. For some types of message, where a message class is used (by setting bit 5 of the data coding field), the lower two bits of the data coding field are not interpreted as alphabet and only bits 2 and 3 impact the alphabet. Furthermore, current version of the JSMPP library only seems to support bits 2 and 3, assuming that bits 0 and 1 are used for message class. This is why the Alphabet class in JSMPP doesn't support the value 3 (binary 0011) which indicates ISO-8859-1. Although JSMPP provides a representation of the message class parameter, the Camel component doesn't currently provide a way to set it other than manually setting the corresponding bits in the data coding field. When setting the data coding field in the outgoing message, the Camel component considers the following values and uses the first one it can find: * the data coding specified in a header * the alphabet specified in a header * the data coding specified in the endpoint configuration (URI parameter) In addition to trying to send the data coding value to the SMSC, the Camel component also tries to analyze the message body, converts it to a Java String (Unicode) and converts that to a byte array in the corresponding alphabet. When deciding which alphabet to use in the byte array, the Camel SMPP component does not consider the data coding value (header or configuration), it only considers the specified alphabet (from either the header or endpoint parameter). If some characters in the String can not be represented in the chosen alphabet, they may be replaced by the question mark ( ? ) symbol. Users of the API may want to consider checking if their message body can be converted to ISO-8859-1 before passing it to the component and if not, setting the alphabet header to request UCS-2 encoding. If the alphabet and data coding options are not specified at all then the component may try to detect the required encoding and set the data coding for you. The list of alphabet codes are specified in the SMPP specification v3.4, section 5.2.19. One notable limitation of the SMPP specification is that there is no alphabet code for explicitly requesting use of the GSM 3.38 (7 bit) character set. Choosing the value 0 for the alphabet selects the SMSC _default_ alphabet, this usually means GSM 3.38 but it is not guaranteed. The SMPP gateway Nexmo https://help.nexmo.com/hc/en-us/articles/204015813-How-to-change-the-character-encoding-in-SMPP-[actually allows the default to be mapped to any other character set with a control panel option]. It is suggested that users check with their SMSC operator to confirm exactly which character set is being used as the default. == Message splitting and throttling After transforming a message body from a String to a byte array, the Camel component is also responsible for splitting the message into parts (within the 140 byte SMS size limit) before passing it to JSMPP. This is completed automatically. If the GSM 3.38 alphabet is used, the component will pack up to 160 characters into the 140 byte message body. If an 8 bit character set is used (e.g. ISO-8859-1 for western Europe) then 140 characters will be allowed within the 140 byte message body. If 16 bit UCS-2 encoding is used then just 70 characters fit into each 140 byte message. Some SMSC providers implement throttling rules. Each part of a message that has been split may be counted separately by the provider's throttling mechanism. The Camel Throttler component can be useful for throttling messages in the SMPP route before handing them to the SMSC. == URI format -------------------------------------------- smpp://[username@]hostname[:port][?options] smpps://[username@]hostname[:port][?options] -------------------------------------------- If no *username* is provided, then Camel will provide the default value `smppclient`. + If no *port* number is provided, then Camel will provide the default value `2775`. + If the protocol name is ""smpps"", camel-smpp with try to use SSLSocket to init a connection to the server. // component-configure options: START == Configuring Options Camel components are configured on two separate levels: - component level - endpoint level === Configuring Component Options The component level is the highest level which holds general and common configurations that are inherited by the endpoints. For example a component may have security settings, credentials for authentication, urls for network connection and so forth. Some components only have a few options, and others may have many. Because components typically have pre configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all. Configuring components can be done with the xref:latest@manual::component-dsl.adoc[Component DSL], in a configuration file (application.properties|yaml), or directly with Java code. === Configuring Endpoint Options Where you find yourself configuring the most is on endpoints, as endpoints often have many options, which allows you to configure what you need the endpoint to do. The options are also categorized into whether the endpoint is used as consumer (from) or as a producer (to), or used for both. Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the xref:latest@manual::Endpoint-dsl.adoc[Endpoint DSL] as a _type safe_ way of configuring endpoints. A good practice when configuring options is to use xref:latest@manual::using-propertyplaceholder.adoc[Property Placeholders], which allows to not hardcode urls, port numbers, sensitive information, and other settings. In other words placeholders allows to externalize the configuration from your code, and gives more flexibility and reuse. The following two sections lists all the options, firstly for the component followed by the endpoint. // component-configure options: END // component options: START == Component Options The SMPP component supports 41 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *initialReconnectDelay* (common) | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | long | *maxReconnect* (common) | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | int | *reconnectDelay* (common) | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | long | *splittingPolicy* (common) | You can specify a policy for handling long messages: ALLOW - the default, long messages are split to 140 bytes per message TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered. REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long. There are 3 enums and the value can be one of: ALLOW, REJECT, TRUNCATE | ALLOW | SmppSplittingPolicy | *systemType* (common) | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *addressRange* (consumer) | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *destAddr* (producer) | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *destAddrNpi* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum). There are 10 enums and the value can be one of: 0, 1, 2, 3, 6, 8, 9, 10, 13, 18 | | byte | *destAddrTon* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated. There are 7 enums and the value can be one of: 0, 1, 2, 3, 4, 5, 6 | | byte | *lazySessionCreation* (producer) | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *numberingPlanIndicator* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum). There are 10 enums and the value can be one of: 0, 1, 2, 3, 6, 8, 9, 10, 13, 18 | | byte | *priorityFlag* (producer) | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level 2 priority 3: Level 3 (highest) priority. There are 4 enums and the value can be one of: 0, 1, 2, 3 | | byte | *protocolId* (producer) | The protocol id | | byte | *registeredDelivery* (producer) | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined: 0: No SMSC delivery receipt requested. 1: SMSC delivery receipt requested where final delivery outcome is success or failure. 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure. There are 3 enums and the value can be one of: 0, 1, 2 | | byte | *replaceIfPresentFlag* (producer) | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined: 0: Don't replace 1: Replace. There are 2 enums and the value can be one of: 0, 1 | | byte | *serviceType* (producer) | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined: CMT: Cellular Messaging CPT: Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting WAP: Wireless Application Protocol USSD: Unstructured Supplementary Services Data. There are 6 enums and the value can be one of: CMT, CPT, VMN, VMA, WAP, USSD | | String | *sourceAddr* (producer) | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *sourceAddrNpi* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum). There are 10 enums and the value can be one of: 0, 1, 2, 3, 6, 8, 9, 10, 13, 18 | | byte | *sourceAddrTon* (producer) | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated. There are 7 enums and the value can be one of: 0, 1, 2, 3, 4, 5, 6 | | byte | *typeOfNumber* (producer) | Defines the type of number (TON) to be used in the SME. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated. There are 7 enums and the value can be one of: 0, 1, 2, 3, 4, 5, 6 | | byte | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *configuration* (advanced) | To use the shared SmppConfiguration as configuration. | | SmppConfiguration | *enquireLinkTimer* (advanced) | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 60000 | Integer | *pduProcessorDegree* (advanced) | Sets the number of threads which can read PDU and process them in parallel. | 3 | Integer | *pduProcessorQueueCapacity* (advanced) | Sets the capacity of the working queue for PDU processing. | 100 | Integer | *sessionStateListener* (advanced) | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *singleDLR* (advanced) | When true, the SMSC delivery receipt would be requested only for the last segment of a multi-segment (long) message. For short messages, with only 1 segment the behaviour is unchanged. | false | boolean | *transactionTimer* (advanced) | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *alphabet* (codec) | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19. 0: SMSC Default Alphabet 4: 8 bit Alphabet 8: UCS2 Alphabet. There are 3 enums and the value can be one of: 0, 4, 8 | | byte | *dataCoding* (codec) | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are: 0: SMSC Default Alphabet 3: Latin 1 (ISO-8859-1) 4: Octet unspecified (8-bit binary) 8: UCS2 (ISO/IEC-10646) 13: Extended Kanji JIS(X 0212-1990) | | byte | *encoding* (codec) | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *httpProxyHost* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *httpProxyPassword* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *httpProxyPort* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *httpProxyUsername* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *proxyHeaders* (proxy) | These headers will be passed to the proxy server while establishing the connection. | | Map | *password* (security) | The password for connecting to SMSC server. | | String | *systemId* (security) | The system id (username) for connecting to SMSC server. | smppclient | String | *usingSSL* (security) | Whether using SSL with the smpps protocol | false | boolean |=== // component options: END // endpoint options: START == Endpoint Options The SMPP endpoint is configured using URI syntax: ---- smpp:host:port ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *host* | Hostname for the SMSC server to use. | localhost | String | *port* | Port number for the SMSC server to use. | 2775 | Integer |=== === Query Parameters (41 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *initialReconnectDelay* (common) | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | long | *maxReconnect* (common) | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | int | *reconnectDelay* (common) | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | long | *splittingPolicy* (common) | You can specify a policy for handling long messages: ALLOW - the default, long messages are split to 140 bytes per message TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered. REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long. There are 3 enums and the value can be one of: ALLOW, REJECT, TRUNCATE | ALLOW | SmppSplittingPolicy | *systemType* (common) | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *addressRange* (consumer) | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *destAddr* (producer) | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *destAddrNpi* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum). There are 10 enums and the value can be one of: 0, 1, 2, 3, 6, 8, 9, 10, 13, 18 | | byte | *destAddrTon* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated. There are 7 enums and the value can be one of: 0, 1, 2, 3, 4, 5, 6 | | byte | *lazySessionCreation* (producer) | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *numberingPlanIndicator* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum). There are 10 enums and the value can be one of: 0, 1, 2, 3, 6, 8, 9, 10, 13, 18 | | byte | *priorityFlag* (producer) | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level 2 priority 3: Level 3 (highest) priority. There are 4 enums and the value can be one of: 0, 1, 2, 3 | | byte | *protocolId* (producer) | The protocol id | | byte | *registeredDelivery* (producer) | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined: 0: No SMSC delivery receipt requested. 1: SMSC delivery receipt requested where final delivery outcome is success or failure. 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure. There are 3 enums and the value can be one of: 0, 1, 2 | | byte | *replaceIfPresentFlag* (producer) | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined: 0: Don't replace 1: Replace. There are 2 enums and the value can be one of: 0, 1 | | byte | *serviceType* (producer) | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined: CMT: Cellular Messaging CPT: Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting WAP: Wireless Application Protocol USSD: Unstructured Supplementary Services Data. There are 6 enums and the value can be one of: CMT, CPT, VMN, VMA, WAP, USSD | | String | *sourceAddr* (producer) | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *sourceAddrNpi* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum). There are 10 enums and the value can be one of: 0, 1, 2, 3, 6, 8, 9, 10, 13, 18 | | byte | *sourceAddrTon* (producer) | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated. There are 7 enums and the value can be one of: 0, 1, 2, 3, 4, 5, 6 | | byte | *typeOfNumber* (producer) | Defines the type of number (TON) to be used in the SME. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated. There are 7 enums and the value can be one of: 0, 1, 2, 3, 4, 5, 6 | | byte | *enquireLinkTimer* (advanced) | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 60000 | Integer | *pduProcessorDegree* (advanced) | Sets the number of threads which can read PDU and process them in parallel. | 3 | Integer | *pduProcessorQueueCapacity* (advanced) | Sets the capacity of the working queue for PDU processing. | 100 | Integer | *sessionStateListener* (advanced) | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *singleDLR* (advanced) | When true, the SMSC delivery receipt would be requested only for the last segment of a multi-segment (long) message. For short messages, with only 1 segment the behaviour is unchanged. | false | boolean | *transactionTimer* (advanced) | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *alphabet* (codec) | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19. 0: SMSC Default Alphabet 4: 8 bit Alphabet 8: UCS2 Alphabet. There are 3 enums and the value can be one of: 0, 4, 8 | | byte | *dataCoding* (codec) | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are: 0: SMSC Default Alphabet 3: Latin 1 (ISO-8859-1) 4: Octet unspecified (8-bit binary) 8: UCS2 (ISO/IEC-10646) 13: Extended Kanji JIS(X 0212-1990) | | byte | *encoding* (codec) | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *httpProxyHost* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *httpProxyPassword* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *httpProxyPort* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *httpProxyUsername* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *proxyHeaders* (proxy) | These headers will be passed to the proxy server while establishing the connection. | | Map | *password* (security) | The password for connecting to SMSC server. | | String | *systemId* (security) | The system id (username) for connecting to SMSC server. | smppclient | String | *usingSSL* (security) | Whether using SSL with the smpps protocol | false | boolean |=== // endpoint options: END == Producer Message Headers The following message headers can be used to affect the behavior of the SMPP producer [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppDestAddr` |`List`/`String` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the destination SME address(es). For mobile terminated messages, this is the directory number of the recipient MS. It must be a `List` for SubmitMulti and a `String` otherwise. |`CamelSmppDestAddrTon` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the type of number (TON) to be used in the SME destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppDestAddrNpi` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddr` |`String` |Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrTon` |`Byte` |Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppSourceAddrNpi` |`Byte` |Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppServiceType` |`String` |The service type parameter can be used to indicate the SMS Application service associated with the message. Use the URI option `serviceType` settings above. |`CamelSmppRegisteredDelivery` |`Byte` |*only for SubmitSm, ReplaceSm, SubmitMulti and DataSm* Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. Use the URI option `registeredDelivery` settings above. |`CamelSmppSingleDLR` | `Boolean` | *only for SubmitSm, SubmitMulti* Is used to request the SMSC delivery receipt only on the last segment of multi-segment (long) messages. Use the URI option `singleDLR` settings above. |`CamelSmppPriorityFlag` |`Byte` |*only for SubmitSm and SubmitMulti* Allows the originating SME to assign a priority level to the short message. Use the URI option `priorityFlag` settings above. |`CamelSmppScheduleDeliveryTime` |`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in chapter 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String`/`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. If it's provided as `Date`, it's interpreted as absolute time or relative time format if you provide it as `String` as specified in chapter 7.1.1 in the smpp specification v3.4. |`CamelSmppReplaceIfPresentFlag` |`Byte` |*only for SubmitSm and SubmitMulti* The replace if present flag parameter is used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following values are defined: `0`, Don't replace and `1`, Replace |`CamelSmppAlphabet` / `CamelSmppDataCoding` |`Byte` |*For SubmitSm, SubmitMulti and ReplaceSm* The data coding according to the SMPP 3.4 specification, section 5.2.19. Use the URI option `alphabet` settings above. |`CamelSmppOptionalParameter` |`Map` |*only for SubmitSm, SubmitMulti and DataSm* The optional parameter which are send to the SMSC. The value is converted in the following way: `String` -> `org.jsmpp.bean.OptionalParameter.COctetString`, `byte[]` -> `org.jsmpp.bean.OptionalParameter.OctetString`, `Byte` -> `org.jsmpp.bean.OptionalParameter.Byte`, `Integer` -> `org.jsmpp.bean.OptionalParameter.Int`, `Short` -> `org.jsmpp.bean.OptionalParameter.Short`, `null` -> `org.jsmpp.bean.OptionalParameter.Null` |CamelSmppEncoding |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the encoding (character set name) of the bytes in the message body. If the message body is a string then this is not relevant because Java Strings are always Unicode. If the body is a byte array then this header can be used to indicate that it is ISO-8859-1 or some other value. Default value is specified by the endpoint configuration parameter _encoding_ |CamelSmppSplittingPolicy |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the policy for message splitting for this exchange. Possible values are described in the endpoint configuration parameter _splittingPolicy_ |======================================================================= The following message headers are used by the SMPP producer to set the response from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppId` |`List`/`String` |The id to identify the submitted short message(s) for later use. In case of a ReplaceSm, QuerySm, CancelSm and DataSm this header vaule is a `String`. In case of a SubmitSm or SubmitMultiSm this header vaule is a `List`. |`CamelSmppSentMessageCount` |`Integer` |*only for SubmitSm and SubmitMultiSm* The total number of messages which has been sent. |`CamelSmppError` |`Map>>` |*only for SubmitMultiSm* The errors which occurred by sending the short message(s) the form `Map>>` (messageID : (destAddr : address, error : errorCode)). |`CamelSmppOptionalParameter` |`Map` |*only for DataSm* The optional parameter which are returned from the SMSC by sending the message. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= == Consumer Message Headers The following message headers are used by the SMPP consumer to set the request data from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppSequenceNumber` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* A sequence number allows a response PDU to be correlated with a request PDU. The associated SMPP response PDU must preserve this field. |`CamelSmppCommandId` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* The command id field identifies the particular SMPP PDU. For the complete list of defined values see chapter 5.1.2.1 in the smpp specification v3.4. |`CamelSmppSourceAddr` |`String` |*only for AlertNotification, DeliverSm and DataSm* Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrNpi` |`Byte` |*only for AlertNotification and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddrTon` |`Byte` |*only for AlertNotification and DataSm* Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppEsmeAddr` |`String` |*only for AlertNotification* Defines the destination ESME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppEsmeAddrNpi` |`Byte` |*only for AlertNotification* Defines the numeric plan indicator (NPI) to be used in the ESME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppEsmeAddrTon` |`Byte` |*only for AlertNotification* Defines the type of number (TON) to be used in the ESME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppId` |`String` |*only for smsc DeliveryReceipt and DataSm* The message ID allocated to the message by the SMSC when originally submitted. |`CamelSmppDelivered` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages delivered. This is only relevant where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDoneDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message reached it's final state. The format is as follows: YYMMDDhhmm. |`CamelSmppStatus` |`DeliveryReceiptState` |*only for smsc DeliveryReceipt:* The final status of the message. The following values are defined: `DELIVRD`: Message is delivered to destination, `EXPIRED`: Message validity period has expired, `DELETED`: Message has been deleted, `UNDELIV`: Message is undeliverable, `ACCEPTD`: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service), `UNKNOWN`: Message is in invalid state, `REJECTD`: Message is in a rejected state |`CamelSmppCommandStatus` |`Integer` |*only for DataSm* The Command status of the message. |`CamelSmppError` |`String` |*only for smsc DeliveryReceipt* Where appropriate this may hold a Network specific error code or an SMSC error code for the attempted delivery of the message. These errors are Network or SMSC specific and are not included here. |`CamelSmppSubmitDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message was submitted. In the case of a message which has been replaced, this is the date that the original message was replaced. The format is as follows: YYMMDDhhmm. |`CamelSmppSubmitted` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages originally submitted. This is only relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDestAddr` |`String` |*only for DeliverSm and DataSm:* Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppScheduleDeliveryTime` |`String` |*only for DeliverSm:* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in Section 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String` |*only for DeliverSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. It can be defined in absolute time format or relative time format. The encoding of absolute and relative time format is specified in Section 7.1.1 in the smpp specification v3.4. |`CamelSmppServiceType` |`String` |*only for DeliverSm and DataSm* The service type parameter indicates the SMS Application service associated with the message. |`CamelSmppRegisteredDelivery` |`Byte` |*only for DataSm* Is used to request an delivery receipt and/or SME originated acknowledgements. Same values as in Producer header list above. |`CamelSmppDestAddrNpi` |`Byte` |*only for DataSm* Defines the numeric plan indicator (NPI) in the destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppDestAddrTon` |`Byte` |*only for DataSm* Defines the type of number (TON) in the destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppMessageType` |`String` |Identifies the type of an incoming message: `AlertNotification`: an SMSC alert notification, `DataSm`: an SMSC data short message, `DeliveryReceipt`: an SMSC delivery receipt, `DeliverSm`: an SMSC deliver short message |`CamelSmppOptionalParameter` |`Map` |*only for DeliverSm* The optional parameters send back by the SMSC. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= [TIP] ==== *JSMPP library* See the documentation of the http://jsmpp.org[JSMPP Library] for more details about the underlying library. ==== == Exception handling This component supports the general Camel exception handling capabilities When an error occurs sending a message with SubmitSm (the default action), the org.apache.camel.component.smpp.SmppException is thrown with a nested exception, org.jsmpp.extra.NegativeResponseException. Call NegativeResponseException.getCommandStatus() to obtain the exact SMPP negative response code, the values are explained in the SMPP specification 3.4, section 5.1.3. + When the SMPP consumer receives a `DeliverSm` or `DataSm` short message and the processing of these messages fails, you can also throw a `ProcessRequestException` instead of handle the failure. In this case, this exception is forwarded to the underlying http://jsmpp.org[JSMPP library] which will return the included error code to the SMSC. This feature is useful to e.g. instruct the SMSC to resend the short message at a later time. This could be done with the following lines of code: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .doTry() .to(""bean:dao?method=updateSmsState"") .doCatch(Exception.class) .throwException(new ProcessRequestException(""update of sms state failed"", 100)) .end(); -------------------------------------------------------------------------------------------------------------------------- Please refer to the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP specification] for the complete list of error codes and their meanings. == Samples A route which sends an SMS using the Java DSL: [source,java] ------------------------------------------------------------------------------------------ from(""direct:start"") .to(""smpp://smppclient@localhost:2775? password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=producer""); ------------------------------------------------------------------------------------------ A route which sends an SMS using the Spring XML DSL: [source,xml] ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Java DSL: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Spring XML DSL: [source,xml] ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- [TIP] ==== *SMSC simulator* If you need an SMSC simulator for your test, you can use the simulator provided by http://opensmpp.logica.com/CommonPart/Download/download2.html#simulator[Logica]. ==== == Debug logging This component has log level *DEBUG*, which can be helpful in debugging problems. If you use log4j, you can add the following line to your configuration: [source,properties] -------------------------------------------------- log4j.logger.org.apache.camel.component.smpp=DEBUG -------------------------------------------------- include::{page-component-version}@camel-spring-boot::page$smpp-starter.adoc[] ",12476,False,2415.646099595508,median " //// This file is generated! See _meta/fields.yml and scripts/generate_field_docs.py //// [[exported-fields]] = Exported fields [partintro] -- This document describes the fields that are exported by Packetbeat. They are grouped in the following categories: * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> -- [[exported-fields-amqp]] == AMQP fields AMQP specific event fields. [float] === `amqp.reply-code` type: long example: 404 AMQP reply code to an error, similar to http reply-code [float] === `amqp.reply-text` type: keyword Text explaining the error. [float] === `amqp.class-id` type: long Failing method class. [float] === `amqp.method-id` type: long Failing method ID. [float] === `amqp.exchange` type: keyword Name of the exchange. [float] === `amqp.exchange-type` type: keyword example: fanout Exchange type. [float] === `amqp.passive` type: boolean If set, do not create exchange/queue. [float] === `amqp.durable` type: boolean If set, request a durable exchange/queue. [float] === `amqp.exclusive` type: boolean If set, request an exclusive queue. [float] === `amqp.auto-delete` type: boolean If set, auto-delete queue when unused. [float] === `amqp.no-wait` type: boolean If set, the server will not respond to the method. [float] === `amqp.consumer-tag` Identifier for the consumer, valid within the current channel. [float] === `amqp.delivery-tag` type: long The server-assigned and channel-specific delivery tag. [float] === `amqp.message-count` type: long The number of messages in the queue, which will be zero for newly-declared queues. [float] === `amqp.consumer-count` type: long The number of consumers of a queue. [float] === `amqp.routing-key` type: keyword Message routing key. [float] === `amqp.no-ack` type: boolean If set, the server does not expect acknowledgements for messages. [float] === `amqp.no-local` type: boolean If set, the server will not send messages to the connection that published them. [float] === `amqp.if-unused` type: boolean Delete only if unused. [float] === `amqp.if-empty` type: boolean Delete only if empty. [float] === `amqp.queue` type: keyword The queue name identifies the queue within the vhost. [float] === `amqp.redelivered` type: boolean Indicates that the message has been previously delivered to this or another client. [float] === `amqp.multiple` type: boolean Acknowledge multiple messages. [float] === `amqp.arguments` type: object Optional additional arguments passed to some methods. Can be of various types. [float] === `amqp.mandatory` type: boolean Indicates mandatory routing. [float] === `amqp.immediate` type: boolean Request immediate delivery. [float] === `amqp.content-type` type: keyword example: text/plain MIME content type. [float] === `amqp.content-encoding` type: keyword MIME content encoding. [float] === `amqp.headers` type: object Message header field table. [float] === `amqp.delivery-mode` type: keyword Non-persistent (1) or persistent (2). [float] === `amqp.priority` type: long Message priority, 0 to 9. [float] === `amqp.correlation-id` type: keyword Application correlation identifier. [float] === `amqp.reply-to` type: keyword Address to reply to. [float] === `amqp.expiration` type: keyword Message expiration specification. [float] === `amqp.message-id` type: keyword Application message identifier. [float] === `amqp.timestamp` type: keyword Message timestamp. [float] === `amqp.type` type: keyword Message type name. [float] === `amqp.user-id` type: keyword Creating user id. [float] === `amqp.app-id` type: keyword Creating application id. [[exported-fields-beat]] == Beat fields Contains common beat fields available in all event types. [float] === `beat.name` The name of the Beat sending the log messages. If the Beat name is set in the configuration file, then that value is used. If it is not set, the hostname is used. To set the Beat name, use the `name` option in the configuration file. [float] === `beat.hostname` The hostname as returned by the operating system on which the Beat is running. [float] === `beat.timezone` The timezone as returned by the operating system on which the Beat is running. [float] === `beat.version` The version of the beat that generated this event. [float] === `@timestamp` type: date example: August 26th 2016, 12:35:53.332 format: date required: True The timestamp when the event log record was generated. [float] === `tags` Arbitrary tags that can be set per Beat and per transaction type. [float] === `fields` type: object Contains user configurable fields. [float] == error fields Error fields containing additional info in case of errors. [float] === `error.message` type: text Error message. [float] === `error.code` type: long Error code. [float] === `error.type` type: keyword Error type. [[exported-fields-cassandra]] == Cassandra fields Cassandra v4/3 specific event fields. [float] == cassandra fields Information about the Cassandra request and response. [float] == request fields Cassandra request. [float] == headers fields Cassandra request headers. [float] === `cassandra.request.headers.version` type: long The version of the protocol. [float] === `cassandra.request.headers.flags` type: keyword Flags applying to this frame. [float] === `cassandra.request.headers.stream` type: keyword A frame has a stream id. If a client sends a request message with the stream id X, it is guaranteed that the stream id of the response to that message will be X. [float] === `cassandra.request.headers.op` type: keyword An operation type that distinguishes the actual message. [float] === `cassandra.request.headers.length` type: long A integer representing the length of the body of the frame (a frame is limited to 256MB in length). [float] === `cassandra.request.query` type: keyword The CQL query which client send to cassandra. [float] == response fields Cassandra response. [float] == headers fields Cassandra response headers, the structure is as same as request's header. [float] === `cassandra.response.headers.version` type: long The version of the protocol. [float] === `cassandra.response.headers.flags` type: keyword Flags applying to this frame. [float] === `cassandra.response.headers.stream` type: keyword A frame has a stream id. If a client sends a request message with the stream id X, it is guaranteed that the stream id of the response to that message will be X. [float] === `cassandra.response.headers.op` type: keyword An operation type that distinguishes the actual message. [float] === `cassandra.response.headers.length` type: long A integer representing the length of the body of the frame (a frame is limited to 256MB in length). [float] == result fields Details about the returned result. [float] === `cassandra.response.result.type` type: keyword Cassandra result type. [float] == rows fields Details about the rows. [float] === `cassandra.response.result.rows.num_rows` type: long Representing the number of rows present in this result. [float] == meta fields Composed of result metadata. [float] === `cassandra.response.result.rows.meta.keyspace` type: keyword Only present after set Global_tables_spec, the keyspace name. [float] === `cassandra.response.result.rows.meta.table` type: keyword Only present after set Global_tables_spec, the table name. [float] === `cassandra.response.result.rows.meta.flags` type: keyword Provides information on the formatting of the remaining information. [float] === `cassandra.response.result.rows.meta.col_count` type: long Representing the number of columns selected by the query that produced this result. [float] === `cassandra.response.result.rows.meta.pkey_columns` type: long Representing the PK columns index and counts. [float] === `cassandra.response.result.rows.meta.paging_state` type: keyword The paging_state is a bytes value that should be used in QUERY/EXECUTE to continue paging and retrieve the remainder of the result for this query. [float] === `cassandra.response.result.keyspace` type: keyword Indicating the name of the keyspace that has been set. [float] == schema_change fields The result to a schema_change message. [float] === `cassandra.response.result.schema_change.change` type: keyword Representing the type of changed involved. [float] === `cassandra.response.result.schema_change.keyspace` type: keyword This describes which keyspace has changed. [float] === `cassandra.response.result.schema_change.table` type: keyword This describes which table has changed. [float] === `cassandra.response.result.schema_change.object` type: keyword This describes the name of said affected object (either the table, user type, function, or aggregate name). [float] === `cassandra.response.result.schema_change.target` type: keyword Target could be ""FUNCTION"" or ""AGGREGATE"", multiple arguments. [float] === `cassandra.response.result.schema_change.name` type: keyword The function/aggregate name. [float] === `cassandra.response.result.schema_change.args` type: keyword One string for each argument type (as CQL type). [float] == prepared fields The result to a PREPARE message. [float] === `cassandra.response.result.prepared.prepared_id` type: keyword Representing the prepared query ID. [float] == req_meta fields This describes the request metadata. [float] === `cassandra.response.result.prepared.req_meta.keyspace` type: keyword Only present after set Global_tables_spec, the keyspace name. [float] === `cassandra.response.result.prepared.req_meta.table` type: keyword Only present after set Global_tables_spec, the table name. [float] === `cassandra.response.result.prepared.req_meta.flags` type: keyword Provides information on the formatting of the remaining information. [float] === `cassandra.response.result.prepared.req_meta.col_count` type: long Representing the number of columns selected by the query that produced this result. [float] === `cassandra.response.result.prepared.req_meta.pkey_columns` type: long Representing the PK columns index and counts. [float] === `cassandra.response.result.prepared.req_meta.paging_state` type: keyword The paging_state is a bytes value that should be used in QUERY/EXECUTE to continue paging and retrieve the remainder of the result for this query. [float] == resp_meta fields This describes the metadata for the result set. [float] === `cassandra.response.result.prepared.resp_meta.keyspace` type: keyword Only present after set Global_tables_spec, the keyspace name. [float] === `cassandra.response.result.prepared.resp_meta.table` type: keyword Only present after set Global_tables_spec, the table name. [float] === `cassandra.response.result.prepared.resp_meta.flags` type: keyword Provides information on the formatting of the remaining information. [float] === `cassandra.response.result.prepared.resp_meta.col_count` type: long Representing the number of columns selected by the query that produced this result. [float] === `cassandra.response.result.prepared.resp_meta.pkey_columns` type: long Representing the PK columns index and counts. [float] === `cassandra.response.result.prepared.resp_meta.paging_state` type: keyword The paging_state is a bytes value that should be used in QUERY/EXECUTE to continue paging and retrieve the remainder of the result for this query. [float] === `cassandra.response.supported` type: object Indicates which startup options are supported by the server. This message comes as a response to an OPTIONS message. [float] == authentication fields Indicates that the server requires authentication, and which authentication mechanism to use. [float] === `cassandra.response.authentication.class` type: keyword Indicates the full class name of the IAuthenticator in use [float] === `cassandra.response.warnings` type: keyword The text of the warnings, only occur when Warning flag was set. [float] == event fields Event pushed by the server. A client will only receive events for the types it has REGISTERed to. [float] === `cassandra.response.event.type` type: keyword Representing the event type. [float] === `cassandra.response.event.change` type: keyword The message corresponding respectively to the type of change followed by the address of the new/removed node. [float] === `cassandra.response.event.host` type: keyword Representing the node ip. [float] === `cassandra.response.event.port` type: long Representing the node port. [float] == schema_change fields The events details related to schema change. [float] === `cassandra.response.event.schema_change.change` type: keyword Representing the type of changed involved. [float] === `cassandra.response.event.schema_change.keyspace` type: keyword This describes which keyspace has changed. [float] === `cassandra.response.event.schema_change.table` type: keyword This describes which table has changed. [float] === `cassandra.response.event.schema_change.object` type: keyword This describes the name of said affected object (either the table, user type, function, or aggregate name). [float] === `cassandra.response.event.schema_change.target` type: keyword Target could be ""FUNCTION"" or ""AGGREGATE"", multiple arguments. [float] === `cassandra.response.event.schema_change.name` type: keyword The function/aggregate name. [float] === `cassandra.response.event.schema_change.args` type: keyword One string for each argument type (as CQL type). [float] == error fields Indicates an error processing a request. The body of the message will be an error code followed by a error message. Then, depending on the exception, more content may follow. [float] === `cassandra.response.error.code` type: long The error code of the Cassandra response. [float] === `cassandra.response.error.msg` type: keyword The error message of the Cassandra response. [float] === `cassandra.response.error.type` type: keyword The error type of the Cassandra response. [float] == details fields The details of the error. [float] === `cassandra.response.error.details.read_consistency` type: keyword Representing the consistency level of the query that triggered the exception. [float] === `cassandra.response.error.details.required` type: long Representing the number of nodes that should be alive to respect consistency level. [float] === `cassandra.response.error.details.alive` type: long Representing the number of replicas that were known to be alive when the request had been processed (since an unavailable exception has been triggered). [float] === `cassandra.response.error.details.received` type: long Representing the number of nodes having acknowledged the request. [float] === `cassandra.response.error.details.blockfor` type: long Representing the number of replicas whose acknowledgement is required to achieve consistency level. [float] === `cassandra.response.error.details.write_type` type: keyword Describe the type of the write that timed out. [float] === `cassandra.response.error.details.data_present` type: boolean It means the replica that was asked for data had responded. [float] === `cassandra.response.error.details.keyspace` type: keyword The keyspace of the failed function. [float] === `cassandra.response.error.details.table` type: keyword The keyspace of the failed function. [float] === `cassandra.response.error.details.stmt_id` type: keyword Representing the unknown ID. [float] === `cassandra.response.error.details.num_failures` type: keyword Representing the number of nodes that experience a failure while executing the request. [float] === `cassandra.response.error.details.function` type: keyword The name of the failed function. [float] === `cassandra.response.error.details.arg_types` type: keyword One string for each argument type (as CQL type) of the failed function. [[exported-fields-cloud]] == Cloud provider metadata fields Metadata from cloud providers added by the add_cloud_metadata processor. [float] === `meta.cloud.provider` example: ec2 Name of the cloud provider. Possible values are ec2, gce, or digitalocean. [float] === `meta.cloud.instance_id` Instance ID of the host machine. [float] === `meta.cloud.instance_name` Instance name of the host machine. [float] === `meta.cloud.machine_type` example: t2.medium Machine type of the host machine. [float] === `meta.cloud.availability_zone` example: us-east-1c Availability zone in which this host is running. [float] === `meta.cloud.project_id` example: project-x Name of the project in Google Cloud. [float] === `meta.cloud.region` Region in which this host is running. [[exported-fields-common]] == Common fields These fields contain data about the environment in which the transaction or flow was captured. [float] === `server` The name of the server that served the transaction. [float] === `client_server` The name of the server that initiated the transaction. [float] === `service` The name of the logical service that served the transaction. [float] === `client_service` The name of the logical service that initiated the transaction. [float] === `ip` format: dotted notation. The IP address of the server that served the transaction. [float] === `client_ip` format: dotted notation. The IP address of the server that initiated the transaction. [float] === `real_ip` format: Dotted notation. If the server initiating the transaction is a proxy, this field contains the original client IP address. For HTTP, for example, the IP address extracted from a configurable HTTP header, by default `X-Forwarded-For`. Unless this field is disabled, it always has a value, and it matches the `client_ip` for non proxy clients. [float] == client_geoip fields The GeoIP information of the client. [float] === `client_geoip.location` type: geo_point example: {'lat': 51, 'lon': 9} The GeoIP location of the `client_ip` address. This field is available only if you define a https://www.elastic.co/guide/en/elasticsearch/plugins/master/using-ingest-geoip.html[GeoIP Processor] as a pipeline in the https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest-geoip.html[Ingest GeoIP processor plugin] or using Logstash. [float] === `client_port` format: dotted notation. The layer 4 port of the process that initiated the transaction. [float] === `transport` example: udp The transport protocol used for the transaction. If not specified, then tcp is assumed. [float] === `type` required: True The type of the transaction (for example, HTTP, MySQL, Redis, or RUM) or ""flow"" in case of flows. [float] === `port` format: dotted notation. The layer 4 port of the process that served the transaction. [float] === `proc` The name of the process that served the transaction. [float] === `client_proc` The name of the process that initiated the transaction. [float] === `release` The software release of the service serving the transaction. This can be the commit id or a semantic version. [[exported-fields-dns]] == DNS fields DNS-specific event fields. [float] === `dns.id` type: long The DNS packet identifier assigned by the program that generated the query. The identifier is copied to the response. [float] === `dns.op_code` example: QUERY The DNS operation code that specifies the kind of query in the message. This value is set by the originator of a query and copied into the response. [float] === `dns.flags.authoritative` type: boolean A DNS flag specifying that the responding server is an authority for the domain name used in the question. [float] === `dns.flags.recursion_available` type: boolean A DNS flag specifying whether recursive query support is available in the name server. [float] === `dns.flags.recursion_desired` type: boolean A DNS flag specifying that the client directs the server to pursue a query recursively. Recursive query support is optional. [float] === `dns.flags.authentic_data` type: boolean A DNS flag specifying that the recursive server considers the response authentic. [float] === `dns.flags.checking_disabled` type: boolean A DNS flag specifying that the client disables the server signature validation of the query. [float] === `dns.flags.truncated_response` type: boolean A DNS flag specifying that only the first 512 bytes of the reply were returned. [float] === `dns.response_code` example: NOERROR The DNS status code. [float] === `dns.question.name` example: www.google.com. The domain name being queried. If the name field contains non-printable characters (below 32 or above 126), then those characters are represented as escaped base 10 integers (\\DDD). Back slashes and quotes are escaped. Tabs, carriage returns, and line feeds are converted to \\t, \\r, and \\n respectively. [float] === `dns.question.type` example: AAAA The type of records being queried. [float] === `dns.question.class` example: IN The class of of records being queried. [float] === `dns.question.etld_plus_one` example: amazon.co.uk. The effective top-level domain (eTLD) plus one more label. For example, the eTLD+1 for ""foo.bar.golang.org."" is ""golang.org."". The data for determining the eTLD comes from an embedded copy of the data from http://publicsuffix.org. [float] === `dns.answers` type: object An array containing a dictionary about each answer section returned by the server. [float] === `dns.answers_count` type: long The number of resource records contained in the `dns.answers` field. [float] === `dns.answers.name` example: example.com. The domain name to which this resource record pertains. [float] === `dns.answers.type` example: MX The type of data contained in this resource record. [float] === `dns.answers.class` example: IN The class of DNS data contained in this resource record. [float] === `dns.answers.ttl` type: long The time interval in seconds that this resource record may be cached before it should be discarded. Zero values mean that the data should not be cached. [float] === `dns.answers.data` The data describing the resource. The meaning of this data depends on the type and class of the resource record. [float] === `dns.authorities` type: object An array containing a dictionary for each authority section from the answer. [float] === `dns.authorities_count` type: long The number of resource records contained in the `dns.authorities` field. The `dns.authorities` field may or may not be included depending on the configuration of Packetbeat. [float] === `dns.authorities.name` example: example.com. The domain name to which this resource record pertains. [float] === `dns.authorities.type` example: NS The type of data contained in this resource record. [float] === `dns.authorities.class` example: IN The class of DNS data contained in this resource record. [float] === `dns.additionals` type: object An array containing a dictionary for each additional section from the answer. [float] === `dns.additionals_count` type: long The number of resource records contained in the `dns.additionals` field. The `dns.additionals` field may or may not be included depending on the configuration of Packetbeat. [float] === `dns.additionals.name` example: example.com. The domain name to which this resource record pertains. [float] === `dns.additionals.type` example: NS The type of data contained in this resource record. [float] === `dns.additionals.class` example: IN The class of DNS data contained in this resource record. [float] === `dns.additionals.ttl` type: long The time interval in seconds that this resource record may be cached before it should be discarded. Zero values mean that the data should not be cached. [float] === `dns.additionals.data` The data describing the resource. The meaning of this data depends on the type and class of the resource record. [float] === `dns.opt.version` example: 0 The EDNS version. [float] === `dns.opt.do` type: boolean If set, the transaction uses DNSSEC. [float] === `dns.opt.ext_rcode` example: BADVERS Extended response code field. [float] === `dns.opt.udp_size` type: long Requestor's UDP payload size (in bytes). [[exported-fields-docker-processor]] == Docker fields beta[] Docker stats collected from Docker. [float] === `docker.container.id` type: keyword Unique container id. [float] === `docker.container.image` type: keyword Name of the image the container was built on. [float] === `docker.container.name` type: keyword Container name. [float] === `docker.container.labels` type: object Image labels. [[exported-fields-flows_event]] == Flow Event fields These fields contain data about the flow itself. [float] === `start_time` type: date example: 2015-01-24 14:06:05.071000 format: YYYY-MM-DDTHH:MM:SS.milliZ required: True The time, the first packet for the flow has been seen. [float] === `last_time` type: date example: 2015-01-24 14:06:05.071000 format: YYYY-MM-DDTHH:MM:SS.milliZ required: True The time, the most recent processed packet for the flow has been seen. [float] === `final` Indicates if event is last event in flow. If final is false, the event reports an intermediate flow state only. [float] === `flow_id` Internal flow id based on connection meta data and address. [float] === `vlan` Innermost VLAN address used in network packets. [float] === `outer_vlan` Second innermost VLAN address used in network packets. [float] == source fields Properties of the source host [float] === `source.mac` Source MAC address as indicated by first packet seen for the current flow. [float] === `source.ip` Innermost IPv4 source address as indicated by first packet seen for the current flow. [float] === `source.ip_location` type: geo_point example: 40.715, -74.011 The GeoIP location of the `ip_source` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `source.outer_ip` Second innermost IPv4 source address as indicated by first packet seen for the current flow. [float] === `source.outer_ip_location` type: geo_point example: 40.715, -74.011 The GeoIP location of the `outer_ip_source` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `source.ipv6` Innermost IPv6 source address as indicated by first packet seen for the current flow. [float] === `source.ipv6_location` type: geo_point example: 60.715, -76.011 The GeoIP location of the `ipv6_source` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `source.outer_ipv6` Second innermost IPv6 source address as indicated by first packet seen for the current flow. [float] === `source.outer_ipv6_location` type: geo_point example: 60.715, -76.011 The GeoIP location of the `outer_ipv6_source` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `source.port` Source port number as indicated by first packet seen for the current flow. [float] == stats fields Object with source to destination flow measurements. [float] === `source.stats.net_packets_total` type: long Total number of packets [float] === `source.stats.net_bytes_total` type: long Total number of bytes [float] == dest fields Properties of the destination host [float] === `dest.mac` Destination MAC address as indicated by first packet seen for the current flow. [float] === `dest.ip` Innermost IPv4 destination address as indicated by first packet seen for the current flow. [float] === `dest.ip_location` type: geo_point example: 40.715, -74.011 The GeoIP location of the `ip_dest` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `dest.outer_ip` Second innermost IPv4 destination address as indicated by first packet seen for the current flow. [float] === `dest.outer_ip_location` type: geo_point example: 40.715, -74.011 The GeoIP location of the `outer_ip_dest` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `dest.ipv6` Innermost IPv6 destination address as indicated by first packet seen for the current flow. [float] === `dest.ipv6_location` type: geo_point example: 60.715, -76.011 The GeoIP location of the `ipv6_dest` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `dest.outer_ipv6` Second innermost IPv6 destination address as indicated by first packet seen for the current flow. [float] === `dest.outer_ipv6_location` type: geo_point example: 60.715, -76.011 The GeoIP location of the `outer_ipv6_dest` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `dest.port` Destination port number as indicated by first packet seen for the current flow. [float] == stats fields Object with destination to source flow measurements. [float] === `dest.stats.net_packets_total` type: long Total number of packets [float] === `dest.stats.net_bytes_total` type: long Total number of bytes [float] === `icmp_id` ICMP id used in ICMP based flow. [float] === `connection_id` optional TCP connection id [[exported-fields-http]] == HTTP fields HTTP-specific event fields. [float] == http fields Information about the HTTP request and response. [float] == request fields HTTP request [float] === `http.request.params` The query parameters or form values. The query parameters are available in the Request-URI and the form values are set in the HTTP body when the content-type is set to `x-www-form-urlencoded`. [float] === `http.request.headers` type: object A map containing the captured header fields from the request. Which headers to capture is configurable. If headers with the same header name are present in the message, they will be separated by commas. [float] === `http.request.body` type: text The body of the HTTP request. [float] == response fields HTTP response [float] === `http.response.code` example: 404 The HTTP status code. [float] === `http.response.phrase` example: Not found. The HTTP status phrase. [float] === `http.response.headers` type: object A map containing the captured header fields from the response. Which headers to capture is configurable. If headers with the same header name are present in the message, they will be separated by commas. [float] === `http.response.body` The body of the HTTP response. [[exported-fields-icmp]] == ICMP fields ICMP specific event fields. [float] === `icmp.version` The version of the ICMP protocol. [float] === `icmp.request.message` type: keyword A human readable form of the request. [float] === `icmp.request.type` type: long The request type. [float] === `icmp.request.code` type: long The request code. [float] === `icmp.response.message` type: keyword A human readable form of the response. [float] === `icmp.response.type` type: long The response type. [float] === `icmp.response.code` type: long The response code. [[exported-fields-kubernetes-processor]] == Kubernetes fields beta[] Kubernetes metadata added by the kubernetes processor [float] === `kubernetes.pod.name` type: keyword Kubernetes pod name [float] === `kubernetes.namespace` type: keyword Kubernetes namespace [float] === `kubernetes.labels` type: object Kubernetes labels map [float] === `kubernetes.annotations` type: object Kubernetes annotations map [float] === `kubernetes.container.name` type: keyword Kubernetes container name [float] === `kubernetes.container.image` type: keyword Kubernetes container image [[exported-fields-memcache]] == Memcache fields Memcached-specific event fields [float] === `memcache.protocol_type` type: keyword The memcache protocol implementation. The value can be ""binary"" for binary-based, ""text"" for text-based, or ""unknown"" for an unknown memcache protocol type. [float] === `memcache.request.line` type: keyword The raw command line for unknown commands ONLY. [float] === `memcache.request.command` type: keyword The memcache command being requested in the memcache text protocol. For example ""set"" or ""get"". The binary protocol opcodes are translated into memcache text protocol commands. [float] === `memcache.response.command` type: keyword Either the text based protocol response message type or the name of the originating request if binary protocol is used. [float] === `memcache.request.type` type: keyword The memcache command classification. This value can be ""UNKNOWN"", ""Load"", ""Store"", ""Delete"", ""Counter"", ""Info"", ""SlabCtrl"", ""LRUCrawler"", ""Stats"", ""Success"", ""Fail"", or ""Auth"". [float] === `memcache.response.type` type: keyword The memcache command classification. This value can be ""UNKNOWN"", ""Load"", ""Store"", ""Delete"", ""Counter"", ""Info"", ""SlabCtrl"", ""LRUCrawler"", ""Stats"", ""Success"", ""Fail"", or ""Auth"". The text based protocol will employ any of these, whereas the binary based protocol will mirror the request commands only (see `memcache.response.status` for binary protocol). [float] === `memcache.response.error_msg` type: keyword The optional error message in the memcache response (text based protocol only). [float] === `memcache.request.opcode` type: keyword The binary protocol message opcode name. [float] === `memcache.response.opcode` type: keyword The binary protocol message opcode name. [float] === `memcache.request.opcode_value` type: long The binary protocol message opcode value. [float] === `memcache.response.opcode_value` type: long The binary protocol message opcode value. [float] === `memcache.request.opaque` type: long The binary protocol opaque header value used for correlating request with response messages. [float] === `memcache.response.opaque` type: long The binary protocol opaque header value used for correlating request with response messages. [float] === `memcache.request.vbucket` type: long The vbucket index sent in the binary message. [float] === `memcache.response.status` type: keyword The textual representation of the response error code (binary protocol only). [float] === `memcache.response.status_code` type: long The status code value returned in the response (binary protocol only). [float] === `memcache.request.keys` type: array The list of keys sent in the store or load commands. [float] === `memcache.response.keys` type: array The list of keys returned for the load command (if present). [float] === `memcache.request.count_values` type: long The number of values found in the memcache request message. If the command does not send any data, this field is missing. [float] === `memcache.response.count_values` type: long The number of values found in the memcache response message. If the command does not send any data, this field is missing. [float] === `memcache.request.values` type: array The list of base64 encoded values sent with the request (if present). [float] === `memcache.response.values` type: array The list of base64 encoded values sent with the response (if present). [float] === `memcache.request.bytes` type: long format: bytes The byte count of the values being transferred. [float] === `memcache.response.bytes` type: long format: bytes The byte count of the values being transferred. [float] === `memcache.request.delta` type: long The counter increment/decrement delta value. [float] === `memcache.request.initial` type: long The counter increment/decrement initial value parameter (binary protocol only). [float] === `memcache.request.verbosity` type: long The value of the memcache ""verbosity"" command. [float] === `memcache.request.raw_args` type: keyword The text protocol raw arguments for the ""stats ..."" and ""lru crawl ..."" commands. [float] === `memcache.request.source_class` type: long The source class id in 'slab reassign' command. [float] === `memcache.request.dest_class` type: long The destination class id in 'slab reassign' command. [float] === `memcache.request.automove` type: keyword The automove mode in the 'slab automove' command expressed as a string. This value can be ""standby""(=0), ""slow""(=1), ""aggressive""(=2), or the raw value if the value is unknown. [float] === `memcache.request.flags` type: long The memcache command flags sent in the request (if present). [float] === `memcache.response.flags` type: long The memcache message flags sent in the response (if present). [float] === `memcache.request.exptime` type: long The data expiry time in seconds sent with the memcache command (if present). If the value is <30 days, the expiry time is relative to ""now"", or else it is an absolute Unix time in seconds (32-bit). [float] === `memcache.request.sleep_us` type: long The sleep setting in microseconds for the 'lru_crawler sleep' command. [float] === `memcache.response.value` type: long The counter value returned by a counter operation. [float] === `memcache.request.noreply` type: boolean Set to true if noreply was set in the request. The `memcache.response` field will be missing. [float] === `memcache.request.quiet` type: boolean Set to true if the binary protocol message is to be treated as a quiet message. [float] === `memcache.request.cas_unique` type: long The CAS (compare-and-swap) identifier if present. [float] === `memcache.response.cas_unique` type: long The CAS (compare-and-swap) identifier to be used with CAS-based updates (if present). [float] === `memcache.response.stats` type: array The list of statistic values returned. Each entry is a dictionary with the fields ""name"" and ""value"". [float] === `memcache.response.version` type: keyword The returned memcache version string. [[exported-fields-mongodb]] == MongoDb fields MongoDB-specific event fields. These fields mirror closely the fields for the MongoDB wire protocol. The higher level fields (for example, `query` and `resource`) apply to MongoDB events as well. [float] === `mongodb.error` If the MongoDB request has resulted in an error, this field contains the error message returned by the server. [float] === `mongodb.fullCollectionName` The full collection name. The full collection name is the concatenation of the database name with the collection name, using a dot (.) for the concatenation. For example, for the database foo and the collection bar, the full collection name is foo.bar. [float] === `mongodb.numberToSkip` type: long Sets the number of documents to omit - starting from the first document in the resulting dataset - when returning the result of the query. [float] === `mongodb.numberToReturn` type: long The requested maximum number of documents to be returned. [float] === `mongodb.numberReturned` type: long The number of documents in the reply. [float] === `mongodb.startingFrom` Where in the cursor this reply is starting. [float] === `mongodb.query` A JSON document that represents the query. The query will contain one or more elements, all of which must match for a document to be included in the result set. Possible elements include $query, $orderby, $hint, $explain, and $snapshot. [float] === `mongodb.returnFieldsSelector` A JSON document that limits the fields in the returned documents. The returnFieldsSelector contains one or more elements, each of which is the name of a field that should be returned, and the integer value 1. [float] === `mongodb.selector` A BSON document that specifies the query for selecting the document to update or delete. [float] === `mongodb.update` A BSON document that specifies the update to be performed. For information on specifying updates, see the Update Operations documentation from the MongoDB Manual. [float] === `mongodb.cursorId` The cursor identifier returned in the OP_REPLY. This must be the value that was returned from the database. [float] == rpc fields OncRPC specific event fields. [float] === `rpc.xid` RPC message transaction identifier. [float] === `rpc.call_size` type: long RPC call size with argument. [float] === `rpc.reply_size` type: long RPC reply size with argument. [float] === `rpc.status` RPC message reply status. [float] === `rpc.time` type: long RPC message processing time. [float] === `rpc.time_str` RPC message processing time in human readable form. [float] === `rpc.auth_flavor` RPC authentication flavor. [float] === `rpc.cred.uid` type: long RPC caller's user id, in case of auth-unix. [float] === `rpc.cred.gid` type: long RPC caller's group id, in case of auth-unix. [float] === `rpc.cred.gids` RPC caller's secondary group ids, in case of auth-unix. [float] === `rpc.cred.stamp` type: long Arbitrary ID which the caller machine may generate. [float] === `rpc.cred.machinename` The name of the caller's machine. [[exported-fields-mysql]] == MySQL fields MySQL-specific event fields. [float] === `mysql.iserror` type: boolean If the MySQL query returns an error, this field is set to true. [float] === `mysql.affected_rows` type: long If the MySQL command is successful, this field contains the affected number of rows of the last statement. [float] === `mysql.insert_id` If the INSERT query is successful, this field contains the id of the newly inserted row. [float] === `mysql.num_fields` If the SELECT query is successful, this field is set to the number of fields returned. [float] === `mysql.num_rows` If the SELECT query is successful, this field is set to the number of rows returned. [float] === `mysql.query` The row mysql query as read from the transaction's request. [float] === `mysql.error_code` type: long The error code returned by MySQL. [float] === `mysql.error_message` The error info message returned by MySQL. [[exported-fields-nfs]] == NFS fields NFS v4/3 specific event fields. [float] === `nfs.version` type: long NFS protocol version number. [float] === `nfs.minor_version` type: long NFS protocol minor version number. [float] === `nfs.tag` NFS v4 COMPOUND operation tag. [float] === `nfs.opcode` NFS operation name, or main operation name, in case of COMPOUND calls. [float] === `nfs.status` NFS operation reply status. [[exported-fields-pgsql]] == PostgreSQL fields PostgreSQL-specific event fields. [float] === `pgsql.query` The row pgsql query as read from the transaction's request. [float] === `pgsql.iserror` type: boolean If the PgSQL query returns an error, this field is set to true. [float] === `pgsql.error_code` type: long The PostgreSQL error code. [float] === `pgsql.error_message` The PostgreSQL error message. [float] === `pgsql.error_severity` The PostgreSQL error severity. [float] === `pgsql.num_fields` If the SELECT query if successful, this field is set to the number of fields returned. [float] === `pgsql.num_rows` If the SELECT query if successful, this field is set to the number of rows returned. [[exported-fields-raw]] == Raw fields These fields contain the raw transaction data. [float] === `request` type: text For text protocols, this is the request as seen on the wire (application layer only). For binary protocols this is our representation of the request. [float] === `response` type: text For text protocols, this is the response as seen on the wire (application layer only). For binary protocols this is our representation of the request. [[exported-fields-redis]] == Redis fields Redis-specific event fields. [float] === `redis.return_value` The return value of the Redis command in a human readable format. [float] === `redis.error` If the Redis command has resulted in an error, this field contains the error message returned by the Redis server. [[exported-fields-thrift]] == Thrift-RPC fields Thrift-RPC specific event fields. [float] === `thrift.params` The RPC method call parameters in a human readable format. If the IDL files are available, the parameters use names whenever possible. Otherwise, the IDs from the message are used. [float] === `thrift.service` The name of the Thrift-RPC service as defined in the IDL files. [float] === `thrift.return_value` The value returned by the Thrift-RPC call. This is encoded in a human readable format. [float] === `thrift.exceptions` If the call resulted in exceptions, this field contains the exceptions in a human readable format. [[exported-fields-tls]] == TLS fields TLS-specific event fields. [float] === `tls.handshake_completed` type: boolean Whether the TLS negotiation has been successful and the session has transitioned to encrypted mode. [float] === `tls.resumed` type: boolean If the TLS session has been resumed from a previous session. [float] === `tls.resumption_method` type: keyword If the session has been resumed, the underlying method used. One of ""id"" for TLS session ID or ""ticket"" for TLS ticket extension. [float] === `tls.client_certificate_requested` type: boolean Whether the server has requested the client to authenticate itself using a client certificate. [float] === `tls.client_hello.version` type: keyword The version of the TLS protocol by which the client wishes to communicate during this session. [float] === `tls.client_hello.supported_ciphers` type: array List of ciphers the client is willing to use for this session. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4 [float] === `tls.client_hello.supported_compression_methods` type: array The list of compression methods the client supports. See https://www.iana.org/assignments/comp-meth-ids/comp-meth-ids.xhtml [float] == extensions fields The hello extensions provided by the client. [float] === `tls.client_hello.extensions.server_name_indication` type: array List of hostnames [float] === `tls.client_hello.extensions.application_layer_protocol_negotiation` type: array List of application-layer protocols the client is willing to use. [float] === `tls.client_hello.extensions.session_ticket` type: keyword Length of the session ticket, if provided, or an empty string to advertise support for tickets. [float] === `tls.server_hello.version` type: keyword The version of the TLS protocol that is used for this session. It is the highest version supported by the server not exceeding the version requested in the client hello. [float] === `tls.server_hello.selected_cipher` type: keyword The cipher suite selected by the server from the list provided by in the client hello. [float] === `tls.server_hello.selected_compression_method` type: keyword The compression method selected by the server from the list provided in the client hello. [float] == extensions fields The hello extensions provided by the server. [float] === `tls.server_hello.extensions.application_layer_protocol_negotiation` type: array Negotiated application layer protocol [float] === `tls.server_hello.extensions.session_ticket` type: keyword Used to announce that a session ticket will be provided by the server. Always an empty string. [float] == client_certificate fields Certificate provided by the client for authentication. [float] === `tls.client_certificate.version` type: long X509 format version. [float] === `tls.client_certificate.serial_number` type: keyword The certificate's serial number. [float] === `tls.client_certificate.not_before` type: date Date before which the certificate is not valid. [float] === `tls.client_certificate.not_after` type: date Date after which the certificate expires. [float] === `tls.client_certificate.public_key_algorithm` type: keyword The algorithm used for this certificate's public key. One of RSA, DSA or ECDSA. [float] === `tls.client_certificate.signature_algorithm` type: keyword The algorithm used for the certificate's signature. [float] === `tls.client_certificate.alternative_names` type: array Subject Alternative Names for this certificate. [float] === `tls.client_certificate.raw` type: keyword The raw certificate in PEM format. [float] == subject fields Subject represented by this certificate. [float] === `tls.client_certificate.subject.country` type: keyword Country code. [float] === `tls.client_certificate.subject.organization` type: keyword Organization name. [float] === `tls.client_certificate.subject.organizational_unit` type: keyword Unit within organization. [float] === `tls.client_certificate.subject.province` type: keyword Province or region within country. [float] === `tls.client_certificate.subject.common_name` type: keyword Name or host name identified by the certificate. [float] == issuer fields Entity that issued and signed this certificate. [float] === `tls.client_certificate.issuer.country` type: keyword Country code. [float] === `tls.client_certificate.issuer.organization` type: keyword Organization name. [float] === `tls.client_certificate.issuer.organizational_unit` type: keyword Unit within organization. [float] === `tls.client_certificate.issuer.province` type: keyword Province or region within country. [float] === `tls.client_certificate.issuer.common_name` type: keyword Name or host name identified by the certificate. [float] == server_certificate fields Certificate provided by the server for authentication. [float] === `tls.server_certificate.version` type: long X509 format version. [float] === `tls.server_certificate.serial_number` type: keyword The certificate's serial number. [float] === `tls.server_certificate.not_before` type: date Date before which the certificate is not valid. [float] === `tls.server_certificate.not_after` type: date Date after which the certificate expires. [float] === `tls.server_certificate.public_key_algorithm` type: keyword The algorithm used for this certificate's public key. One of RSA, DSA or ECDSA. [float] === `tls.server_certificate.signature_algorithm` type: keyword The algorithm used for the certificate's signature. [float] === `tls.server_certificate.alternative_names` type: array Subject Alternative Names for this certificate. [float] === `tls.server_certificate.raw` type: keyword The raw certificate in PEM format. [float] == subject fields Subject represented by this certificate. [float] === `tls.server_certificate.subject.country` type: keyword Country code. [float] === `tls.server_certificate.subject.organization` type: keyword Organization name. [float] === `tls.server_certificate.subject.organizational_unit` type: keyword Unit within organization. [float] === `tls.server_certificate.subject.province` type: keyword Province or region within country. [float] === `tls.server_certificate.subject.common_name` type: keyword Name or host name identified by the certificate. [float] == issuer fields Entity that issued and signed this certificate. [float] === `tls.server_certificate.issuer.country` type: keyword Country code. [float] === `tls.server_certificate.issuer.organization` type: keyword Organization name. [float] === `tls.server_certificate.issuer.organizational_unit` type: keyword Unit within organization. [float] === `tls.server_certificate.issuer.province` type: keyword Province or region within country. [float] === `tls.server_certificate.issuer.common_name` type: keyword Name or host name identified by the certificate. [float] === `tls.server_certificate_chain` type: array Chain of trust for the server certificate. [float] === `tls.client_certificate_chain` type: array Chain of trust for the client certificate. [[exported-fields-trans_event]] == Transaction Event fields These fields contain data about the transaction itself. [float] === `direction` required: True Indicates whether the transaction is inbound (emitted by server) or outbound (emitted by the client). Values can be in or out. No defaults. [float] === `status` required: True The high level status of the transaction. The way to compute this value depends on the protocol, but the result has a meaning independent of the protocol. [float] === `method` The command/verb/method of the transaction. For HTTP, this is the method name (GET, POST, PUT, and so on), for SQL this is the verb (SELECT, UPDATE, DELETE, and so on). [float] === `resource` The logical resource that this transaction refers to. For HTTP, this is the URL path up to the last slash (/). For example, if the URL is `/users/1`, the resource is `/users`. For databases, the resource is typically the table name. The field is not filled for all transaction types. [float] === `path` required: True The path the transaction refers to. For HTTP, this is the URL. For SQL databases, this is the table name. For key-value stores, this is the key. [float] === `query` type: keyword The query in a human readable format. For HTTP, it will typically be something like `GET /users/_search?name=test`. For MySQL, it is something like `SELECT id from users where name=test`. [float] === `params` type: text The request parameters. For HTTP, these are the POST or GET parameters. For Thrift-RPC, these are the parameters from the request. [float] === `notes` Messages from Packetbeat itself. This field usually contains error messages for interpreting the raw data. This information can be helpful for troubleshooting. [[exported-fields-trans_measurements]] == Measurements (Transactions) fields These fields contain measurements related to the transaction. [float] === `responsetime` type: long The wall clock time it took to complete the transaction. The precision is in milliseconds. [float] === `cpu_time` type: long The CPU time it took to complete the transaction. [float] === `bytes_in` type: long format: bytes The number of bytes of the request. Note that this size is the application layer message length, without the length of the IP or TCP headers. [float] === `bytes_out` type: long format: bytes The number of bytes of the response. Note that this size is the application layer message length, without the length of the IP or TCP headers. [float] === `dnstime` type: long The time it takes to query the name server for a given request. This is typically used for RUM (real-user-monitoring) but can also have values for server-to-server communication when DNS is used for service discovery. The precision is in microseconds. [float] === `connecttime` type: long The time it takes for the TCP connection to be established for the given transaction. The precision is in microseconds. [float] === `loadtime` type: long The time it takes for the content to be loaded. This is typically used for RUM (real-user-monitoring) but it can make sense in other cases as well. The precision is in microseconds. [float] === `domloadtime` type: long In RUM (real-user-monitoring), the total time it takes for the DOM to be loaded. In terms of the W3 Navigation Timing API, this is the difference between `domContentLoadedEnd` and `domContentLoadedStart`. ",12466,False,2266.731595743467,median "/** * @file * @brief Shop keeper functions. **/ #include ""AppHdr.h"" #include ""shopping.h"" #include #include #include #include ""artefact.h"" #include ""branch.h"" #include ""cio.h"" #include ""colour.h"" #include ""describe.h"" #include ""dgn-overview.h"" #include ""english.h"" #include ""env.h"" #include ""files.h"" #include ""invent.h"" #include ""item-name.h"" #include ""item-prop.h"" #include ""item-status-flag-type.h"" #include ""items.h"" #include ""libutil.h"" #include ""menu.h"" #include ""message.h"" #include ""notes.h"" #include ""options.h"" #include ""output.h"" #include ""player.h"" #include ""prompt.h"" #include ""spl-book.h"" #include ""stash.h"" #include ""state.h"" #include ""stepdown.h"" #include ""stringutil.h"" #include ""tag-version.h"" #ifdef USE_TILE_LOCAL #include ""tilereg-crt.h"" #endif #include ""travel.h"" #include ""unicode.h"" #include ""unwind.h"" ShoppingList shopping_list; static int _shop_get_item_value(const item_def& item, int greed, bool id) { int result = (greed * item_value(item, id) / 10); return max(result, 1); } int item_price(const item_def& item, const shop_struct& shop) { return _shop_get_item_value(item, shop.greed, shoptype_identifies_stock(shop.type)); } // This probably still needs some work. Rings used to be the only // artefacts which had a change in price, and that value corresponds // to returning 50 from this function. Good artefacts will probably // be returning just over 30 right now. Note that this isn't used // as a multiple, its used in the old ring way: 7 * ret is added to // the price of the artefact. -- bwr int artefact_value(const item_def &item) { ASSERT(is_artefact(item)); int ret = 10; artefact_properties_t prop; artefact_properties(item, prop); // Brands are already accounted for via existing ego checks // This should probably be more complex... but this isn't so bad: ret += 6 * prop[ARTP_AC] + 6 * prop[ARTP_EVASION] + 4 * prop[ARTP_SHIELDING] + 6 * prop[ARTP_SLAYING] + 3 * prop[ARTP_STRENGTH] + 3 * prop[ARTP_INTELLIGENCE] + 3 * prop[ARTP_DEXTERITY] + 4 * prop[ARTP_HP] + 3 * prop[ARTP_MAGICAL_POWER]; // These resistances have meaningful levels if (prop[ARTP_FIRE] > 0) ret += 5 + 5 * (prop[ARTP_FIRE] * prop[ARTP_FIRE]); else if (prop[ARTP_FIRE] < 0) ret -= 10; if (prop[ARTP_COLD] > 0) ret += 5 + 5 * (prop[ARTP_COLD] * prop[ARTP_COLD]); else if (prop[ARTP_COLD] < 0) ret -= 10; if (prop[ARTP_WILLPOWER] > 0) ret += 4 + 4 * prop[ARTP_WILLPOWER]; else if (prop[ARTP_WILLPOWER] < 0) ret -= 6; if (prop[ARTP_NEGATIVE_ENERGY] > 0) ret += 3 + 3 * (prop[ARTP_NEGATIVE_ENERGY] * prop[ARTP_NEGATIVE_ENERGY]); // Discount Stlth-, charge for Stlth+ ret += 2 * prop[ARTP_STEALTH]; // Stlth+ costs more than Stlth- cheapens if (prop[ARTP_STEALTH] > 0) ret += 2 * prop[ARTP_STEALTH]; // only one meaningful level: if (prop[ARTP_POISON]) ret += 6; // only one meaningful level (hard to get): if (prop[ARTP_ELECTRICITY]) ret += 10; // only one meaningful level (hard to get): if (prop[ARTP_RCORR]) ret += 8; // only one meaningful level (hard to get): if (prop[ARTP_RMUT]) ret += 8; if (prop[ARTP_SEE_INVISIBLE]) ret += 6; // abilities: if (prop[ARTP_FLY]) ret += 3; if (prop[ARTP_BLINK]) ret += 10; if (prop[ARTP_INVISIBLE]) ret += 10; if (prop[ARTP_ANGRY]) ret -= 3; if (prop[ARTP_CAUSE_TELEPORTATION]) ret -= 3; if (prop[ARTP_NOISE]) ret -= 5; if (prop[ARTP_PREVENT_TELEPORTATION]) ret -= 8; if (prop[ARTP_PREVENT_SPELLCASTING]) ret -= 10; if (prop[ARTP_CONTAM]) ret -= 8; if (prop[ARTP_CORRODE]) ret -= 8; if (prop[ARTP_DRAIN]) ret -= 8; if (prop[ARTP_SLOW]) ret -= 8; if (prop[ARTP_FRAGILE]) ret -= 8; if (prop[ARTP_RMSL]) ret += 20; if (prop[ARTP_CLARITY]) ret += 20; if (prop[ARTP_ARCHMAGI]) ret += 20; return (ret > 0) ? ret : 0; } unsigned int item_value(item_def item, bool ident) { // Note that we pass item in by value, since we want a local // copy to mangle as necessary. item.flags = (ident) ? (item.flags | ISFLAG_IDENT_MASK) : (item.flags); if (is_unrandom_artefact(item) && item_ident(item, ISFLAG_KNOW_PROPERTIES)) { const unrandart_entry *entry = get_unrand_entry(item.unrand_idx); if (entry->value != 0) return entry->value; } int valued = 0; switch (item.base_type) { case OBJ_WEAPONS: valued += weapon_base_price((weapon_type)item.sub_type); if (item_type_known(item)) { switch (get_weapon_brand(item)) { case SPWPN_NORMAL: default: // randart valued *= 10; break; case SPWPN_SPEED: case SPWPN_VAMPIRISM: case SPWPN_ANTIMAGIC: valued *= 30; break; case SPWPN_DISTORTION: case SPWPN_ELECTROCUTION: case SPWPN_PAIN: case SPWPN_ACID: // Unrand-only. case SPWPN_PENETRATION: // Unrand-only. case SPWPN_SPECTRAL: valued *= 25; break; case SPWPN_CHAOS: case SPWPN_DRAINING: case SPWPN_FLAMING: case SPWPN_FREEZING: case SPWPN_HOLY_WRATH: valued *= 18; break; case SPWPN_VORPAL: valued *= 15; break; case SPWPN_PROTECTION: case SPWPN_VENOM: valued *= 12; break; } valued /= 10; } if (item_ident(item, ISFLAG_KNOW_PLUSES)) valued += 50 * item.plus; if (is_artefact(item)) { if (item_type_known(item)) valued += (7 * artefact_value(item)); else valued += 50; } else if (item_type_known(item) && get_equip_desc(item) != 0) // ??? { valued += 20; } else if (!(item.flags & ISFLAG_IDENT_MASK) && (get_equip_desc(item) != 0)) { valued += 30; // un-id'd ""glowing"" - arbitrary added cost } break; case OBJ_MISSILES: // ammunition valued += missile_base_price((missile_type)item.sub_type); if (item_type_known(item)) { switch (get_ammo_brand(item)) { case SPMSL_NORMAL: default: valued *= 10; break; case SPMSL_CHAOS: valued *= 40; break; case SPMSL_CURARE: case SPMSL_BLINDING: case SPMSL_SILVER: #if TAG_MAJOR_VERSION == 34 case SPMSL_PARALYSIS: case SPMSL_PENETRATION: case SPMSL_STEEL: #endif case SPMSL_DISPERSAL: valued *= 30; break; #if TAG_MAJOR_VERSION == 34 case SPMSL_FLAME: case SPMSL_FROST: case SPMSL_SLEEP: case SPMSL_CONFUSION: valued *= 25; break; #endif case SPMSL_POISONED: #if TAG_MAJOR_VERSION == 34 case SPMSL_RETURNING: case SPMSL_EXPLODING: case SPMSL_SLOW: case SPMSL_SICKNESS: #endif case SPMSL_FRENZY: valued *= 20; break; } valued /= 10; } break; case OBJ_ARMOUR: valued += armour_base_price((armour_type)item.sub_type); if (item_type_known(item)) { const int sparm = get_armour_ego_type(item); switch (sparm) { case SPARM_ARCHMAGI: case SPARM_RESISTANCE: valued += 250; break; case SPARM_COLD_RESISTANCE: case SPARM_DEXTERITY: case SPARM_FIRE_RESISTANCE: case SPARM_SEE_INVISIBLE: case SPARM_INTELLIGENCE: case SPARM_FLYING: case SPARM_STEALTH: case SPARM_STRENGTH: case SPARM_INVISIBILITY: case SPARM_WILLPOWER: case SPARM_PROTECTION: case SPARM_HURLING: case SPARM_REPULSION: case SPARM_PRESERVATION: case SPARM_SHADOWS: case SPARM_RAMPAGING: case SPARM_INFUSION: case SPARM_LIGHT: case SPARM_ENERGY: valued += 50; break; case SPARM_POSITIVE_ENERGY: case SPARM_POISON_RESISTANCE: case SPARM_REFLECTION: case SPARM_SPIRIT_SHIELD: case SPARM_HARM: case SPARM_RAGE: case SPARM_MAYHEM: case SPARM_GUILE: valued += 20; break; case SPARM_PONDEROUSNESS: valued -= 250; break; } } if (item_ident(item, ISFLAG_KNOW_PLUSES)) valued += 50 * item.plus; if (is_artefact(item)) { if (item_type_known(item)) valued += (7 * artefact_value(item)); else valued += 50; } else if (item_type_known(item) && get_equip_desc(item) != 0) valued += 20; // ??? else if (!(item.flags & ISFLAG_IDENT_MASK) && (get_equip_desc(item) != 0)) { valued += 30; // un-id'd ""glowing"" - arbitrary added cost } break; case OBJ_WANDS: if (!item_type_known(item)) valued += 40; else { // true if the wand is of a good type, a type with significant // inherent value even when empty. Good wands are less expensive // per charge. bool good = false; switch (item.sub_type) { case WAND_ACID: case WAND_DIGGING: valued += 80; good = true; break; case WAND_ICEBLAST: case WAND_MINDBURST: valued += 40; good = true; break; case WAND_CHARMING: case WAND_POLYMORPH: case WAND_PARALYSIS: valued += 20; break; case WAND_FLAME: valued += 10; break; default: valued += 6; break; } if (item_ident(item, ISFLAG_KNOW_PLUSES)) { if (good) valued += (valued * item.plus) / 4; else valued += (valued * item.plus) / 2; } } break; case OBJ_POTIONS: if (!item_type_known(item)) valued += 9; else { switch (item.sub_type) { case POT_EXPERIENCE: valued += 500; break; case POT_RESISTANCE: case POT_HASTE: valued += 100; break; case POT_MAGIC: case POT_INVISIBILITY: case POT_CANCELLATION: case POT_AMBROSIA: case POT_MUTATION: valued += 80; break; case POT_BERSERK_RAGE: case POT_HEAL_WOUNDS: valued += 50; break; case POT_MIGHT: case POT_BRILLIANCE: valued += 40; break; case POT_CURING: case POT_LIGNIFY: case POT_ATTRACTION: case POT_FLIGHT: valued += 30; break; case POT_DEGENERATION: valued += 10; break; CASE_REMOVED_POTIONS(item.sub_type) } } break; case OBJ_SCROLLS: if (!item_type_known(item)) valued += 10; else { switch (item.sub_type) { case SCR_ACQUIREMENT: valued += 520; break; case SCR_BRAND_WEAPON: valued += 200; break; case SCR_SUMMONING: valued += 95; break; case SCR_BLINKING: case SCR_ENCHANT_ARMOUR: case SCR_ENCHANT_WEAPON: case SCR_TORMENT: case SCR_HOLY_WORD: case SCR_SILENCE: case SCR_VULNERABILITY: valued += 75; break; case SCR_AMNESIA: case SCR_FEAR: case SCR_IMMOLATION: case SCR_MAGIC_MAPPING: valued += 35; break; case SCR_TELEPORTATION: valued += 30; break; case SCR_FOG: case SCR_IDENTIFY: #if TAG_MAJOR_VERSION == 34 case SCR_CURSE_ARMOUR: case SCR_CURSE_WEAPON: case SCR_CURSE_JEWELLERY: #endif valued += 20; break; case SCR_NOISE: valued += 10; break; } } break; case OBJ_JEWELLERY: if (!item_type_known(item)) valued += 50; else { // Variable-strength rings. if (jewellery_type_has_plusses(item.sub_type)) { // Formula: price = kn(n+1) / 2, where k depends on the subtype, // n is the power. (The base variable is equal to 2n.) int base = 0; int coefficient = 0; if (item.sub_type == RING_SLAYING) base = 3 * item.plus; else base = 2 * item.plus; switch (item.sub_type) { case RING_SLAYING: case RING_PROTECTION: case RING_EVASION: coefficient = 40; break; case RING_STRENGTH: case RING_DEXTERITY: case RING_INTELLIGENCE: coefficient = 30; break; default: break; } if (base <= 0) valued += 25 * base; else valued += (coefficient * base * (base + 1)) / 8; } else { switch (item.sub_type) { case AMU_FAITH: valued += 400; break; case RING_WIZARDRY: case AMU_REGENERATION: case AMU_GUARDIAN_SPIRIT: case AMU_MANA_REGENERATION: case AMU_ACROBAT: case AMU_REFLECTION: valued += 300; break; case RING_FIRE: case RING_ICE: case RING_PROTECTION_FROM_COLD: case RING_PROTECTION_FROM_FIRE: case RING_WILLPOWER: valued += 250; break; case RING_MAGICAL_POWER: case RING_LIFE_PROTECTION: case RING_POISON_RESISTANCE: case RING_RESIST_CORROSION: valued += 200; break; case RING_STEALTH: case RING_FLIGHT: valued += 175; break; case RING_SEE_INVISIBLE: valued += 150; break; case AMU_NOTHING: valued += 75; break; } } if (is_artefact(item)) { // in this branch we're guaranteed to know // the item type! if (valued < 0) valued = (artefact_value(item) - 5) * 7; else valued += artefact_value(item) * 7; } // Hard minimum, as it's worth 20 to ID a ring. valued = max(20, valued); } break; case OBJ_MISCELLANY: switch (item.sub_type) { case MISC_HORN_OF_GERYON: case MISC_ZIGGURAT: valued += 5000; break; case MISC_PHIAL_OF_FLOODS: case MISC_TIN_OF_TREMORSTONES: case MISC_BOX_OF_BEASTS: case MISC_CONDENSER_VANE: case MISC_PHANTOM_MIRROR: valued += 400; break; case MISC_LIGHTNING_ROD: valued += 300; break; case MISC_XOMS_CHESSBOARD: default: valued += 200; } break; case OBJ_BOOKS: { valued = 0; const book_type book = static_cast(item.sub_type); if (book == BOOK_MANUAL) return 800; #if TAG_MAJOR_VERSION == 34 if (book == BOOK_BUGGY_DESTRUCTION) break; #endif int levels = 0; const vector spells = spells_in_book(item); for (spell_type spell : spells) levels += spell_difficulty(spell); // Level 9 spells are worth 4x level 1 spells. valued += levels * 20 + spells.size() * 20; break; } case OBJ_STAVES: valued = item_type_known(item) ? 250 : 120; break; case OBJ_ORBS: valued = 250000; break; case OBJ_RUNES: valued = 10000; break; default: break; } // end switch if (valued < 1) valued = 1; valued = stepdown_value(valued, 1000, 1000, 10000, 10000); return item.quantity * valued; } bool is_worthless_consumable(const item_def &item) { switch (item.base_type) { case OBJ_POTIONS: switch (item.sub_type) { // Blood potions are worthless because they are easy to make. case POT_DEGENERATION: return true; default: return false; CASE_REMOVED_POTIONS(item.sub_type) } case OBJ_SCROLLS: switch (item.sub_type) { #if TAG_MAJOR_VERSION == 34 case SCR_CURSE_ARMOUR: case SCR_CURSE_WEAPON: case SCR_CURSE_JEWELLERY: #endif case SCR_NOISE: return true; default: return false; } // Only consumables are worthless. default: return false; } } static int _count_identical(const vector& stock, const item_def& item) { int count = 0; for (const item_def& other : stock) if (ShoppingList::items_are_same(item, other)) count++; return count; } /** Buy an item from a shop! * * @param shop the shop to purchase from. * @param pos where the shop is located * @param index the index of the item to buy in shop.stock * @returns true if it went in your inventory, false otherwise. */ static bool _purchase(shop_struct& shop, const level_pos& pos, int index) { item_def item = shop.stock[index]; // intentional copy const int cost = item_price(item, shop); shop.stock.erase(shop.stock.begin() + index); // Remove from shopping list if it's unique // (i.e., if the shop has multiple scrolls of // identify, don't remove the other scrolls // from the shopping list if there's any // left). if (shopping_list.is_on_list(item, &pos) && _count_identical(shop.stock, item) == 0) { shopping_list.del_thing(item, &pos); } // Take a note of the purchase. take_note(Note(NOTE_BUY_ITEM, cost, 0, item.name(DESC_A).c_str())); // But take no further similar notes. item.flags |= ISFLAG_NOTED_GET; if (fully_identified(item)) item.flags |= ISFLAG_NOTED_ID; you.del_gold(cost); you.attribute[ATTR_PURCHASES] += cost; origin_purchased(item); if (shoptype_identifies_stock(shop.type) || item_type_is_equipment(item.base_type)) { // Identify the item and its type. // This also takes the ID note if necessary. identify_item(item); } // Shopkeepers will place goods you can't carry outside the shop. if (item_is_stationary(item) || !move_item_to_inv(item)) { copy_item_to_grid(item, shop.pos); return false; } return true; } enum shopping_order { ORDER_TYPE, ORDER_DEFAULT = ORDER_TYPE, ORDER_PRICE, ORDER_ALPHABETICAL, NUM_ORDERS }; static const char * const shopping_order_names[NUM_ORDERS] = { ""type"", ""price"", ""name"" }; static shopping_order operator++(shopping_order &x) { x = static_cast(x + 1); if (x == NUM_ORDERS) x = ORDER_DEFAULT; return x; } class ShopMenu : public InvMenu { friend class ShopEntry; shop_struct& shop; shopping_order order = ORDER_DEFAULT; level_pos pos; bool can_purchase; int selected_cost() const; void init_entries(); void update_help(); void resort(); void purchase_selected(); virtual bool process_key(int keyin) override; public: bool bought_something = false; ShopMenu(shop_struct& _shop, const level_pos& _pos, bool _can_purchase); }; class ShopEntry : public InvEntry { ShopMenu& menu; string get_text() const override { const int cost = item_price(*item, menu.shop); const int total_cost = menu.selected_cost(); const bool on_list = shopping_list.is_on_list(*item, &menu.pos); // Colour stock as follows: // * lightcyan, if on the shopping list and not selected. // * lightred, if you can't buy all you selected. // * lightgreen, if this item is purchasable along with your selections // * red, if this item is not purchasable even by itself. // * yellow, if this item would be purchasable if you deselected // something else. // Is this too complicated? (jpeg) const colour_t keycol = !selected() && on_list ? LIGHTCYAN : selected() && total_cost > you.gold ? LIGHTRED : cost <= you.gold - total_cost ? LIGHTGREEN : cost > you.gold ? RED : YELLOW; const string keystr = colour_to_str(keycol); const string itemstr = colour_to_str(menu_colour(text, item_prefix(*item), tag)); return make_stringf("" <%s>%c %c <%s>%4d gold %s%s"", keystr.c_str(), hotkeys[0], selected() ? '+' : on_list ? '$' : '-', keystr.c_str(), itemstr.c_str(), cost, text.c_str(), shop_item_unknown(*item) ? "" (unknown)"" : """", itemstr.c_str()); } virtual void select(int qty = -1) override { if (shopping_list.is_on_list(*item, &menu.pos) && qty != 0) shopping_list.del_thing(*item, &menu.pos); InvEntry::select(qty); } public: ShopEntry(const item_def& i, ShopMenu& m) : InvEntry(i), menu(m) { show_background = false; } }; // XX why is this MF_QUIET_SELECT? ShopMenu::ShopMenu(shop_struct& _shop, const level_pos& _pos, bool _can_purchase) : InvMenu(MF_MULTISELECT | MF_NO_SELECT_QTY | MF_QUIET_SELECT | MF_ALLOW_FORMATTING | MF_INIT_HOVER), shop(_shop), pos(_pos), can_purchase(_can_purchase) { menu_action = can_purchase ? ACT_EXECUTE : ACT_EXAMINE; set_flags(get_flags() & ~MF_USE_TWO_COLUMNS); set_tag(""shop""); init_entries(); resort(); update_help(); set_title(""Welcome to "" + shop_name(shop) + ""! What would you "" ""like to do?""); } void ShopMenu::init_entries() { menu_letter ckey = 'a'; for (item_def& item : shop.stock) { auto newentry = make_unique(item, *this); newentry->hotkeys.clear(); newentry->add_hotkey(ckey++); add_entry(move(newentry)); } } int ShopMenu::selected_cost() const { int cost = 0; for (auto item : selected_entries()) cost += item_price(*dynamic_cast(item)->item, shop); return cost; } void ShopMenu::update_help() { string top_line = make_stringf(""You have %d gold piece%s."", you.gold, you.gold != 1 ? ""s"" : """"); const int total_cost = selected_cost(); if (total_cost > you.gold) { top_line += """"; top_line += make_stringf("" You are short %d gold piece%s for the purchase."", total_cost - you.gold, (total_cost - you.gold != 1) ? ""s"" : """"); top_line += """"; } else if (total_cost) { top_line += make_stringf("" After the purchase, you will have %d gold piece%s."", you.gold - total_cost, (you.gold - total_cost != 1) ? ""s"" : """"); } top_line += """"; // Ensure length >= 80ch, which prevents the local tiles menu from resizing // as the player selects/deselects entries. Blegh.. int top_line_width = strwidth(formatted_string::parse_string(top_line).tostring()); top_line += string(max(0, 80 - top_line_width), ' ') + '\\n'; set_more(formatted_string::parse_string(top_line + make_stringf( //You have 0 gold pieces. //[Esc/R-Click] exit [!] buy|examine items [a-i] select item for purchase //[/] sort (default) [Enter] make purchase [A-I] put item on shopping list #if defined(USE_TILE_LOCAL) && !defined(TOUCH_UI) ""[Esc/R-Click] exit "" #else // ""/R-Click"" ""[Esc] exit "" #endif ""%s %s %s\\n"" ""[/] sort (%s)%s %s %s put item on shopping list"", !can_purchase ? "" "" "" "" "" "" "" "" "" "" : menu_action == ACT_EXECUTE ? ""[!] buy|examine items"" : ""[!] buy|examine items"", hyphenated_hotkey_letters(item_count(), 'a').c_str(), menu_action == ACT_EXECUTE ? ""select item for purchase"" : ""examine item"", shopping_order_names[order], // strwidth(""default"") string(7 - strwidth(shopping_order_names[order]), ' ').c_str(), !can_purchase ? "" "" "" "" "" "" : ""[Enter] make purchase"", hyphenated_hotkey_letters(item_count(), 'A').c_str()))); } void ShopMenu::purchase_selected() { bool buying_from_list = false; vector selected = selected_entries(); int cost = selected_cost(); if (selected.empty()) { ASSERT(cost == 0); buying_from_list = true; for (auto item : items) { const item_def& it = *dynamic_cast(item)->item; if (shopping_list.is_on_list(it, &pos)) { selected.push_back(item); cost += item_price(it, shop); } } } if (selected.empty()) return; const string col = colour_to_str(channel_to_colour(MSGCH_PROMPT)); update_help(); const formatted_string old_more = more; if (cost > you.gold) { more = formatted_string::parse_string(make_stringf( ""<%s>You don't have enough money.\\n"", col.c_str(), col.c_str())); more += old_more; update_more(); return; } more = formatted_string::parse_string(make_stringf( ""<%s>Purchase items%s for %d gold? (%s/N)\\n"", col.c_str(), buying_from_list ? "" in shopping list"" : """", cost, Options.easy_confirm == easy_confirm_type::none ? ""Y"" : ""y"", col.c_str())); more += old_more; update_more(); if (!yesno(nullptr, true, 'n', false, false, true)) { more = old_more; update_more(); return; } sort(begin(selected), end(selected), [](MenuEntry* a, MenuEntry* b) { return a->data > b->data; }); vector bought_indices; int outside_items = 0; // Store last_pickup in case we need to restore it. // Then clear it to fill with items purchased. map tmp_l_p = you.last_pickup; you.last_pickup.clear(); // Will iterate backwards through the shop (because of the earlier sort). // This means we can erase() from shop.stock (since it only invalidates // pointers to later elements), but nothing else. for (auto entry : selected) { const int i = static_cast(entry->data) - shop.stock.data(); item_def& item(shop.stock[i]); // Can happen if the price changes due to id status if (item_price(item, shop) > you.gold) continue; const int quant = item.quantity; if (!_purchase(shop, pos, i)) { // The purchased item didn't fit into your // knapsack. outside_items += quant; } bought_indices.push_back(i); bought_something = true; } if (you.last_pickup.empty()) you.last_pickup = tmp_l_p; // Since the old ShopEntrys may now point to past the end of shop.stock (or // just the wrong place in general) nuke the whole thing and start over. clear(); init_entries(); resort(); if (outside_items) { update_help(); const formatted_string next_more = more; more = formatted_string::parse_string(make_stringf( ""<%s>I'll put %s outside for you.\\n"", col.c_str(), bought_indices.size() == 1 ? ""it"" : (int) bought_indices.size() == outside_items ? ""them"" : ""some of them"", col.c_str())); more += next_more; update_more(); } else update_help(); update_menu(true); } // Doesn't handle redrawing itself. void ShopMenu::resort() { switch (order) { case ORDER_TYPE: { const bool id = shoptype_identifies_stock(shop.type); // Using a map to sort reduces the number of item->name() calls. multimap list; for (const auto entry : items) { const auto item = dynamic_cast(entry)->item; if (is_known_artefact(*item)) list.insert({item->name(DESC_QUALNAME, false, id), entry}); else { list.insert({item->name(DESC_DBNAME, false, id) + "" "" + item->name(DESC_PLAIN, false, id), entry}); } } items.clear(); for (auto &entry : list) items.push_back(entry.second); break; } case ORDER_PRICE: sort(begin(items), end(items), [this](MenuEntry* a, MenuEntry* b) { return item_price(*dynamic_cast(a)->item, shop) < item_price(*dynamic_cast(b)->item, shop); }); break; case ORDER_ALPHABETICAL: sort(begin(items), end(items), [this](MenuEntry* a, MenuEntry* b) -> bool { const bool id = shoptype_identifies_stock(shop.type); return dynamic_cast(a)->item->name(DESC_PLAIN, false, id) < dynamic_cast(b)->item->name(DESC_PLAIN, false, id); }); break; case NUM_ORDERS: die(""invalid ordering""); } for (size_t i = 0; i < items.size(); ++i) items[i]->hotkeys[0] = index_to_letter(i); } bool ShopMenu::process_key(int keyin) { switch (keyin) { case '!': case '?': if (can_purchase) { if (menu_action == ACT_EXECUTE) menu_action = ACT_EXAMINE; else menu_action = ACT_EXECUTE; update_help(); update_more(); } return true; case CK_MOUSE_CLICK: case CK_ENTER: if (can_purchase) purchase_selected(); return true; case '$': { const vector selected = selected_entries(); if (!selected.empty()) { // Move selected to shopping list. for (auto entry : selected) { const item_def& item = *dynamic_cast(entry)->item; entry->selected_qty = 0; if (!shopping_list.is_on_list(item, &pos)) shopping_list.add_thing(item, item_price(item, shop), &pos); } } else // Move shoplist to selection. for (auto entry : items) if (shopping_list.is_on_list(*dynamic_cast(entry)->item, &pos)) entry->select(-2); // Move shoplist to selection. update_menu(true); return true; } case '/': ++order; resort(); update_help(); update_menu(true); return true; default: break; } if (keyin - 'a' >= 0 && keyin - 'a' < (int)items.size() && menu_action == ACT_EXAMINE) { // A hack to make the description more useful. // The default copy constructor is non-const for item_def, // so we need this violation of const hygene to tweak the flags // to make the description more useful. The flags are copied by // value by the default copy constructor so this is safe. item_def& item(*const_cast(dynamic_cast( items[letter_to_index(keyin)])->item)); if (shoptype_identifies_stock(shop.type)) { item.flags |= (ISFLAG_IDENT_MASK | ISFLAG_NOTED_ID | ISFLAG_NOTED_GET); } describe_item_popup(item); return true; } else if (keyin - 'A' >= 0 && keyin - 'A' < (int)items.size()) { const auto index = letter_to_index(keyin) % 26; auto entry = dynamic_cast(items[index]); entry->selected_qty = 0; const item_def& item(*entry->item); if (shopping_list.is_on_list(item, &pos)) shopping_list.del_thing(item, &pos); else shopping_list.add_thing(item, item_price(item, shop), &pos); update_menu(true); return true; } auto old_selected = selected_entries(); bool ret = InvMenu::process_key(keyin); if (old_selected != selected_entries()) { // Update the footer to display the new $$$ info. update_help(); update_menu(true); } return ret; } void shop() { if (!shop_at(you.pos())) { mprf(MSGCH_ERROR, ""Help! Non-existent shop.""); return; } shop_struct& shop = *shop_at(you.pos()); const string shopname = shop_name(shop); // Quick out, if no inventory if (shop.stock.empty()) { mprf(""%s appears to be closed."", shopname.c_str()); destroy_shop_at(you.pos()); return; } bool culled = false; for (const auto& item : shop.stock) { const int cost = item_price(item, shop); culled |= shopping_list.cull_identical_items(item, cost); } if (culled) more(); // make sure all messages appear before menu ShopMenu menu(shop, level_pos::current(), true); menu.show(); StashTrack.get_shop(shop.pos) = ShopInfo(shop); bool any_on_list = any_of(begin(shop.stock), end(shop.stock), [](const item_def& item) { return shopping_list.is_on_list(item); }); // If the shop is now empty, erase it from the overview. if (shop.stock.empty()) destroy_shop_at(you.pos()); redraw_screen(); update_screen(); if (menu.bought_something) mprf(""Thank you for shopping at %s!"", shopname.c_str()); if (any_on_list) mpr(""You can access your shopping list by pressing '$'.""); } void shop(shop_struct& shop, const level_pos& pos) { ASSERT(shop.pos == pos.pos); ShopMenu(shop, pos, false).show(); } void destroy_shop_at(coord_def p) { if (shop_at(p)) { env.shop.erase(p); env.grid(p) = DNGN_ABANDONED_SHOP; unnotice_feature(level_pos(level_id::current(), p)); } } shop_struct *shop_at(const coord_def& where) { if (env.grid(where) != DNGN_ENTER_SHOP) return nullptr; auto it = env.shop.find(where); ASSERT(it != env.shop.end()); ASSERT(it->second.pos == where); ASSERT(it->second.type != SHOP_UNASSIGNED); return &it->second; } string shop_type_name(shop_type type) { switch (type) { case SHOP_WEAPON_ANTIQUE: return ""Antique Weapon""; case SHOP_ARMOUR_ANTIQUE: return ""Antique Armour""; case SHOP_WEAPON: return ""Weapon""; case SHOP_ARMOUR: return ""Armour""; case SHOP_JEWELLERY: return ""Jewellery""; case SHOP_BOOK: return ""Book""; #if TAG_MAJOR_VERSION == 34 case SHOP_EVOKABLES: return ""Gadget""; case SHOP_FOOD: return ""Removed Food""; #endif case SHOP_SCROLL: return ""Magic Scroll""; case SHOP_GENERAL_ANTIQUE: return ""Assorted Antiques""; case SHOP_DISTILLERY: return ""Distillery""; case SHOP_GENERAL: return ""General Store""; default: return ""Bug""; } } static const char *_shop_type_suffix(shop_type type, const coord_def &where) { if (type == SHOP_GENERAL || type == SHOP_GENERAL_ANTIQUE || type == SHOP_DISTILLERY) { return """"; } static const char * const suffixnames[] = { ""Shoppe"", ""Boutique"", ""Emporium"", ""Shop"" }; return suffixnames[(where.x + where.y) % ARRAYSZ(suffixnames)]; } string shop_name(const shop_struct& shop) { const shop_type type = shop.type; string sh_name = """"; #if TAG_MAJOR_VERSION == 34 // xref ShopInfo::load if (shop.shop_name == "" "") return shop.shop_type_name; #endif if (!shop.shop_name.empty()) sh_name += apostrophise(shop.shop_name) + "" ""; else { uint32_t seed = static_cast(shop.keeper_name[0]) | (static_cast(shop.keeper_name[1]) << 8) | (static_cast(shop.keeper_name[1]) << 16); sh_name += apostrophise(make_name(seed)) + "" ""; } if (!shop.shop_type_name.empty()) sh_name += shop.shop_type_name; else sh_name += shop_type_name(type); if (!shop.shop_suffix_name.empty()) sh_name += "" "" + shop.shop_suffix_name; else { string sh_suffix = _shop_type_suffix(type, shop.pos); if (!sh_suffix.empty()) sh_name += "" "" + sh_suffix; } return sh_name; } bool is_shop_item(const item_def &item) { return item.link == ITEM_IN_SHOP; } bool shoptype_identifies_stock(shop_type type) { return type != SHOP_WEAPON_ANTIQUE && type != SHOP_ARMOUR_ANTIQUE && type != SHOP_GENERAL_ANTIQUE; } bool shop_item_unknown(const item_def &item) { return item_type_has_ids(item.base_type) && item_type_known(item) && !get_ident_type(item) && !is_artefact(item); } static const char *shop_types[] = { ""weapon"", ""armour"", ""antique weapon"", ""antique armour"", ""antiques"", ""jewellery"", #if TAG_MAJOR_VERSION == 34 ""removed gadget"", #endif ""book"", #if TAG_MAJOR_VERSION == 34 ""removed food"", #endif ""distillery"", ""scroll"", ""general"", }; /** What shop type is this? * * @param s the shop type, in a string. * @returns the corresponding enum, or SHOP_UNASSIGNED if none. */ shop_type str_to_shoptype(const string &s) { #if TAG_MAJOR_VERSION == 34 if (s == ""removed gadget"" || s == ""removed food"") return SHOP_UNASSIGNED; #endif if (s == ""random"" || s == ""any"") return SHOP_RANDOM; for (size_t i = 0; i < ARRAYSZ(shop_types); ++i) if (s == shop_types[i]) return static_cast(i); return SHOP_UNASSIGNED; } const char *shoptype_to_str(shop_type type) { return shop_types[type]; } void list_shop_types() { mpr_nojoin(MSGCH_PLAIN, ""Available shop types: ""); for (const char *type : shop_types) mprf_nocap(""%s"", type); } //////////////////////////////////////////////////////////////////////// // TODO: // * Warn if buying something not on the shopping list would put // something on shopping list out of your reach. #define SHOPPING_LIST_KEY ""shopping_list_key"" #define SHOPPING_LIST_COST_KEY ""shopping_list_cost_key"" #define SHOPPING_THING_COST_KEY ""cost_key"" #define SHOPPING_THING_ITEM_KEY ""item_key"" #define SHOPPING_THING_DESC_KEY ""desc_key"" #define SHOPPING_THING_VERB_KEY ""verb_key"" #define SHOPPING_THING_POS_KEY ""pos_key"" ShoppingList::ShoppingList() : list(nullptr), min_unbuyable_cost(0), min_unbuyable_idx(0), max_buyable_cost(0), max_buyable_idx(0) { } #define SETUP_POS() \\ ASSERT(list); \\ level_pos pos; \\ if (_pos != nullptr) \\ pos = *_pos; \\ else \\ pos = level_pos::current(); \\ ASSERT(pos.is_valid()); bool ShoppingList::add_thing(const item_def &item, int cost, const level_pos* _pos) { ASSERT(item.defined()); ASSERT(cost > 0); SETUP_POS(); if (!find_thing(item, pos).empty()) // TODO: this check isn't working? { mprf(MSGCH_ERROR, ""%s is already on the shopping list."", item.name(DESC_THE).c_str()); return false; } CrawlHashTable *thing = new CrawlHashTable(); (*thing)[SHOPPING_THING_COST_KEY] = cost; (*thing)[SHOPPING_THING_POS_KEY] = pos; (*thing)[SHOPPING_THING_ITEM_KEY] = item; list->push_back(*thing); refresh(); return true; } bool ShoppingList::is_on_list(const item_def &item, const level_pos* _pos) const { SETUP_POS(); return !find_thing(item, pos).empty(); } bool ShoppingList::is_on_list(string desc, const level_pos* _pos) const { SETUP_POS(); return !find_thing(desc, pos).empty(); } void ShoppingList::del_thing_at_index(int idx) { ASSERT_RANGE(idx, 0, list->size()); list->erase(idx); refresh(); } template void ShoppingList::del_thing_at_indices(C const &idxs) { set> indices(idxs.begin(), idxs.end()); for (auto idx : indices) { ASSERT_RANGE(idx, 0, list->size()); list->erase(idx); } refresh(); } void ShoppingList::del_things_from(const level_id &lid) { for (unsigned int i = 0; i < list->size(); i++) { const CrawlHashTable &thing = (*list)[i]; if (thing_pos(thing).is_on(lid)) list->erase(i--); } refresh(); } bool ShoppingList::del_thing(const item_def &item, const level_pos* _pos) { SETUP_POS(); auto indices = find_thing(item, pos); if (indices.empty()) { mprf(MSGCH_ERROR, ""%s isn't on shopping list, can't delete it."", item.name(DESC_THE).c_str()); return false; } del_thing_at_indices(indices); return true; } bool ShoppingList::del_thing(string desc, const level_pos* _pos) { SETUP_POS(); auto indices = find_thing(desc, pos); if (indices.empty()) { mprf(MSGCH_ERROR, ""%s isn't on shopping list, can't delete it."", desc.c_str()); return false; } del_thing_at_indices(indices); return true; } #undef SETUP_POS #define REMOVE_PROMPTED_KEY ""remove_prompted_key"" #define REPLACE_PROMPTED_KEY ""replace_prompted_key"" // TODO: // // * If you get a randart which lets you turn invisible, then remove // any ordinary rings of invisibility from the shopping list. // // * If you collected enough spellbooks that all the spells in a // shopping list book are covered, then auto-remove it. bool ShoppingList::cull_identical_items(const item_def& item, int cost) { // Dead men can't update their shopping lists. if (!crawl_state.need_save) return 0; // Can't put items in Bazaar shops in the shopping list, so // don't bother transferring shopping list items to Bazaar shops. // TODO: temporary shoplists if (cost != -1 && !is_connected_branch(you.where_are_you)) return 0; switch (item.base_type) { case OBJ_JEWELLERY: case OBJ_BOOKS: case OBJ_STAVES: // Only these are really interchangeable. break; case OBJ_MISCELLANY: // ... and a few of these. if (!is_xp_evoker(item)) return 0; break; default: return 0; } if (!item_type_known(item) || is_artefact(item)) return 0; // Ignore stat-modification rings which reduce a stat, since they're // worthless. if (item.base_type == OBJ_JEWELLERY && item.plus < 0) return 0; // Manuals are consumable, and interesting enough to keep on list. if (item.is_type(OBJ_BOOKS, BOOK_MANUAL)) return 0; // Item is already on shopping-list. const bool on_list = !find_thing(item, level_pos::current()).empty(); const bool do_prompt = item.base_type == OBJ_JEWELLERY && !jewellery_is_amulet(item) && ring_has_stackable_effect(item); bool add_item = false; typedef pair list_pair; vector to_del; // NOTE: Don't modify the shopping list while iterating over it. for (CrawlHashTable &thing : *list) { if (!thing_is_item(thing)) continue; const item_def& list_item = get_thing_item(thing); if (list_item.base_type != item.base_type || list_item.sub_type != item.sub_type) { continue; } if (!item_type_known(list_item) || is_artefact(list_item)) continue; // Don't prompt to remove rings with strictly better pluses // than the new one. Also, don't prompt to remove rings with // known pluses when the new ring's pluses are unknown. if (item.base_type == OBJ_JEWELLERY) { const bool has_plus = jewellery_has_pluses(item); const int delta_p = item.plus - list_item.plus; if (has_plus && item_ident(list_item, ISFLAG_KNOW_PLUSES) && (!item_ident(item, ISFLAG_KNOW_PLUSES) || delta_p < 0)) { continue; } } // Don't prompt to remove known manuals when the new one is unknown // or for a different skill. if (item.is_type(OBJ_BOOKS, BOOK_MANUAL) && item_type_known(list_item) && (!item_type_known(item) || item.plus != list_item.plus)) { continue; } list_pair listed(list_item, thing_pos(thing)); // cost = -1, we just found a shop item which is cheaper than // one on the shopping list. if (cost != -1) { int list_cost = thing_cost(thing); if (cost >= list_cost) continue; // Only prompt once. if (thing.exists(REPLACE_PROMPTED_KEY)) continue; thing[REPLACE_PROMPTED_KEY] = (bool) true; string prompt = make_stringf(""Shopping list: replace %dgp %s with cheaper "" ""one? (Y/n)"", list_cost, describe_thing(thing).c_str()); if (yesno(prompt.c_str(), true, 'y', false)) { add_item = true; to_del.push_back(listed); } continue; } // cost == -1, we just got an item which is on the shopping list. if (do_prompt) { // Only prompt once. if (thing.exists(REMOVE_PROMPTED_KEY)) continue; thing[REMOVE_PROMPTED_KEY] = (bool) true; string prompt = make_stringf(""Shopping list: remove %s? (Y/n)"", describe_thing(thing, DESC_A).c_str()); if (yesno(prompt.c_str(), true, 'y', false)) { to_del.push_back(listed); mprf(""Shopping list: removing %s"", describe_thing(thing, DESC_A).c_str()); } else canned_msg(MSG_OK); } else { mprf(""Shopping list: removing %s"", describe_thing(thing, DESC_A).c_str()); to_del.push_back(listed); } } for (list_pair &entry : to_del) del_thing(entry.first, &entry.second); if (add_item && !on_list) add_thing(item, cost); return to_del.size(); } void ShoppingList::item_type_identified(object_class_type base_type, int sub_type) { // Dead men can't update their shopping lists. if (!crawl_state.need_save) return; // Only restore the excursion at the very end. level_excursion le; #if TAG_MAJOR_VERSION == 34 // Handle removed Gozag shops from old saves. Only do this once: // future Gozag abandonment will call remove_dead_shops itself. if (!you.props.exists(REMOVED_DEAD_SHOPS_KEY)) { remove_dead_shops(); you.props[REMOVED_DEAD_SHOPS_KEY] = true; } #endif for (CrawlHashTable &thing : *list) { if (!thing_is_item(thing)) continue; const item_def& item = get_thing_item(thing); if (item.base_type != base_type || item.sub_type != sub_type) continue; const level_pos place = thing_pos(thing); le.go_to(place.id); const shop_struct *shop = shop_at(place.pos); ASSERT(shop); if (shoptype_identifies_stock(shop->type)) continue; thing[SHOPPING_THING_COST_KEY] = _shop_get_item_value(item, shop->greed, false); } // Prices could have changed. refresh(); } void ShoppingList::spells_added_to_library(const vector& spells, bool quiet) { if (!list) /* let's not make book starts crash instantly... */ return; unordered_set indices_to_del; for (CrawlHashTable &thing : *list) { if (!thing_is_item(thing)) // ??? continue; const item_def& book = get_thing_item(thing); if (book.base_type != OBJ_BOOKS || book.sub_type == BOOK_MANUAL) continue; const auto item_spells = spells_in_book(book); if (any_of(item_spells.begin(), item_spells.end(), [&spells](const spell_type st) { return find(spells.begin(), spells.end(), st) != spells.end(); }) && is_useless_item(book, false)) { level_pos pos = thing_pos(thing); // TODO: unreliable? auto thing_indices = find_thing(get_thing_item(thing), pos); indices_to_del.insert(thing_indices.begin(), thing_indices.end()); } } if (!quiet) { for (auto idx : indices_to_del) { ASSERT_RANGE(idx, 0, list->size()); mprf(""Shopping list: removing %s"", describe_thing((*list)[idx], DESC_A).c_str()); } } del_thing_at_indices(indices_to_del); } void ShoppingList::remove_dead_shops() { // Only restore the excursion at the very end. level_excursion le; set shops_to_remove; for (CrawlHashTable &thing : *list) { const level_pos place = thing_pos(thing); le.go_to(place.id); // thereby running DACT_REMOVE_GOZAG_SHOPS const shop_struct *shop = shop_at(place.pos); if (!shop) shops_to_remove.insert(place); } for (auto pos : shops_to_remove) forget_pos(pos); // Prices could have changed. refresh(); } vector ShoppingList::entries() { ASSERT(list); vector list_entries; for (const CrawlHashTable &entry : *list) { list_entries.push_back( make_pair(name_thing(entry), thing_cost(entry)) ); } return list_entries; } int ShoppingList::size() const { ASSERT(list); return list->size(); } bool ShoppingList::items_are_same(const item_def& item_a, const item_def& item_b) { return item_name_simple(item_a) == item_name_simple(item_b); } void ShoppingList::move_things(const coord_def &_src, const coord_def &_dst) { if (crawl_state.map_stat_gen || crawl_state.obj_stat_gen || crawl_state.test) { return; // Shopping list is unitialized and uneeded. } const level_pos src(level_id::current(), _src); const level_pos dst(level_id::current(), _dst); for (CrawlHashTable &thing : *list) if (thing_pos(thing) == src) thing[SHOPPING_THING_POS_KEY] = dst; } void ShoppingList::forget_pos(const level_pos &pos) { if (!crawl_state.need_save) return; // Shopping list is uninitialized and unneeded. for (unsigned int i = 0; i < list->size(); i++) { const CrawlHashTable &thing = (*list)[i]; if (thing_pos(thing) == pos) { list->erase(i); i--; } } // Maybe we just forgot about a shop. refresh(); } void ShoppingList::gold_changed(int old_amount, int new_amount) { ASSERT(list); if (new_amount > old_amount && new_amount >= min_unbuyable_cost) { ASSERT(min_unbuyable_idx < list->size()); vector descs; for (unsigned int i = min_unbuyable_idx; i < list->size(); i++) { const CrawlHashTable &thing = (*list)[i]; const int cost = thing_cost(thing); if (cost > new_amount) { ASSERT(i > (unsigned int) min_unbuyable_idx); break; } string desc; if (thing.exists(SHOPPING_THING_VERB_KEY)) desc += thing[SHOPPING_THING_VERB_KEY].get_string(); else desc = ""buy""; desc += "" ""; desc += describe_thing(thing, DESC_A); descs.push_back(desc); } ASSERT(!descs.empty()); mpr_comma_separated_list(""You now have enough gold to "", descs, "", or ""); mpr(""You can access your shopping list by pressing '$'.""); // Our gold has changed, maybe we can buy different things now. refresh(); } else if (new_amount < old_amount && new_amount < max_buyable_cost) { // As above. refresh(); } } class ShoppingListMenu : public Menu { public: ShoppingListMenu() : Menu(MF_SINGLESELECT | MF_ALLOW_FORMATTING | MF_ARROWS_SELECT | MF_INIT_HOVER) {} bool view_only {false}; string get_keyhelp(bool) const override { string s = make_stringf(""You have %d gold pieces\\n"", you.gold); if (view_only) s += ""Choose to examine item ""; else { s += ""[!] ""; switch (menu_action) { case ACT_EXECUTE: s += ""travel|examine|delete""; break; case ACT_EXAMINE: s += ""travel|examine|delete""; break; default: s += ""travel|examine|delete""; break; } s += "" items ""; } if (items.size() > 0) { // could be dropped if there's ever more interesting hotkeys s += hyphenated_hotkey_letters(items.size(), 'a') + "" choose item""; } return pad_more_with(s, ""[Esc] exit""); } protected: virtual formatted_string calc_title() override; }; formatted_string ShoppingListMenu::calc_title() { formatted_string fs; const int total_cost = you.props[SHOPPING_LIST_COST_KEY]; fs.textcolour(title->colour); fs.cprintf(""Shopping list: %d %s%s, total cost %d gold pieces"", title->quantity, title->text.c_str(), title->quantity > 1 ? ""s"" : """", total_cost); return fs; } /** * Describe the location of a given shopping list entry. * * @param thing A shopping list entry. * @return Something like [Orc:4], probably. */ string ShoppingList::describe_thing_pos(const CrawlHashTable &thing) { return make_stringf(""[%s]"", thing_pos(thing).id.describe().c_str()); } void ShoppingList::fill_out_menu(Menu& shopmenu) { menu_letter hotkey; int longest = 0; // How much space does the longest entry need for proper alignment? for (const CrawlHashTable &thing : *list) longest = max(longest, strwidth(describe_thing_pos(thing))); for (CrawlHashTable &thing : *list) { const int cost = thing_cost(thing); const bool unknown = thing_is_item(thing) && shop_item_unknown(get_thing_item(thing)); const string etitle = make_stringf( ""%*s%5d gold %s%s"", longest, describe_thing_pos(thing).c_str(), cost, name_thing(thing, DESC_A).c_str(), unknown ? "" (unknown)"" : """"); MenuEntry *me = new MenuEntry(etitle, MEL_ITEM, 1, hotkey); me->data = &thing; if (thing_is_item(thing)) { // Colour shopping list item according to menu colours. const item_def &item = get_thing_item(thing); const string colprf = item_prefix(item); const int col = menu_colour(item.name(DESC_A), colprf, ""shop""); vector item_tiles; get_tiles_for_item(item, item_tiles, true); for (const auto &tile : item_tiles) me->add_tile(tile); if (col != -1) me->colour = col; } if (cost > you.gold) me->colour = DARKGREY; shopmenu.add_entry(me); ++hotkey; } } void ShoppingList::display(bool view_only) { if (list->empty()) return; ShoppingListMenu shopmenu; shopmenu.view_only = view_only; shopmenu.set_tag(""shop""); shopmenu.menu_action = view_only ? Menu::ACT_EXAMINE : Menu::ACT_EXECUTE; shopmenu.action_cycle = view_only ? Menu::CYCLE_NONE : Menu::CYCLE_CYCLE; string title = ""item""; MenuEntry *mtitle = new MenuEntry(title, MEL_TITLE); mtitle->quantity = list->size(); shopmenu.set_title(mtitle); fill_out_menu(shopmenu); shopmenu.on_single_selection = [this, &shopmenu, &mtitle](const MenuEntry& sel) { const CrawlHashTable* thing = static_cast(sel.data); const bool is_item = thing_is_item(*thing); if (shopmenu.menu_action == Menu::ACT_EXECUTE) { int cost = thing_cost(*thing); if (cost > you.gold) { string prompt = make_stringf(""Travel to: %s\\nYou cannot afford this item; travel there "" ""anyway? (y/N)"", describe_thing(*thing, DESC_A).c_str()); clrscr(); if (!yesno(prompt.c_str(), true, 'n')) return true; } const level_pos lp(thing_pos(*thing)); start_translevel_travel(lp); return false; } else if (shopmenu.menu_action == Menu::ACT_EXAMINE) { if (is_item) { const item_def &item = get_thing_item(*thing); describe_item_popup(item); } else // not an item, so we only stored a description. { // HACK: Assume it's some kind of portal vault. const string info = make_stringf( ""%s with an entry fee of %d gold pieces."", describe_thing(*thing, DESC_A).c_str(), (int) thing_cost(*thing)); show_description(info.c_str()); } } else if (shopmenu.menu_action == Menu::ACT_MISC) { const int index = shopmenu.get_entry_index(&sel); if (index == -1) { mprf(MSGCH_ERROR, ""ERROR: Unable to delete thing from shopping list!""); more(); return true; } del_thing_at_index(index); mtitle->quantity = this->list->size(); shopmenu.set_title(mtitle); if (this->list->empty()) { mpr(""Your shopping list is now empty.""); return false; } shopmenu.clear(); fill_out_menu(shopmenu); shopmenu.update_menu(true); } else die(""Invalid menu action type""); return true; }; shopmenu.show(); redraw_screen(); update_screen(); } static bool _compare_shopping_things(const CrawlStoreValue& a, const CrawlStoreValue& b) { const CrawlHashTable& hash_a = a.get_table(); const CrawlHashTable& hash_b = b.get_table(); const int a_cost = hash_a[SHOPPING_THING_COST_KEY]; const int b_cost = hash_b[SHOPPING_THING_COST_KEY]; const level_id id_a = hash_a[SHOPPING_THING_POS_KEY].get_level_pos().id; const level_id id_b = hash_b[SHOPPING_THING_POS_KEY].get_level_pos().id; // Put Bazaar items at the top of the shopping list. if (!player_in_branch(BRANCH_BAZAAR) || id_a.branch == id_b.branch) return a_cost < b_cost; else return id_a.branch == BRANCH_BAZAAR; } // Reset max_buyable and min_unbuyable info. Call this anytime any of the // player's gold, the shopping list, and the prices of the items on it // change. void ShoppingList::refresh() { if (!you.props.exists(SHOPPING_LIST_KEY)) you.props[SHOPPING_LIST_KEY].new_vector(SV_HASH, SFLAG_CONST_TYPE); list = &you.props[SHOPPING_LIST_KEY].get_vector(); stable_sort(list->begin(), list->end(), _compare_shopping_things); min_unbuyable_cost = INT_MAX; min_unbuyable_idx = -1; max_buyable_cost = -1; max_buyable_idx = -1; int total_cost = 0; for (unsigned int i = 0; i < list->size(); i++) { const CrawlHashTable &thing = (*list)[i]; const int cost = thing_cost(thing); if (cost <= you.gold) { max_buyable_cost = cost; max_buyable_idx = i; } else if (min_unbuyable_idx == -1) { min_unbuyable_cost = cost; min_unbuyable_idx = i; } total_cost += cost; } you.props[SHOPPING_LIST_COST_KEY].get_int() = total_cost; } unordered_set ShoppingList::find_thing(const item_def &item, const level_pos &pos) const { unordered_set result; for (unsigned int i = 0; i < list->size(); i++) { const CrawlHashTable &thing = (*list)[i]; const level_pos _pos = thing_pos(thing); if (pos != _pos) // TODO: using thing_pos above seems to make this unreliable? continue; if (!thing_is_item(thing)) continue; const item_def &_item = get_thing_item(thing); if (item_name_simple(item) == item_name_simple(_item)) result.insert(i); } return result; } unordered_set ShoppingList::find_thing(const string &desc, const level_pos &pos) const { unordered_set result; for (unsigned int i = 0; i < list->size(); i++) { const CrawlHashTable &thing = (*list)[i]; const level_pos _pos = thing_pos(thing); if (pos != _pos) continue; if (thing_is_item(thing)) continue; if (desc == name_thing(thing)) result.insert(i); } return result; } bool ShoppingList::thing_is_item(const CrawlHashTable& thing) { return thing.exists(SHOPPING_THING_ITEM_KEY); } const item_def& ShoppingList::get_thing_item(const CrawlHashTable& thing) { ASSERT(thing.exists(SHOPPING_THING_ITEM_KEY)); const item_def &item = thing[SHOPPING_THING_ITEM_KEY].get_item(); ASSERT(item.defined()); return item; } string ShoppingList::get_thing_desc(const CrawlHashTable& thing) { ASSERT(thing.exists(SHOPPING_THING_DESC_KEY)); string desc = thing[SHOPPING_THING_DESC_KEY].get_string(); return desc; } int ShoppingList::thing_cost(const CrawlHashTable& thing) { ASSERT(thing.exists(SHOPPING_THING_COST_KEY)); return thing[SHOPPING_THING_COST_KEY].get_int(); } level_pos ShoppingList::thing_pos(const CrawlHashTable& thing) { ASSERT(thing.exists(SHOPPING_THING_POS_KEY)); return thing[SHOPPING_THING_POS_KEY].get_level_pos(); } string ShoppingList::name_thing(const CrawlHashTable& thing, description_level_type descrip) { if (thing_is_item(thing)) { const item_def &item = get_thing_item(thing); return item.name(descrip); } else { string desc = get_thing_desc(thing); return apply_description(descrip, desc); } } string ShoppingList::describe_thing(const CrawlHashTable& thing, description_level_type descrip) { string desc = name_thing(thing, descrip) + "" on ""; const level_pos pos = thing_pos(thing); if (pos.id == level_id::current()) desc += ""this level""; else desc += pos.id.describe(); return desc; } // Item name without inscription. string ShoppingList::item_name_simple(const item_def& item, bool ident) { return item.name(DESC_PLAIN, false, ident, false, false); } ",16240,False,2443.7700967638893,median "= v1.EgressNetworkPolicy {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] EgressNetworkPolicy describes the current egress network policy for a Namespace. When using the 'redhat/openshift-ovs-multitenant' network plugin, traffic from a pod to an IP address outside the cluster will be checked against each EgressNetworkPolicyRule in the pod's namespace's EgressNetworkPolicy, in order. If no rule matches (or no EgressNetworkPolicy is present) then the traffic will be allowed by default. == Object Schema Expand or mouse-over a field for more information about it. ++++

apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
spec:
egress:
- to:
- cidrSelector:
dnsName:
type:
++++ == Operations [[Post-oapi-v1-namespaces-namespace-egressnetworkpolicies]] === Create a EgressNetworkPolicy in a namespace Create an EgressNetworkPolicy ==== HTTP request ---- POST /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies <<'EOF' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.EgressNetworkPolicy |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicy |201 Created|v1.EgressNetworkPolicy |202 Accepted|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-oapi-v1-namespaces-namespace-egressnetworkpolicies-name]] === Get a EgressNetworkPolicy in a namespace Read the specified EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-oapi-v1-egressnetworkpolicies]] === Get all EgressNetworkPolicies List or watch objects of kind EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/oapi/v1/egressnetworkpolicies ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicyList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-oapi-v1-namespaces-namespace-egressnetworkpolicies]] === Get all EgressNetworkPolicies in a namespace List or watch objects of kind EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicyList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-oapi-v1-watch-namespaces-namespace-egressnetworkpolicies-name]] === Watch a EgressNetworkPolicy in a namespace Watch changes to an object of kind EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/oapi/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-oapi-v1-watch-egressnetworkpolicies]] === Watch all EgressNetworkPolicies Watch individual changes to a list of EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/watch/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/oapi/v1/watch/egressnetworkpolicies ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-oapi-v1-watch-namespaces-namespace-egressnetworkpolicies]] === Watch all EgressNetworkPolicies in a namespace Watch individual changes to a list of EgressNetworkPolicy ==== HTTP request ---- GET /oapi/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/oapi/v1/watch/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-oapi-v1-namespaces-namespace-egressnetworkpolicies-name]] === Update a EgressNetworkPolicy in a namespace Replace the specified EgressNetworkPolicy ==== HTTP request ---- PUT /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME <<'EOF' { ""kind"": ""EgressNetworkPolicy"", ""apiVersion"": ""v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.EgressNetworkPolicy |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicy |201 Created|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-oapi-v1-namespaces-namespace-egressnetworkpolicies-name]] === Patch a EgressNetworkPolicy in a namespace Partially update the specified EgressNetworkPolicy ==== HTTP request ---- PATCH /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.EgressNetworkPolicy |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-oapi-v1-namespaces-namespace-egressnetworkpolicies-name]] === Delete a EgressNetworkPolicy in a namespace Delete an EgressNetworkPolicy ==== HTTP request ---- DELETE /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the EgressNetworkPolicy |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-oapi-v1-namespaces-namespace-egressnetworkpolicies]] === Delete all EgressNetworkPolicies in a namespace Delete collection of EgressNetworkPolicy ==== HTTP request ---- DELETE /oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/oapi/v1/namespaces/$NAMESPACE/egressnetworkpolicies ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",12079,False,2410.4731784790088,median "#pragma once #include namespace Kvasir { //DMA controller namespace Dma2Lisr{ ///; ///Stream x transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation tcif3{}; ///Stream x half transfer interrupt flag (x=3..0) constexpr Register::FieldLocation htif3{}; ///Stream x transfer error interrupt flag (x=3..0) constexpr Register::FieldLocation teif3{}; ///Stream x direct mode error interrupt flag (x=3..0) constexpr Register::FieldLocation dmeif3{}; ///Stream x FIFO error interrupt flag (x=3..0) constexpr Register::FieldLocation feif3{}; ///Stream x transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation tcif2{}; ///Stream x half transfer interrupt flag (x=3..0) constexpr Register::FieldLocation htif2{}; ///Stream x transfer error interrupt flag (x=3..0) constexpr Register::FieldLocation teif2{}; ///Stream x direct mode error interrupt flag (x=3..0) constexpr Register::FieldLocation dmeif2{}; ///Stream x FIFO error interrupt flag (x=3..0) constexpr Register::FieldLocation feif2{}; ///Stream x transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation tcif1{}; ///Stream x half transfer interrupt flag (x=3..0) constexpr Register::FieldLocation htif1{}; ///Stream x transfer error interrupt flag (x=3..0) constexpr Register::FieldLocation teif1{}; ///Stream x direct mode error interrupt flag (x=3..0) constexpr Register::FieldLocation dmeif1{}; ///Stream x FIFO error interrupt flag (x=3..0) constexpr Register::FieldLocation feif1{}; ///Stream x transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation tcif0{}; ///Stream x half transfer interrupt flag (x=3..0) constexpr Register::FieldLocation htif0{}; ///Stream x transfer error interrupt flag (x=3..0) constexpr Register::FieldLocation teif0{}; ///Stream x direct mode error interrupt flag (x=3..0) constexpr Register::FieldLocation dmeif0{}; ///Stream x FIFO error interrupt flag (x=3..0) constexpr Register::FieldLocation feif0{}; } namespace Dma2Hisr{ ///; ///Stream x transfer complete interrupt flag (x=7..4) constexpr Register::FieldLocation tcif7{}; ///Stream x half transfer interrupt flag (x=7..4) constexpr Register::FieldLocation htif7{}; ///Stream x transfer error interrupt flag (x=7..4) constexpr Register::FieldLocation teif7{}; ///Stream x direct mode error interrupt flag (x=7..4) constexpr Register::FieldLocation dmeif7{}; ///Stream x FIFO error interrupt flag (x=7..4) constexpr Register::FieldLocation feif7{}; ///Stream x transfer complete interrupt flag (x=7..4) constexpr Register::FieldLocation tcif6{}; ///Stream x half transfer interrupt flag (x=7..4) constexpr Register::FieldLocation htif6{}; ///Stream x transfer error interrupt flag (x=7..4) constexpr Register::FieldLocation teif6{}; ///Stream x direct mode error interrupt flag (x=7..4) constexpr Register::FieldLocation dmeif6{}; ///Stream x FIFO error interrupt flag (x=7..4) constexpr Register::FieldLocation feif6{}; ///Stream x transfer complete interrupt flag (x=7..4) constexpr Register::FieldLocation tcif5{}; ///Stream x half transfer interrupt flag (x=7..4) constexpr Register::FieldLocation htif5{}; ///Stream x transfer error interrupt flag (x=7..4) constexpr Register::FieldLocation teif5{}; ///Stream x direct mode error interrupt flag (x=7..4) constexpr Register::FieldLocation dmeif5{}; ///Stream x FIFO error interrupt flag (x=7..4) constexpr Register::FieldLocation feif5{}; ///Stream x transfer complete interrupt flag (x=7..4) constexpr Register::FieldLocation tcif4{}; ///Stream x half transfer interrupt flag (x=7..4) constexpr Register::FieldLocation htif4{}; ///Stream x transfer error interrupt flag (x=7..4) constexpr Register::FieldLocation teif4{}; ///Stream x direct mode error interrupt flag (x=7..4) constexpr Register::FieldLocation dmeif4{}; ///Stream x FIFO error interrupt flag (x=7..4) constexpr Register::FieldLocation feif4{}; } namespace Dma2Lifcr{ ///; ///Stream x clear transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation ctcif3{}; ///Stream x clear half transfer interrupt flag (x = 3..0) constexpr Register::FieldLocation chtif3{}; ///Stream x clear transfer error interrupt flag (x = 3..0) constexpr Register::FieldLocation cteif3{}; ///Stream x clear direct mode error interrupt flag (x = 3..0) constexpr Register::FieldLocation cdmeif3{}; ///Stream x clear FIFO error interrupt flag (x = 3..0) constexpr Register::FieldLocation cfeif3{}; ///Stream x clear transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation ctcif2{}; ///Stream x clear half transfer interrupt flag (x = 3..0) constexpr Register::FieldLocation chtif2{}; ///Stream x clear transfer error interrupt flag (x = 3..0) constexpr Register::FieldLocation cteif2{}; ///Stream x clear direct mode error interrupt flag (x = 3..0) constexpr Register::FieldLocation cdmeif2{}; ///Stream x clear FIFO error interrupt flag (x = 3..0) constexpr Register::FieldLocation cfeif2{}; ///Stream x clear transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation ctcif1{}; ///Stream x clear half transfer interrupt flag (x = 3..0) constexpr Register::FieldLocation chtif1{}; ///Stream x clear transfer error interrupt flag (x = 3..0) constexpr Register::FieldLocation cteif1{}; ///Stream x clear direct mode error interrupt flag (x = 3..0) constexpr Register::FieldLocation cdmeif1{}; ///Stream x clear FIFO error interrupt flag (x = 3..0) constexpr Register::FieldLocation cfeif1{}; ///Stream x clear transfer complete interrupt flag (x = 3..0) constexpr Register::FieldLocation ctcif0{}; ///Stream x clear half transfer interrupt flag (x = 3..0) constexpr Register::FieldLocation chtif0{}; ///Stream x clear transfer error interrupt flag (x = 3..0) constexpr Register::FieldLocation cteif0{}; ///Stream x clear direct mode error interrupt flag (x = 3..0) constexpr Register::FieldLocation cdmeif0{}; ///Stream x clear FIFO error interrupt flag (x = 3..0) constexpr Register::FieldLocation cfeif0{}; } namespace Dma2Hifcr{ ///; ///Stream x clear transfer complete interrupt flag (x = 7..4) constexpr Register::FieldLocation ctcif7{}; ///Stream x clear half transfer interrupt flag (x = 7..4) constexpr Register::FieldLocation chtif7{}; ///Stream x clear transfer error interrupt flag (x = 7..4) constexpr Register::FieldLocation cteif7{}; ///Stream x clear direct mode error interrupt flag (x = 7..4) constexpr Register::FieldLocation cdmeif7{}; ///Stream x clear FIFO error interrupt flag (x = 7..4) constexpr Register::FieldLocation cfeif7{}; ///Stream x clear transfer complete interrupt flag (x = 7..4) constexpr Register::FieldLocation ctcif6{}; ///Stream x clear half transfer interrupt flag (x = 7..4) constexpr Register::FieldLocation chtif6{}; ///Stream x clear transfer error interrupt flag (x = 7..4) constexpr Register::FieldLocation cteif6{}; ///Stream x clear direct mode error interrupt flag (x = 7..4) constexpr Register::FieldLocation cdmeif6{}; ///Stream x clear FIFO error interrupt flag (x = 7..4) constexpr Register::FieldLocation cfeif6{}; ///Stream x clear transfer complete interrupt flag (x = 7..4) constexpr Register::FieldLocation ctcif5{}; ///Stream x clear half transfer interrupt flag (x = 7..4) constexpr Register::FieldLocation chtif5{}; ///Stream x clear transfer error interrupt flag (x = 7..4) constexpr Register::FieldLocation cteif5{}; ///Stream x clear direct mode error interrupt flag (x = 7..4) constexpr Register::FieldLocation cdmeif5{}; ///Stream x clear FIFO error interrupt flag (x = 7..4) constexpr Register::FieldLocation cfeif5{}; ///Stream x clear transfer complete interrupt flag (x = 7..4) constexpr Register::FieldLocation ctcif4{}; ///Stream x clear half transfer interrupt flag (x = 7..4) constexpr Register::FieldLocation chtif4{}; ///Stream x clear transfer error interrupt flag (x = 7..4) constexpr Register::FieldLocation cteif4{}; ///Stream x clear direct mode error interrupt flag (x = 7..4) constexpr Register::FieldLocation cdmeif4{}; ///Stream x clear FIFO error interrupt flag (x = 7..4) constexpr Register::FieldLocation cfeif4{}; } namespace Dma2S0cr{ ///; ///Channel selection constexpr Register::FieldLocation chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation pburst{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation ct{}; ///Double buffer mode constexpr Register::FieldLocation dbm{}; ///Priority level constexpr Register::FieldLocation pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation pincos{}; ///Memory data size constexpr Register::FieldLocation msize{}; ///Peripheral data size constexpr Register::FieldLocation psize{}; ///Memory increment mode constexpr Register::FieldLocation minc{}; ///Peripheral increment mode constexpr Register::FieldLocation pinc{}; ///Circular mode constexpr Register::FieldLocation circ{}; ///Data transfer direction constexpr Register::FieldLocation dir{}; ///Peripheral flow controller constexpr Register::FieldLocation pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation en{}; } namespace Dma2S0ndtr{ ///; ///Number of data items to transfer constexpr Register::FieldLocation ndt{}; } namespace Dma2S0par{ ///; ///Peripheral address constexpr Register::FieldLocation pa{}; } namespace Dma2S0m0ar{ ///; ///Memory 0 address constexpr Register::FieldLocation m0a{}; } namespace Dma2S0m1ar{ ///; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation m1a{}; } namespace Dma2S0fcr{ ///; ///FIFO error interrupt enable constexpr Register::FieldLocation feie{}; ///FIFO status constexpr Register::FieldLocation,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation fth{}; } namespace Dma2S1cr{ ///; ///Channel selection constexpr Register::FieldLocation chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation pburst{}; ///ACK constexpr Register::FieldLocation ack{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation ct{}; ///Double buffer mode constexpr Register::FieldLocation dbm{}; ///Priority level constexpr Register::FieldLocation pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation pincos{}; ///Memory data size constexpr Register::FieldLocation msize{}; ///Peripheral data size constexpr Register::FieldLocation psize{}; ///Memory increment mode constexpr Register::FieldLocation minc{}; ///Peripheral increment mode constexpr Register::FieldLocation pinc{}; ///Circular mode constexpr Register::FieldLocation circ{}; ///Data transfer direction constexpr Register::FieldLocation dir{}; ///Peripheral flow controller constexpr Register::FieldLocation pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation en{}; } namespace Dma2S1ndtr{ ///; ///Number of data items to transfer constexpr Register::FieldLocation ndt{}; } namespace Dma2S1par{ ///; ///Peripheral address constexpr Register::FieldLocation pa{}; } namespace Dma2S1m0ar{ ///; ///Memory 0 address constexpr Register::FieldLocation m0a{}; } namespace Dma2S1m1ar{ ///; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation m1a{}; } namespace Dma2S1fcr{ ///; ///FIFO error interrupt enable constexpr Register::FieldLocation feie{}; ///FIFO status constexpr Register::FieldLocation,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation fth{}; } namespace Dma2S2cr{ ///; ///Channel selection constexpr Register::FieldLocation chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation pburst{}; ///ACK constexpr Register::FieldLocation ack{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation ct{}; ///Double buffer mode constexpr Register::FieldLocation dbm{}; ///Priority level constexpr Register::FieldLocation pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation pincos{}; ///Memory data size constexpr Register::FieldLocation msize{}; ///Peripheral data size constexpr Register::FieldLocation psize{}; ///Memory increment mode constexpr Register::FieldLocation minc{}; ///Peripheral increment mode constexpr Register::FieldLocation pinc{}; ///Circular mode constexpr Register::FieldLocation circ{}; ///Data transfer direction constexpr Register::FieldLocation dir{}; ///Peripheral flow controller constexpr Register::FieldLocation pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation en{}; } namespace Dma2S2ndtr{ ///; ///Number of data items to transfer constexpr Register::FieldLocation ndt{}; } namespace Dma2S2par{ ///; ///Peripheral address constexpr Register::FieldLocation pa{}; } namespace Dma2S2m0ar{ ///; ///Memory 0 address constexpr Register::FieldLocation m0a{}; } namespace Dma2S2m1ar{ ///; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation m1a{}; } namespace Dma2S2fcr{ ///; ///FIFO error interrupt enable constexpr Register::FieldLocation feie{}; ///FIFO status constexpr Register::FieldLocation,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation fth{}; } namespace Dma2S3cr{ ///; ///Channel selection constexpr Register::FieldLocation chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation pburst{}; ///ACK constexpr Register::FieldLocation ack{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation ct{}; ///Double buffer mode constexpr Register::FieldLocation dbm{}; ///Priority level constexpr Register::FieldLocation pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation pincos{}; ///Memory data size constexpr Register::FieldLocation msize{}; ///Peripheral data size constexpr Register::FieldLocation psize{}; ///Memory increment mode constexpr Register::FieldLocation minc{}; ///Peripheral increment mode constexpr Register::FieldLocation pinc{}; ///Circular mode constexpr Register::FieldLocation circ{}; ///Data transfer direction constexpr Register::FieldLocation dir{}; ///Peripheral flow controller constexpr Register::FieldLocation pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation en{}; } namespace Dma2S3ndtr{ ///; ///Number of data items to transfer constexpr Register::FieldLocation ndt{}; } namespace Dma2S3par{ ///; ///Peripheral address constexpr Register::FieldLocation pa{}; } namespace Dma2S3m0ar{ ///; ///Memory 0 address constexpr Register::FieldLocation m0a{}; } namespace Dma2S3m1ar{ ///; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation m1a{}; } namespace Dma2S3fcr{ ///; ///FIFO error interrupt enable constexpr Register::FieldLocation feie{}; ///FIFO status constexpr Register::FieldLocation,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation fth{}; } namespace Dma2S4cr{ ///; ///Channel selection constexpr Register::FieldLocation chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation pburst{}; ///ACK constexpr Register::FieldLocation ack{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation ct{}; ///Double buffer mode constexpr Register::FieldLocation dbm{}; ///Priority level constexpr Register::FieldLocation pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation pincos{}; ///Memory data size constexpr Register::FieldLocation msize{}; ///Peripheral data size constexpr Register::FieldLocation psize{}; ///Memory increment mode constexpr Register::FieldLocation minc{}; ///Peripheral increment mode constexpr Register::FieldLocation pinc{}; ///Circular mode constexpr Register::FieldLocation circ{}; ///Data transfer direction constexpr Register::FieldLocation dir{}; ///Peripheral flow controller constexpr Register::FieldLocation pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation en{}; } namespace Dma2S4ndtr{ ///; ///Number of data items to transfer constexpr Register::FieldLocation ndt{}; } namespace Dma2S4par{ ///; ///Peripheral address constexpr Register::FieldLocation pa{}; } namespace Dma2S4m0ar{ ///; ///Memory 0 address constexpr Register::FieldLocation m0a{}; } namespace Dma2S4m1ar{ ///; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation m1a{}; } namespace Dma2S4fcr{ ///; ///FIFO error interrupt enable constexpr Register::FieldLocation feie{}; ///FIFO status constexpr Register::FieldLocation,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation fth{}; } namespace Dma2S5cr{ ///; ///Channel selection constexpr Register::FieldLocation chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation pburst{}; ///ACK constexpr Register::FieldLocation ack{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation ct{}; ///Double buffer mode constexpr Register::FieldLocation dbm{}; ///Priority level constexpr Register::FieldLocation pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation pincos{}; ///Memory data size constexpr Register::FieldLocation msize{}; ///Peripheral data size constexpr Register::FieldLocation psize{}; ///Memory increment mode constexpr Register::FieldLocation minc{}; ///Peripheral increment mode constexpr Register::FieldLocation pinc{}; ///Circular mode constexpr Register::FieldLocation circ{}; ///Data transfer direction constexpr Register::FieldLocation dir{}; ///Peripheral flow controller constexpr Register::FieldLocation pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation en{}; } namespace Dma2S5ndtr{ ///; ///Number of data items to transfer constexpr Register::FieldLocation ndt{}; } namespace Dma2S5par{ ///; ///Peripheral address constexpr Register::FieldLocation pa{}; } namespace Dma2S5m0ar{ ///; ///Memory 0 address constexpr Register::FieldLocation m0a{}; } namespace Dma2S5m1ar{ ///; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation m1a{}; } namespace Dma2S5fcr{ ///; ///FIFO error interrupt enable constexpr Register::FieldLocation feie{}; ///FIFO status constexpr Register::FieldLocation,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation fth{}; } namespace Dma2S6cr{ ///; ///Channel selection constexpr Register::FieldLocation chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation pburst{}; ///ACK constexpr Register::FieldLocation ack{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation ct{}; ///Double buffer mode constexpr Register::FieldLocation dbm{}; ///Priority level constexpr Register::FieldLocation pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation pincos{}; ///Memory data size constexpr Register::FieldLocation msize{}; ///Peripheral data size constexpr Register::FieldLocation psize{}; ///Memory increment mode constexpr Register::FieldLocation minc{}; ///Peripheral increment mode constexpr Register::FieldLocation pinc{}; ///Circular mode constexpr Register::FieldLocation circ{}; ///Data transfer direction constexpr Register::FieldLocation dir{}; ///Peripheral flow controller constexpr Register::FieldLocation pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation en{}; } namespace Dma2S6ndtr{ ///; ///Number of data items to transfer constexpr Register::FieldLocation ndt{}; } namespace Dma2S6par{ ///; ///Peripheral address constexpr Register::FieldLocation pa{}; } namespace Dma2S6m0ar{ ///; ///Memory 0 address constexpr Register::FieldLocation m0a{}; } namespace Dma2S6m1ar{ ///; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation m1a{}; } namespace Dma2S6fcr{ ///; ///FIFO error interrupt enable constexpr Register::FieldLocation feie{}; ///FIFO status constexpr Register::FieldLocation,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation fth{}; } namespace Dma2S7cr{ ///; ///Channel selection constexpr Register::FieldLocation chsel{}; ///Memory burst transfer configuration constexpr Register::FieldLocation mburst{}; ///Peripheral burst transfer configuration constexpr Register::FieldLocation pburst{}; ///ACK constexpr Register::FieldLocation ack{}; ///Current target (only in double buffer mode) constexpr Register::FieldLocation ct{}; ///Double buffer mode constexpr Register::FieldLocation dbm{}; ///Priority level constexpr Register::FieldLocation pl{}; ///Peripheral increment offset size constexpr Register::FieldLocation pincos{}; ///Memory data size constexpr Register::FieldLocation msize{}; ///Peripheral data size constexpr Register::FieldLocation psize{}; ///Memory increment mode constexpr Register::FieldLocation minc{}; ///Peripheral increment mode constexpr Register::FieldLocation pinc{}; ///Circular mode constexpr Register::FieldLocation circ{}; ///Data transfer direction constexpr Register::FieldLocation dir{}; ///Peripheral flow controller constexpr Register::FieldLocation pfctrl{}; ///Transfer complete interrupt enable constexpr Register::FieldLocation tcie{}; ///Half transfer interrupt enable constexpr Register::FieldLocation htie{}; ///Transfer error interrupt enable constexpr Register::FieldLocation teie{}; ///Direct mode error interrupt enable constexpr Register::FieldLocation dmeie{}; ///Stream enable / flag stream ready when read low constexpr Register::FieldLocation en{}; } namespace Dma2S7ndtr{ ///; ///Number of data items to transfer constexpr Register::FieldLocation ndt{}; } namespace Dma2S7par{ ///; ///Peripheral address constexpr Register::FieldLocation pa{}; } namespace Dma2S7m0ar{ ///; ///Memory 0 address constexpr Register::FieldLocation m0a{}; } namespace Dma2S7m1ar{ ///; ///Memory 1 address (used in case of Double buffer mode) constexpr Register::FieldLocation m1a{}; } namespace Dma2S7fcr{ ///; ///FIFO error interrupt enable constexpr Register::FieldLocation feie{}; ///FIFO status constexpr Register::FieldLocation,unsigned> fs{}; ///Direct mode disable constexpr Register::FieldLocation dmdis{}; ///FIFO threshold selection constexpr Register::FieldLocation fth{}; } } ",16197,True,5137.126212575614,median "= Kaui User Guide - DRAFT, PARTIAL © 2022 The Billing Project, LLC :doctype: book :revlevel: 1.0 :revdate: Jan 2022 :revremarks: first draft :toc: :toclevels: 3 :figure-caption!: :icons: font :imagesdir: https://github.com/killbill/killbill-docs/raw/v3/userguide/assets/img/kaui //Formal location - https://github.com/killbill/killbill-docs/raw/v3/userguide/assets/img/kaui //Mary's directory - C:\\_My Documents\\FlowWritingLLC\\Projects\\Kill Bill\\Documentation\\killbill-docs\\userguide\\assets\\img\\kaui //DINAH'S IMAGES //https://drive.google.com/drive/folders==/1gmtaGIc2d9MGrgRYPfrZRIAZO3UfnCU3 //Ruby30-x64 //Command to convert to PDF: //Asciidoctor-pdf ""C:/_My Documents/FlowWritingLLC/Projects/Kill Bill/Documentation/killbill-docs/userguide/kaui/Kaui_Guide_Draft.adoc"" //RESOURCES //https://asciidoctor.org/ //https://github.com/asciidoctor/asciidoctor.org/blob/main/docs/asciidoc-writers-guide.adoc //https://docs.asciidoctor.org/asciidoc/latest/syntax-quick-reference/ //https://github.com/asciidoctor/asciidoctor-pdf/tree/main#readme //https://github.com/asciidoctor/asciidoctor-pdf/blob/main/docs/theming-guide.adoc#keys-extends == How to Use This Guide <> explains how to *navigate* in Kaui and its *basic interface features*. <> explains how to perform the basic tasks for administering *customer accounts*, such as creating accounts, invoices, and so forth. It’s appropriate for back office staff, such as those working in customer service, product management, and finance. <> explains how to create and manage *users* as well as *users roles* and *permissions*. It’s appropriate for Kill Bill administrators and software developers. Advanced features are covered in Parts 4 - 6: * <> * <> * <> The <> are great for *basic questions* like, _How do I create an invoice?_ === About Screenshots The screenshots displayed in this guide may differ from what you see on your Kaui screen. That's because your user permissions control what features you can access (i.e., what you see on the screen). If you have any questions about why your Kaui screen doesn't match what you see in this guide, ask your Kaui administrator. == Other Learning Resources === Videos We regularly add new overviews and tutorials to https://www.youtube.com/c/KillbillIoOSS[our YouTube videos], so check in from time to time. [glossary] === Glossary The terms listed below are used frequently in this guide. We've provided an abbreviated description below. For a full description, see the https://docs.killbill.io/latest/Kill-Bill-Glossary.html[_Kill Bill Glossary_]. Account (a.k.a. customer account):: A record that contains details about the customer (name, address, etc.). Child:: An account that is associated with a parent account. External Key:: An alternative unique ID for an object. Parent:: An account that contains one or more child accounts. Payment Method:: A record of the details required for Kill Bill to trigger a payment. Plan:: Define how much a customer pays for a product and the frequency of the payment. Plugin:: Software that runs alongside Kill Bill in order to provide additional functionality. Phase (a.k.a plan phase):: Time periods within a subscription during which certain rules apply. Subscription:: A contract between you (the business) and a customer that associates an account with a plan and a specific start date. Tag:: A property that can be added to an object (for example, an account or a subscription) for information purposes or to affect the behavior of the system. Tenant:: The division or organization that is using Kill Bill as a group of users. Note that an organization can have more than one tenant, as Kill Bill supports multitenancy. User:: A person who logs on to use Kaui. == Part 1 - Navigation and Interface [[part_1_navigation_and_interface]] === What Is Kaui? ""Kaui"" (KAUI) stands for Kill (Bill) Admin User Interface. This self-contained web application interacts with Kill Bill over HTTPS. Backoffice staff (for example, Support or Finance) will find Kaui useful to process refunds, credits, chargebacks, and so forth. Kaui also enables the Kill Bill administrator to perform more advanced tasks, such as managing tags, deploying plugins, and configuring the tenant(s). Other types of users who might find Kaui useful are developers (for testing), operations, and product managers. [NOTE] *Note:* For Developers: Kaui functionality is provided via a series of Ruby on Rails mountable engines. You can extend its functionality (for example, to provide a custom UI for your plugins) by mounting your own engine(s). === What You Can Do in Kaui In Kaui, users can perform basic tasks, such as: * Create a customer account * Generate a customer invoice * Cancel a subscription However, Kaui can also help advanced users perform tasks, for example: * Adding a plugin to Kill Bill * Managing Kill Bill users * Creating tags or custom fields These are just a handful of the tasks you can accomplish with Kaui. For a full list, see the _Table of Contents_ at the beginning of this guide. === Sign In and Sign Out [[log_in_and_log_out]] To sign in to Kaui, type in your username and password, then select the *Sign In* button. image::LoginScreen.png[width=650,align=""center""] If your organization uses more than one Kill Bill tenant, select the tenant from the dropdown and select the *Save* button: image::ChooseTenant.png[width=650,align=""center""] [NOTE] *Note:* Authentication is handled by Kill Bill. The method your organization uses to manage users is highly configurable. For information on managing users and permissions, see <>. To log out of Kaui, select *SIGN OUT* in the upper right corner of the Kill Bill homepage: image::SignOut-Labeled.png[width=650,align=""center""] === Navigate This section gets you familiar with the standard features of Kaui's user interface, such as: * <> * <> * <> * <> * <> ==== Homepage Layout The homepage is the screen that Kaui displays after you first log in. image::Homepage-Labeled.png[width=650,align=""center""] 1. <> 2. <> 3. <> _Not yet documented._ 4. <> _Not yet documented._ 5. <> <> _Not yet documented._ 6. Username / Tenant name and <> 7. Latest invoices, accounts, and payments (latest records created for this tenant) 8. This is Killian, the Kill Bill mascot! ==== Return to Homepage From any screen in Kill Bill, you can return to the homepage by clicking the logo in the upper left corner: image::killbill_logo_LARGER.png[width=200,align=""center""] ==== Icons [cols=""^1,3""] |=== ^|Icon ^|Description |image:i_PlusGreen.png[] |Add—Indicates you can add an item, such as a payment method, credit, charge, etc. |image:i_InvoiceGen.png[] |Dry-run invoice—Appears on the Account page. Clicking it manually triggers a committed or dry-run invoice. |image:i_DownArrow.png[] |Expand—Expand a section or dropdown menu. |image:i_UpArrow.png[] |Collapse—Collapse a section. |image:i_Tag.png[] |Tags—_Admin-level feature:_ On the home page, click to access Tags, Tag Definitions, and Custom Fields. _All users:_ In other locations in Kaui, click to select a tag to apply to the current object (for example, an account). |image:i_Plug.png[] |Kaui Package Manager—Appears at the top of the screen and gives you access to plugin specific screens. (Also known as Kill Bill Plugin Manager.) |image:i_Addon.png[] |Add-on—Appears on the Subscription screen and lets you add an add-on to the account's subscription. |image:i_CreditCard.png[] |Make a payment—Appears on the Invoice screen and lets you make a payment against the invoice. |image:i_Gears.png[] |Users, Tenants, & Admin—_Admin level feature:_ Appears at the top of the screen and gives you access to Users, Tenants, and Admin. |image:i_Refresh.png[] |Appears in the Payment Methods section of the Account page, clicking the Refresh icon triggers a refresh for each payment plugin installed in Kill Bill, for that account. When you refresh a payment method, Kill Bill retrieves the latest payment information from where it's stored (for example, from Stripe or another payment gateway). *Note:* This icon does not display if the only payment method listed is `EXTERNAL_PAYMENT`. |=== ==== Grids/Tables [[grids_tables]] Grids (also referred to as _tables_) appear throughout Kaui to keep lists organized: image::GridSample.png[align=""center""] For very large grids, use the pagination controls to view different ""pages:"" image::PaginationControls.png[80,500,align=""center""] [%unbreakable] -- To sort columns on a grid, click the up/down arrow in that column's header: image::ShowSortArrowsOnColumn.png[width=650,align=""center""] -- Kaui shows you which column is currently sorted by the purple arrow: image::ShowSortByColumn.png[width=650,align=""center""] The direction of the arrow (up or down) indicates if the column is sorted in ascending or descending order. If relevant, you can click a link in the grid to view that item's detail. For example, on the Invoices grid, click the link to open that specific invoice: image::ClickToViewDetail.png[width=650,align=""center""] ==== Basic Search [TIP] *Tip:* To view all accounts, place your cursor in the search field and press the Enter key. To search for customer accounts, use the basic search. Basic search is available at the top of the screen no matter where you are in Kaui. image::ShowTopSearch.png[width=650,align=""center""] [%unbreakable] -- You can search for an account using the following criteria: * Account ID * External key * Name * Email address -- Basic search is also available in the center of the *homepage*: image::ShowSearchHomepage.png[width=650,align=""center""] ==== Advanced Search An advanced search can help you find account information as well as other types of objects in the system: * Bundle * Credit * Custom field * Invoice * Invoice payment * Payment * Subscription * Tag * Tag definition * Transaction To perform an advanced search: 1. On the homepage, click *Advanced search:* image::ShowAdvancedSearch.png[width=650,align=""center""] Kaui displays the Advanced Search pop-up: image::AdvancedSearchPopup.png[width=450,align=""center""] [start=2] . In the *Object type* field, select the object type you want to search for: image::AdvSearch-ObjectTypeDropdown.png[width=450,align=""center""] [NOTE] *Note:* For information on which fields are searched for each object type, see the table in the next section. [start=3] . In the *Search for* field, enter the identifier (ID) of the object you're searching for. (_Example:_ If you're searching for a specific invoice, type in the invoice number.) [start=4] . If you want Kaui to search and display the first record in the search results, click the *Fast search* checkbox. . Click the *Search* button. Kaui displays the search results. [TIP] *Tip:* At the bottom of the Advanced Search pop-up, Kaui displays the search syntax. You can copy and paste this advanced search syntax into a basic search field. This is helpful if you frequently perform the same kinds of advanced searches. For example: image::AdvancedSearchSyntax-Labeled.png[] ==== Searchable Fields by Object Type [cols=""1,3""] |=== ^|Object Type ^|Searchable Fields |Account |account ID, name, email, company name, external key |Bundle |account ID, bundle ID, external key |Credit |invoice item ID |Custom field |custom field ID, field name, field value, object type |Invoice |invoice number, invoice ID, account ID, currency |Invoice payment |payment ID |Payment |payment ID, external key |Payment method |payment method ID, external key |Subscription |subscription ID, external key |Tag |tag ID |Tag definition |tag fefinition ID |Transaction |transaction ID, external key |=== //________________________________________________// == Part 2 - Accounts [[part_2_accounts]] This section helps you become familiar with customer accounts and the layout of the Account page. The Account page provides information about a specific customer, such as email address, physical address, and so forth. It is also the central location for the customer's billing information, subscriptions, invoices, and payment methods. To find a customer in the system, use <> or <>. To open the customer account, click the customer ID in the search results. The next section explains how the Account page is laid out. To skip this and see the task-based steps, go to <>. === Account Page Layout The Account page has the following sections: 1. Sub-menu 2. Account information 3. Billing info 4. Personal info 5. Payment methods image::AccountPage_Labeled.png[] [%unbreakable] -- *1. Account Sub-Menu* The *Account* sub-menu organizes and provides access to different areas of the customer's account: * Subscriptions * Invoices * Payments * Timeline * Tags * Custom Fields -- image::Account-Submenu.png[width=650,align=""center""] To see these areas, click the relevant item on the sub-menu. To return to the customer's Account page, click *Account* on the sub-menu. *2. Account Information* This section of the screen displays a summary of the customer's account information, such as their ID, currency, and time zone. To edit this information, click *Edit* next to Account Information. Here you can perform the following tasks for the customer account: * <> * <> * <> *3. Personal Information* This section of the screen displays the customer's personal contact information (read only). By default, Personal Information details are hidden for GDPR Compliance and customer privacy. To see the information, click *Show/Hide Content*. To edit this information, see the <> section. *4. Billing Info* Here you can perform the following tasks for the customer: * <> * Add a credit * Create a charge //LINK THE ABOVE LATER You can also see a summary of billing information: [cols=""1,3""] |=== ^|Field ^|Description |Account balance |Amount of money due on the account, including any account credits. |Account credit |Amount of any money owed to the customer. |Overdue status |The status of the customer's account that indicates if they are overdue or up-to-date on their invoice payments. *Note:* The account can have a negative account balance, but not be overdue. That's because overdue status depends on invoice due dates and how late payments are defined based on a company's business policy. For example, an invoice may not be overdue if a company allows a 15-day grace period (a.k.a. NET terms) to make a payment. |Bill cycle day (BCD) |The day of the month on which the system generates an invoice for this account. This field applies to accounts that are subscribed to monthly subscriptions (or a multiple of monthly, such as quarterly, annually, etc.). For more information, see the <> table. |Next invoice date |The date on which the system generates the customer's next invoice. |=== The *Trigger invoice generation* feature lets you generate an invoice, either as a test or in a committed state. *5. Payment Methods* This section of the Account page lets you: * <<_add_payment_method,Add a payment method>> * <<_set_a_payment_method_as_the_default,Set a payment method as default>> * <<_delete_payment_method,Delete a payment method>> * <<_applying_transactions_to_a_payment_method,Apply a transaction to a payment method (authorize, charge, credit, etc.)>> For more information on payment methods, see the <<_payment_methods>> section. === Create an Account 1. At the top right of the screen, click *Create New Account*: image::CreateNewAccount-Labeled.png[width=650,align=""center""] [start=2] . Kaui opens the Add New Account screen: image::AddNewAccount.png[width=550,align=""center""] [start=3] . Fill in the fields. For field descriptions, see <>. . Click the *Save* button. <<< ==== Account Field Descriptions [cols=""1,3""] |=== ^|Field ^|Description |Name |The customer's first and last name. |First name length |This field sets the length of the customer's first name. Kill Bill automatically calculates this number based on the location of the space between the first and last name. You can overwrite it with a different number, if necessary. *Note:* This field is used if your organization needs to extract customers' first or last names for communication (invoices, emails, etc.). The field lets an organization accommodate variations of names used across the globe. |External key |An optional alternate ID for the account. Once this is saved for the customer, you cannot change it. *Tip:* The external key feature is helpful if you integrate Kill Bill with another system, such as a CRM, and want to use that system's ID in Kill Bill (for identification, searching, and so forth). Once this is set and saved for the customer, you cannot change it. |Email |The main email address to use for communicating with the customer. |Bill cycle day (BCD) |For monthly or quarterly subscriptions, what day of the month the invoice is created. Once this is saved for the customer, you cannot change it. *Note:* The system has three types of billing (date) alignment that affect the BCD: `ACCOUNT`, `SUBSCRIPTION`, and `BUNDLE`. For more information about the three billing alignment types, see https://docs.killbill.io/latest/catalog-examples.html[_Catalog Examples_] and https://docs.killbill.io/latest/userguide_subscription.html#_billing_alignment_rules[""Billing Alignment Rules""] in the https://docs.killbill.io/latest/userguide_subscription.html[_Subscription_ manual]. |Currency |The currency that the customer uses to make purchases. Once this is saved for the customer, you cannot change it. |Timezone |The time zone in which the customer resides. Once this is saved for the customer, you cannot change it. |Locale |Indicates the language that Kaui uses to send communication to the customer (invoices, emails, etc.) If your organizaton communicates with customers in a language that's different than the system's default language, it's important to select the appropriate locale for the customer. For more information, see the https://docs.killbill.io/latest/internationalization.html[_Internationalization_ manual]. |Address line 1 and Address line 2 |The street address where the customer resides. |Zip code |The zip code for the area in which the customer resides. |Company |If relevant, the company/organization the customer works for. |City |The city in which the customer resides. |State |The state in which the customer resides. |Country |The country in which the customer resides. |Phone |The customer's phone number. |Notes |Additional information about the account. These notes are not viewable by the customer. |Migrated? |This field is for informational purposes only. You can check this box if you have migrated this customer account into Kill Bill. |Contact email addresses |Additional addresses to which account-related emails will be sent. The email addresses listed here will receive the same emails as the main Email address. For more information, see <<_add_additional_contact_emails>>. |=== === Edit an Account You can make changes to most of the account fields after it has been created. [NOTE] *Note:* You cannot change the following fields: Bill Cycle Day, Currency, External Key, and Time Zone. 1. Open the account on the Account page. 2. Next to Account Information, click *Edit*. Kaui opens the Update Account screen: image::Account_UpdateScreen.png[width=650,align=""center""] [start=3] . Make changes to the fields. For field descriptions, see <>. [start=4] . Click the *Save* button. === Add Additional Contact Emails If a customer wants to receive email at more than one email address (which is the one defined in the *Email* field for the account), you can add more email addresses. 1. Open the account on the Account page. 2. In the Personal Information section, click the gray down arrow ( image:i_GrayDownArrow.png[] ) to expand the section. image::PersonalInformation.png[width=550,align=""center""] [start=3] . Click the plus sign ( image:i_PlusGreen.png[] ) next to *Contact emails*. Kaui opens the Add New Email screen: image::AddNewEmail.png[width=550,align=""center""] [start=4] . Type in a single email address. . Select the *Save* button. Kaui returns to the Account page. . To see the email address you added, expand the Personal Information section: image::NewContactEmail.png[width=550,align=""center""] [start=7] . To add another email address, repeat steps 2 - 5. ==== Delete Additional Contact Emails [WARNING] *Warning:* Kaui does not ask you to confirm your deletion; use this feature with caution. To remove additional contact emails: 1. Open the account on the Account page. 2. In the Personal Information section, click the gray down arrow ( image:i_GrayDownArrow.png[] ) to expand the section. 3. Next to the email you want to delete, click the red X ( image:i_RedX.png[] ). Kaui immediately deletes the email address. === Close an Account Use the steps in this section to indicate you will no longer be doing business with a customer. If the customer has unpaid invoices, using the steps below, you can choose to either write off or item-adjust them. [NOTE] *Note:* Closing an account does not delete it. It only indicates the account is no longer a customer of yours. Once you close the account, its data becomes read-only, and you cannot make changes to it. 1. Open the account on the Account page. 2. Next to Account Information, click *Close*. Kaui displays the Close Account pop-up: image::CloseAccountPopup.png[width=450,align=""center""] [start=3] . Check the *Name* and *Account ID* fields to ensure you are closing the correct account. . Toggle any of the following options: * *Cancel All Subscriptions*—Stops any subscriptions that are current for this account. * *Write Off Unpaid Invoices*—Brings the balance for all unpaid invoices to zero. When you choose to write off the invoice, it is removed from Account Receivables. * *Item Adjust Unpaid Invoices*—Adds an invoice line item with a negative amount to bring each unpaid invoice's balance to zero. [NOTE] *Note:* The last two options are mutually exclusive (i.e., you can only select one of them). [start=5] . Click the *Close* button. Kaui displays a message that lets you know the account was closed. In addition, the *Account* sub-menu displays ""Closed:"" image::AccountSubmenu-Closed.png[width=650,align=""center""] === Add a Tag to an Account A ""tag"" is a way to attach specific information to an account (_Example:_ `good_user`) or a specify a certain behavior (_Example:_ `AUTO_INVOICING_OFF`). Kill Bill includes two types of tags: * *System tags:* Written in ALL CAPS characters, system tags can affect the behavior of the system. * *User tags:* Written in all lowercase characters, user tags do not affect the object they're attached to. User tabs are for informational purposes only. For more information on Tags, including a list of default tags, see the https://killbill.github.io/slate/#account-tags[""Tag"" section] in the https://killbill.github.io/slate/[_REST API Reference Manual_]. To add a tag to a customer account: 1. Open the account on the Account page. 2. In the Account Information section, click the tag icon in the upper left corner: image::AccountInfo-Section-Labeled.png[width=550,align=""center""] [start=3] . Select the checkboxes of the tags you want to assign to the account. image::Account-TagDropdown.png[width=550,align=""center""] [start=4] . Click the *Update* button to save your changes. <<< === Link to Parent Account When you link an account to a _parent_ account, the account becomes a _child_ account. Defining a parent-child association between accounts lets you define which entity is responsible for paying the invoice. For more information on this feature, see the https://docs.killbill.io/latest/ha.html[_Hierarchical Accounts Tutorial_]. 1. As a preparation step, open the parent account and copy the account ID in the Account Information section. 2. Open the account that will become the child account. 3. In the Account Information section of the child account, click the plus sign icon (image:i_PlusGreen.png[]) next to the *Parent* field: image::Account-ParentField-Labeled.png[width=550,align=""center""] Kaui opens a pop-up: image::LinkToParentPopup.png[width=550,align=""center""] [start=4] . Click in the *Parent account id* field and paste in the account ID that you copied in step 1. . To set the parent as responsible for all payments associated with this account, check the *Is payment delegated to a parent?* box. If you do not check this box, the child account is responsible for its own payments. [start=6] . Click the *Save* button. Kaui displays the parent account ID as a link in the Account Information section. image::Account-ParentID-Labeled.png[width=550,align=""center""] You can open the parent account by clicking the account ID link. ==== Add Credit to an Account Issuing a credit in Kaui creates a credit memo. For accounting purposes, the memo is saved with the customer account's invoices. 1. On the Account page, click *Add Credit* at the top of the Billing Info section. image::AddCredit-Labeled.png[width=550,align=""center""] Kaui opens the *Add New Credit* screen: image::AddCreditPopup.png[width=550,align=""center""] [start=2] . Fill in the fields: * *Amount*—The amount of the credit. * *Currency*—The currency defaults from the customer account and should not need to be changed. * *Reason*—The reason is automatically selected based on https://docs.killbill.io/latest/userguide_configuration.html#_kaui_configuration[Kaui configuration settings]. However, you can make a different selection. * *Comment*—The text you enter here displays on the <> page after saving the credit. Adding comments is optional. [start=3] . Click the *Save* button. To view the credit, select *Invoices* on the sub-menu. On the Account page (in the Billing Info section), Kaui adjusts the account balance and account credit accordingly. ==== Create a Charge on an Account Creating a charge in Kaui creates a new invoice. To create a charge: 1. On the Account page, click *Create Charge* at the top of the Billing Info section. image::CreateCharge-Labeled.png[width=550,align=""center""] Kaui opens the *Add New Charge* screen: image::AddNewChargePopup.png[width=550,align=""center""] [start=2] . To set the invoice as a draft instead of immediately committing it, uncheck the *Auto-commit* box. . Fill in the fields: * *Amount*—The amount of the charge. * *Currency*—The currency defaults from the customer account and should not need to be changed. * *Description* and *Comment*—What you type here displays on the customer's invoice. Both fields are optional. [start=4] . Click *Save* and Kaui generates an invoice. . If you unchecked the *Auto-commit* box and have changed your mind, you can click the text *Commit* at the top of the page. If you do not commit the invoice, it will stay in Draft mode. You can commit it by opening it from the Invoices page and clicking *Commit*. On the Account page (in the Billing Info section), Kaui adjusts the account balance to reflect the amount of the charge. === Payment Methods A customer account can have several payment methods to allow for making payments in different ways, such as credit cards, debit cards, PayPal, and so forth. The payment method includes the details needed for Kill Bill to process a payment against an invoice. Saving this information in Kaui makes it easier to accept payments from the customer because the customer or service staff don't need to repeatedly provide their payment method details. In production systems, payment method information is typically added via gateway-specific data flows. However, developers can use the Payment Method section for testing purposes. [NOTE] *Note:*Although you can't edit a payment method, you can delete it. [WARNING] *Warning!* For PCI compliance, _do not_ enter any genuine payment information in these fields. ==== About Payment Plugin Names Each payment method is associated with a payment plugin, a type of software that performs the backend processing for that specific payment method. The *Plugin name* field specifies the name of this payment plugin. (_Example:_ `killbill-stripe`). The plugin name is typically mentioned in the plugin's `readme` file. For example, in the https://github.com/killbill/killbill-stripe-plugin#using-stripe-checkout[Stripe plugin `readme` file], the plugin name is specified in the command line. ==== View Payment Method Details To view a payment method after it's created: 1. Open the account on the Account page. 2. In the *Payment Methods* area, click the gray down arrow ( image:i_GrayDownArrow.png[] ) next to the payment method. Kaui expands the details for the payment method: image::PaymentMethod-Expanded.png[width=550,align=""center""] ==== Set a Payment Method as the Default Kill Bill uses the default payment method to automatically pay invoices (whether that invoice is generated by the system or manually by a user). To set a payment method as the default: 1. Open the account on the Account page. 2. In the Payment Methods section, click the star icon (image:i_StarClear.png[]) next to the relevant payment method: image::PaymentMethodStar-Labeled.png[width=550,align=""center""] The filled star ( image:i_StarFilled.png[] ) indicates it's now the default payment method. ==== Add Payment Method To add a payment method: 1. Open the account on the Account page. 2. Next to *Payment Methods*, click the plus sign: image::PaymentMethods-PlusSign-Labeled.png[width=550,align=""center""] Kaui displays the Add New Payment Method screen: image::AddPaymentMethodScreen.png[width=550,align=""center""] [start=3] . Fill in the fields. For field descriptions, see <>. . Click the *Save* button. ===== Payment Method Field Descriptions [cols=""1,3""] |=== ^|Field ^|Description |External key |An optional alternate ID for the payment method. Once this is saved for the customer, you cannot change it. |Plugin name |Type in the name of the plugin that is associated with this type of payment method. Each payment method is associated with a payment plugin that does the backend processing related to the payment method. The *Plugin name* field specifies the name of the payment plugin associated with the payment method (_Example:_ `killbill-stripe`). The Plugin name is typically mentioned in the plugin's `readme` file. For example, in the https://github.com/killbill/killbill-stripe-plugin#using-stripe-checkout[Stripe plugin `readme` file], the plugin name is specified in the command line. |Card type |The name of the credit or debit card. |Card holder name |The name that appears on the card. |Expiration month Expiration year |The month and year the card expires. Enter month as _mm_ and year as _yy_. (_Examples:_ `07` for the month of July and `23` for the year 2023.) |Credit card number |The credit card number, typed without dashes. |Address 1, Address 2, City, ZIP code, State, Country |The billing address associated with this card. |Add property (Name/Value) |Use the *Name/Value* fields to assign custom fields and values to the payment method. *Note:* Custom fields are an advanced feature. For more information, see <>. |Default payment method? |Check the box to set this payment method as the default. Kill Bill uses the default payment method to automatically pay invoices (whether the invoice is generated by the system or manually by a user). *Note:* If you forget to select this box, you can set the payment method as the default by clicking the star icon next to the payment method on the Account page: image:PaymentMethodStar-Labeled.png[width=350,align=""center""] |=== ==== Applying Transactions to a Payment Method This section explains how to apply a transaction to a payment method. These transactions are directly applied on the payment instrument (as opposed to being applied to the unpaid invoice). Use this functionality only for transactions _unrelated to invoices and/or payments_. _Example:_ After paying her final invoice, a customer cancels her subscription and demands a full refund because she is dissatisfied. In this case, you would process this transaction (the refund) against the payment method as explained in this section. You can perform the following transactions from the Payment Methods section: [cols=""1,1""] [frame=none] [grid=none] |=== a| * Authorize * Capture * Credit (see note) a| * Purchase (i.e., charge) * Refund * Void |=== [NOTE] *Note:* ""Credit"" here refers to depositing funds directly to the customer card and is unrelated to account credits. 1. Open the account on the Account page. 2. In the *Payment Methods* area, click the gray down arrow ( image:i_GrayDownArrow.png[] ) next to the payment method. 3. Select the type of transaction you want to perform: image::Payment_Method-Transactions.png[width=550,align=""center""] [NOTE] *Note:* This area lists Authorize, Purchase, and Credit. For other transaction types, click any of these options. You will be able to change the transaction type on the next screen. <<< Kaui displays the Process Transaction screen: image::ProcessTransaction.png[width=550,align=""center""] [start=4] . Fill in the fields. For field descriptions, see <>. . Click the *Save* button. Kaui saves the transaction and displays it on the Payments page. ==== Process Transaction Field Descriptions [cols=""1,3""] |=== ^|Field ^|Description |Transaction type |From the dropdown list, select the type of transaction you want to perform. |Amount |The amount of the transaction. |Currency |The currency to use for the transaction. This field defaults from the customer account. |Payment key |The unique payment key (ID) to which you want to apply the transaction. This field is required for transaction types that are applied to a specific payment (Capture, Chargeback, Refund, Void). *Note:* You can copy the payment key for a specific transaction from the *External Key* column of the Payments page. Or you can copy it from the URL displayed on your browser's address line: _Example:_ URL: `\\https://demo.killbill.io/accounts/cb736a4f-9b56-4074-ae07-1d37b37cb69f/payments/0d1e11e5-2df6-4b6b-992f-e9ff2de38cef` Payment key: `0d1e11e5-2df6-4b6b-992f-e9ff2de38cef` |Transaction key |Kill Bill automatically generates an external transaction key for Authorize, Purchase, and Credit transactions. To process a transaction that requires the transaction key, open the payment detail from the Payments screen and copy the key from the *Transaction External Key* column. image:TransactionKey-Labeled.png[width=350,align=""center""] |Reason |The reason is automatically selected based on https://docs.killbill.io/latest/userguide_configuration.html#_kaui_configuration[Kaui configuration settings]. However, you can make a different selection. |Comment |The text you enter here displays on the <> page after the transaction is complete. Adding comments is optional. |Add control plugin |For information on control plugins, see <>. |Add property (Name/Value) |Use this area to assign custom fields and values to the transaction. For information on custom fields, see <>. |=== ==== Delete Payment Method [WARNING] *Warning:* Kaui does not ask you to confirm your deletion; use this feature with caution. To delete a payment method: 1. Open the account on the Account page. 2. In the *Payment Methods* area, click the red X ( image:i_RedX.png[] ) next to the payment method. Kaui _immediately_ removes the payment method. //________________________________________________// === Subscriptions *_IN PROCESS_* // This area of Kaui lists the subscriptions associated with the account. //To create a subscription, you must first have at least one plan defined in the catalog. //Add a Subscription //Edit a Subscription? //Delete a Subscription //________________________________________________// === Invoices This section helps you become familiar with the Invoices and Invoice Details pages. ==== Invoices Page The Invoices page lists the invoices for the currently selected account. image::Invoices.png[width=650,align=""center""] Kill Bill generates invoices automatically based on the customer's subscriptions. However, you can manually create an invoice by <<_create_charge, creating a charge>> on the customer's account. Click on the invoice number to open the Invoice Details page. ==== Invoice Details Page The Invoice Details page displays information about the invoice, such as the date it was generated, amount, and so forth. image::Invoice_Detail.png[width=650,align=""center""] On the Invoice Details page, you can: * Make a payment against an invoice * Write off or void an invoice * See the payment details (if the invoice was paid) [NOTE] *Note:* You can perform two other invoice-related tasks on the Accounts page: <> and <>. ==== Open Invoice Details To get to the Invoice Details page: . Open an account. . Click *Invoices* on the sub-menu. . Select an invoice number. [NOTE] *Note:* To see any associated payment details, you may need to scroll down the page. ==== Make a Payment on an Invoice To make a manual payment against an invoice: 1. <> for the invoice. image::Invoice_Detail.png[width=650,align=""center""] [start=2] . Hover over the credit card icon and select *Make Payment*. image::Invoice_MakePayment.png[width=350,align=""center""] [NOTE] *Note:* If the invoice has already been fully paid, the credit card icon doesn't show, and the payment details are displayed below the invoice. [start=2] . Kaui displays the Process Payment screen: image::Invoice_ProcessPayment.png[width=450,align=""center""] [start=3] . Fill in the fields. For field descriptions, see <>. . Click *Save*. The invoice detail shows the balance due on the invoice. Below the invoice, Kaui displays the payment details, including the status of the payment. ==== Process Payment Field Descriptions [cols=""1,3""] |=== ^|Field ^|Description |External? |Select this checkbox if the customer is making a payment outside of the Kill Bill system (such as with a check). Note that if this checkbox is selected, it overrides anything selected in the *Payment Method* field. |Amount |The amount defaults from the invoice balance. If the customer is making a partial payment, you can change this amount. |Payment Method |To use the account’s default payment method, leave the field blank. Otherwise, select the payment method from the drop-down. |Reason |The reason is automatically selected based on https://docs.killbill.io/latest/userguide_configuration.html#_kaui_configuration[Kaui configuration settings]. However, you can make a different selection. |Comment |The text you enter here displays on the <> page after the payment is complete. Adding comments is optional. |=== ==== Write Off or Void an Invoice This section explains how to write off an invoice and void an invoice. ""Write-off"" and ""void"" have different distinct meanings in Kill Bill: * *Write off:* Brings the balance of an unpaid invoice to $0. This method is typically used when closing an account with unpaid invoices (or when you are sure the invoice is uncollectible). * *Void:* Changes the invoice's status to VOID, in which case it is ignored by the system. An invoice _cannot_ be voided if: ** It was partially or fully paid. ** It contains positive credit items. ** Any invoice item was internally adjusted by the system. (In this situation, you could refund the payment before voiding the invoice.) ===== Write Off an Invoice To write off an invoice: 1. <> for the invoice. image::Invoice_Detail2.png[width=650,align=""center""] [start=2] . Hover over the tag icon (image:i_Tag.png[]). Kaui displays a drop-down: image::Invoice_WriteOffDropdown.png[width=350,align=""center""] [start=3] . Select the *WRITTEN_OFF* checkbox and (optionally) type text in the *Comment* field. . Click the *Update* button. If the write-off is successful, Kaui displays ""This invoice has been written off"" at the top of the Invoice Detail. ===== Void an Invoice To void an invoice: 1. <> for the invoice. image::Invoice_Detail3.png[width=650,align=""center""] [start=2] . Hover over the trashcan icon (image:i_trash.png[]). Kaui displays a drop-down: image::Invoice_VoidDropdown.png[width=350,align=""center""] [start=3] . If desired, type text in the *Comment* field. . Click the *Void* button. If the void is successful, Kaui displays ""This invoice has been voided"" at the top of the Invoice Detail. ==== Pay All Unpaid Invoices You can pay all unpaid invoices if a customer account has at least one outstanding invoice. Before you begin, make sure the customer has a valid payment method (see Note). [NOTE] *Note:* If the invoices have gone unpaid because of issues with the customer's payment method (for example, an expired credit card), make sure you <> and <>. To pay all invoices: . Open the account on the Account page. . In the *Billing Info* section, click *Pay all invoices*. image::PayAllInvoices.png[width=350,align=""center""] If the payments are completed, Kaui displays a success message at the top of the screen. To see the payment details, click *Payments* on the sub-menu. ==== Generate a Dry-Run Invoice A dry-run invoice lets you see how a customer's invoice will look without actually committing it. This feature creates a draft invoice as if it's being generated on the customer's bill cycle day. It's a helpful feature for testing. (You cannot generate a dry-run invoice for an invoice generated from a charge.) <--NOT SURE WE NEED TO SAY THIS After you generate the invoice, which is in `DRAFT` mode, you have the choice to commit it. If you do not commit the `DRAFT` invoice, it remains in the system as a draft. In order to generate a dry-run invoice, the customer account must be associated with a subscription that has a billing date in the future. . Open the account on the Account page. . In the *Billing Info* section, make sure the *Dry-run* checkbox is selected. image::Invoice-DryRunBox.png[width=450,align=""center""] [start=3] . In the field next to *Dry-run*, enter the date that matches the invoice's upcoming invoice date. image::Invoice-NextBillDate.png[width=450,align=""center""] [start=4] . Click the magic wand button: image::i_InvoiceGen.png[align=""center""] Kaui generates and displays the draft invoice. A message at the top indicates it is a draft invoice. [NOTE] *Note:* To change the invoice from `DRAFT` to `COMMITTED`, click ""trigger an invoice run"" in the message at the top of the invoice. //________________________________________________// === Payments This section helps you become familiar with the Payments and Payment Details pages. ==== Payments Page The Payments page lists any payments applied to invoices for the customer account. [NOTE] *Note:* If a customer account has a default payment method, Kaui automatically makes a payment when an invoice is generated in the system. See <> for more information. image::Payments.png[width=850,align=""center""] ==== About Automatic Invoice Payments Kill Bill automatically generates a payment for an invoice if an account: * Has an outstanding, unpaid invoice AND * Has a default and valid payment method Kill Bill _does not_ automatically generate an invoice payment if: * No default payment method exists for the account * The default payment method is invalid (e.g., expired credit card) * The `AUTO_PAY_OFF` or `MANUAL_PAY` https://docs.killbill.io/latest/userguide_subscription.html#components-tag[system tags] are defined for the account [NOTE] *Note:* For invoices that Kill Bill does not automatically pay, you can use the ""Pay all Invoices"" feature. For more information, see <>. ==== Payment Details Page The Payment Details page displays information about a specific payment, such as the date it was generated, amount, and so forth. Below the payment information is information about the payment method used. image::PaymentDetails.png[width=850,align=""center""] On the Payment Details page, you can: <> or <>. ==== Open Payment Details To get to the Payment Details page: 1. Open an account. 2. Click *Payments* on the sub-menu. 3. Select a payment number. [NOTE] *Note:* To see the associated payment method information, you may need to scroll down the page. ==== Refund a Payment When you refund a payment from the Payment Details page, it brings the invoice amount to zero (i.e., the invoice will have no balance). You can also perform a partial refund in which the partial refund amount is added as an invoice line item. <--NOT SURE THIS IS RIGHT The refund is applied to the same payment method used in the original payment. [NOTE] *Note:* You can also perform a refund directly on the payment method that was originally used. For more information, see <>. To refund a payment: 1. <> for the payment. image::PaymentDetails2.png[width=850,align=""center""] [start=2] . Hover over the credit card icon and select *Refund*. image::PaymentDetail-SelectRefund.png[width=350,align=""center""] Kaui opens the Process Refund screen. image::ProcessRefundPopup.png[width=450,align=""center""] [start=3] . Fill in the fields. For field descriptions, see <>. . Click the *Save* button. Kaui saves the refund and displays it as a separate row on the Payments Details page: image::PaymentDetails-Refund-Labeled.png[width=650,align=""center""] ==== Process Refund Field Descriptions [cols=""2,4""] |=== ^|Field ^|Description |No Invoice Adjustment Invoice Item Adjustment |If you are refunding the entire balance of the invoice, select *No Invoice Adjustment*. However, if you are providing a partial refund, select *Invoice Item Adjustment*. <--NOT SURE THIS IS RIGHT |Amount |The amount of the refund. Kaui automatically fills this in based on the invoice balance. |Reason |The refund reason is automatically selected based on https://docs.killbill.io/latest/userguide_configuration.html#_kaui_configuration[Kaui configuration settings]. However, you can make a different selection. |Comment |The text you enter here displays on the <> page after the payment is complete. Adding comments is optional. |=== ==== Perform a Chargeback If your business receives a chargeback notice for a payment, you can record that chargeback in Kill Bill. 1. <> for the payment. image::PaymentDetails3.png[width=850,align=""center""] [start=2] . Hover over the credit card icon and select *Chargeback*. image::PaymentDetail-SelectChargeback.png[width=350,align=""center""] Kaui opens the Process Chargeback screen with the *Amount* and *Reason* fields already filled in. image::ProcessChargeback.png[width=450,align=""center""] [start=3] . If necessary, select a different *Reason*. (The chargeback reason is automatically selected based on https://docs.killbill.io/latest/userguide_configuration.html#_kaui_configuration[Kaui configuration settings]. However, you can make a different selection.) . If the subscription associated with the payment needs to be canceled, check the *Cancel account subscriptions* box. . Fill in the *Comment* field (optional). The text you enter here displays on the <> page. . Click the *Save* button. Kaui saves the chargeback and displays it as a separate row on the Payments Details page: image::PaymentDetails-Chargeback-Labeled.png[width=650,align=""center""] === Timeline *_IN PROCESS_* // How to view/interpret the timeline. What it shows. // The Timeline also includes information about payment retries (When an account is unpaid, Kill Bill (the payment retry system) retries payments per the scheduled configuration. // The billing timeline shows all the events that occurred for a specific user account: // The top two *Filter by...* dropdown fields let you filter the events by subscription bundle or by event type. // In the *Details* column, you can click payment and invoice links to open the associated documents. // image::TimelinePage.png[] // MENTION payment retries per https://killbillio.slack.com/archives/G01H4PZRTN1/p1633596764006800 //________________________________________________// == Part 3 - Users, Roles, and Permissions [[part_3_users_roles_permissions]] *_IN PROCESS_* //either database or third-party integration for storing usernames and passwords //The default ""admin"" username/password includes all of the roles and permissions available with Kill Bill. //________________________________________________// == Part 4 - Tags and Custom Fields [[part_4_tags_and_custom_fields]] *_IN PROCESS_* // === Tags // For the tags, it would make sense to touch on the 'system' tags versus user tags, the former (Uppercase) having a strong effect on the behavior of the system, while the latter (lowercase) having NO effect on the behavior of the system. // === Custom Fields //________________________________________________// == Part 5 - Plugin Manager and Analytics [[part_5_plugin_manager_and_analytics]] *_IN PROCESS_* // === KPM (Kill Bill Package Manager) // === Analytics and Reporting // === Deposits (Wire Transfers) //________________________________________________// == Part 6 - Tenants and Admin [[part_6_tenants_and_admin]] *_IN PROCESS_* //________________________________________________// == FAQs [[faqs]] *_IN PROCESS_* //I'm thinking this will get so long that it might be best to make it a separate manual? // *Q:* What can I search on with Advanced Search? // *A:* You can search on the following object types: // * Accounts // * Bundles // * Credits // * Custom fields // * Invoices // * Invoice payments // * Payments // * Subscriptions // * Transactions // * Tags // * Tag Definitions ",12142,False,2265.2632630870826,median "--- title: ""FreeBSD/ia64 5.0-RELEASE Installation Instructions"" sidenav: download --- ++++

The FreeBSD Project

Copyright © 2000, 2001, 2002, 2003 by The FreeBSD Documentation Project


This article gives some brief instructions on installing FreeBSD/ia64 5.0-RELEASE, with particular emphasis given to obtaining a FreeBSD distribution. Some notes on troubleshooting and frequently-asked questions are also given.


1 Installing FreeBSD

This section documents the process of installing a new distribution of FreeBSD. These instructions pay particular emphasis to the process of obtaining the FreeBSD 5.0-RELEASE distribution and to beginning the installation procedure. The ``Installing FreeBSD'' chapter of the FreeBSD Handbook provides more in-depth information about the installation program itself, including a guided walkthrough with screenshots.

If you are upgrading from a previous release of FreeBSD, please see Section 3 for instructions on upgrading.


1.1 Getting Started

Probably the most important pre-installation step that can be taken is that of reading the various instruction documents provided with FreeBSD. A roadmap of documents pertaining to this release of FreeBSD can be found in README.TXT, which can usually be found in the same location as this file; most of these documents, such as the release notes and the hardware compatibility list, are also accessible in the Documentation menu of the installer.

Note that on-line versions of the FreeBSD FAQ and Handbook are also available from the FreeBSD Project Web site, if you have an Internet connection.

This collection of documents may seem daunting, but the time spent reading them will likely be saved many times over. Being familiar with what resources are available can also be helpful in the event of problems during installation.

The best laid plans sometimes go awry, so if you run into trouble take a look at Section 4, which contains valuable troubleshooting information. You should also read an updated copy of ERRATA.TXT before installing, since this will alert you to any problems which have reported in the interim for your particular release.

Important: While FreeBSD does its best to safeguard against accidental loss of data, it's still more than possible to wipe out your entire disk with this installation if you make a mistake. Please do not proceed to the final FreeBSD installation menu unless you've adequately backed up any important data first.


1.2 Hardware Requirements

If you are not familiar with configuring hardware for FreeBSD, you should be sure to read the HARDWARE.TXT file; it contains important information on what hardware is supported by FreeBSD.


1.5 Detail on various installation types

Once you've gotten yourself to the initial installation screen somehow, you should be able to follow the various menu prompts and go from there. If you've never used the FreeBSD installation before, you are also encouraged to read some of the documentation in the Documentation submenu as well as the general ``Usage'' instructions on the first menu.

Note: If you get stuck at a screen, press the F1 key for online documentation relevant to that specific section.

If you've never installed FreeBSD before, or even if you have, the ``Standard'' installation mode is the most recommended since it makes sure that you'll visit all the various important checklist items along the way. If you're much more comfortable with the FreeBSD installation process and know exactly what you want to do, use the ``Express'' or ``Custom'' installation options. If you're upgrading an existing system, use the ``Upgrade'' option.

The FreeBSD installer supports the direct use of floppy, DOS, tape, CDROM, FTP, NFS and UFS partitions as installation media; further tips on installing from each type of media are listed below.


1.5.1 Installing from a Network CDROM

If you simply wish to install from a local CDROM drive then see Section 1.4. If you don't have a CDROM drive on your system and wish to use a FreeBSD distribution CD in the CDROM drive of another system to which you have network connectivity, there are also several ways of going about it:

  • If you would be able to FTP install FreeBSD directly from the CDROM drive in some FreeBSD machine, it's quite easy: You simply add the following line to the password file (using the vipw(8) command):

        ftp:*:99:99::0:0:FTP:/cdrom:/sbin/nologin
    

    On the machine on which you are running the install, go to the Options menu and set Release Name to any. You may then choose a Media type of FTP and type in ftp://machine after picking ``URL'' in the ftp sites menu.

    Warning: This may allow anyone on the local network (or Internet) to make ``anonymous FTP'' connections to this machine, which may not be desirable.

  • If you would rather use NFS to export the CDROM directly to the machine(s) you'll be installing from, you need to first add an entry to the /etc/exports file (on the machine with the CDROM drive). The example below allows the machine ziggy.foo.com to mount the CDROM directly via NFS during installation:

        /cdrom          -ro             ziggy.foo.com
    

    The machine with the CDROM must also be configured as an NFS server, of course, and if you're not sure how to do that then an NFS installation is probably not the best choice for you unless you're willing to read up on rc.conf(5) and configure things appropriately. Assuming that this part goes smoothly, you should be able to enter: cdrom-host:/cdrom as the path for an NFS installation when the target machine is installed, e.g. wiggy:/cdrom.


1.5.2 Installing from Floppies

If you must install from floppy disks, either due to unsupported hardware or just because you enjoy doing things the hard way, you must first prepare some floppies for the install.

First, make your boot floppies as described in Section 1.3.

Second, peruse Section 2 and pay special attention to the ``Distribution Format'' section since it describes which files you're going to need to put onto floppy and which you can safely skip.

Next you will need, at minimum, as many 1.44MB floppies as it takes to hold all files in the bin (binary distribution) directory. If you're preparing these floppies under DOS, then these floppies must be formatted using the MS-DOS FORMAT command. If you're using Windows, use the Windows File Manager format command.

Important: Frequently, floppy disks come ``factory preformatted''. While convenient, many problems reported by users in the past have resulted from the use of improperly formatted media. Re-format them yourself, just to make sure.

If you're creating the floppies from another FreeBSD machine, a format is still not a bad idea though you don't need to put a DOS filesystem on each floppy. You can use the disklabel(8) and newfs(8) commands to put a UFS filesystem on a floppy, as the following sequence of commands illustrates:

    # fdformat -f 1440 fd0.1440
    # disklabel -w -r fd0.1440 floppy3
    # newfs -t 2 -u 18 -l 1 -i 65536 /dev/fd0

After you've formatted the floppies for DOS or UFS, you'll need to copy the files onto them. The distribution files are split into chunks conveniently sized so that 5 of them will fit on a conventional 1.44MB floppy. Go through all your floppies, packing as many files as will fit on each one, until you've got all the distributions you want packed up in this fashion. Each distribution should go into its own subdirectory on the floppy, e.g.: a:\\bin\\bin.inf, a:\\bin\\bin.aa, a:\\bin\\bin.ab, ...

Important: The bin.inf file also needs to go on the first floppy of the bin set since it is read by the installation program in order to figure out how many additional pieces to look for when fetching and concatenating the distribution. When putting distributions onto floppies, the distname.inf file must occupy the first floppy of each distribution set. This is also covered in README.TXT.

Once you come to the Media screen of the install, select ``Floppy'' and you'll be prompted for the rest.


1.5.4 Installing from QIC/SCSI Tape

When installing from tape, the installation program expects the files to be simply tar'ed onto it, so after fetching all of the files for the distributions you're interested in, simply use tar(1) to get them onto the tape with a command something like this:

    # cd /where/you/have/your/dists
    # tar cvf /dev/rsa0 dist1 .. dist2

When you go to do the installation, you should also make sure that you leave enough room in some temporary directory (which you'll be allowed to choose) to accommodate the full contents of the tape you've created. Due to the non-random access nature of tapes, this method of installation requires quite a bit of temporary storage. You should expect to require as much temporary storage as you have stuff written on tape.

Note: When going to do the installation, the tape must be in the drive before booting from the boot floppies. The installation ``probe'' may otherwise fail to find it.

Now create a boot floppy as described in Section 1.3 and proceed with the installation.


1.5.5 Installing over a Network using FTP or NFS

After making the boot floppies as described in the first section, you can load the rest of the installation over a network using one of 3 types of connections: serial port, parallel port, or Ethernet.


1.5.5.1 Serial Port

SLIP support is rather primitive, and is limited primarily to hard-wired links, such as a serial cable running between two computers. The link must be hard-wired because the SLIP installation doesn't currently offer a dialing capability. If you need to dial out with a modem or otherwise dialog with the link before connecting to it, then I recommend that the PPP utility be used instead.

If you're using PPP, make sure that you have your Internet Service Provider's IP address and DNS information handy as you'll need to know it fairly early in the installation process. You may also need to know your own IP address, though PPP supports dynamic address negotiation and may be able to pick up this information directly from your ISP if they support it.

You will also need to know how to use the various ``AT commands'' for dialing out with your particular brand of modem as the PPP dialer provides only a very simple terminal emulator.


1.5.5.2 Parallel Port

If a hard-wired connection to another FreeBSD or Linux machine is available, you might also consider installing over a ``laplink'' style parallel port cable. The data rate over the parallel port is much higher than what is typically possible over a serial line (up to 50k/sec), thus resulting in a quicker installation. It's not typically necessary to use ``real'' IP addresses when using a point-to-point parallel cable in this way and you can generally just use RFC 1918 style addresses for the ends of the link (e.g. 10.0.0.1, 10.0.0.2, etc).

Important: If you use a Linux machine rather than a FreeBSD machine as your PLIP peer, you will also have to specify link0 in the TCP/IP setup screen's ``extra options for ifconfig'' field in order to be compatible with Linux's slightly different PLIP protocol.


1.5.5.3 Ethernet

FreeBSD supports many common Ethernet cards; a table of supported cards is provided as part of the FreeBSD Hardware Notes (see HARDWARE.TXT in the Documentation menu on the boot floppy or the top level directory of the CDROM). If you are using one of the supported PCMCIA Ethernet cards, also be sure that it's plugged in before the laptop is powered on. FreeBSD does not, unfortunately, currently support ``hot insertion'' of PCMCIA cards during installation.

You will also need to know your IP address on the network, the netmask value for your subnet and the name of your machine. Your system administrator can tell you which values are appropriate to your particular network setup. If you will be referring to other hosts by name rather than IP address, you'll also need a name server and possibly the address of a gateway (if you're using PPP, it's your provider's IP address) to use in talking to it. If you want to install by FTP via an HTTP proxy (see below), you will also need the proxy's address.

If you do not know the answers to these questions then you should really probably talk to your system administrator first before trying this type of installation. Using a randomly chosen IP address or netmask on a live network is almost guaranteed not to work, and will probably result in a lecture from said system administrator.

Once you have a network connection of some sort working, the installation can continue over NFS or FTP.


1.5.5.4 NFS installation tips

NFS installation is fairly straight-forward: Simply copy the FreeBSD distribution files you want onto a server somewhere and then point the NFS media selection at it.

If this server supports only ``privileged port'' access (this is generally the default for Sun and Linux workstations), you will need to set this option in the Options menu before installation can proceed.

If you have a poor quality Ethernet card which suffers from very slow transfer rates, you may also wish to toggle the appropriate Options flag.

In order for NFS installation to work, the server must also support ``subdir mounts'', e.g. if your FreeBSD distribution directory lives on wiggy:/usr/archive/stuff/FreeBSD, then wiggy will have to allow the direct mounting of /usr/archive/stuff/FreeBSD, not just /usr or /usr/archive/stuff.

In FreeBSD's /etc/exports file this is controlled by the -alldirs option. Other NFS servers may have different conventions. If you are getting Permission Denied messages from the server then it's likely that you don't have this properly enabled.


1.5.5.5 FTP Installation tips

FTP installation may be done from any mirror site containing a reasonably up-to-date version of FreeBSD. A full menu of reasonable choices for almost any location in the world is provided in the FTP site menu during installation.

If you are installing from some other FTP site not listed in this menu, or you are having troubles getting your name server configured properly, you can also specify your own URL by selecting the ``URL'' choice in that menu. A URL can contain a hostname or an IP address, so something like the following would work in the absence of a name server:

    ftp://216.66.64.162/pub/FreeBSD/releases/ia64/4.2-RELEASE

There are three FTP installation modes you can use:

  • FTP: This method uses the standard ``Active'' mode for transfers, in which the server initiates a connection to the client. This will not work through most firewalls but will often work best with older FTP servers that do not support passive mode. If your connection hangs with passive mode, try this one.

  • FTP Passive: This sets the FTP ""Passive"" mode which prevents the server from opening connections to the client. This option is best for users to pass through firewalls that do not allow incoming connections on random port addresses.

  • FTP via an HTTP proxy: This option instructs FreeBSD to use HTTP to connect to a proxy for all FTP operations. The proxy will translate the requests and send them to the FTP server. This allows the user to pass through firewalls that do not allow FTP at all, but offer an HTTP proxy. You must specify the hostname of the proxy in addition to the FTP server.

    In the rare case that you have an FTP proxy that does not go through HTTP, you can specify the URL as something like:

        ftp://foo.bar.com:port/pub/FreeBSD
    

    In the URL above, port is the port number of the proxy FTP server.




2 Distribution Format

A typical FreeBSD distribution directory looks something like this (exact details may vary depending on version, architecture, and other factors):

    ERRATA.HTM      README.TXT      compat1x        dict            kernel
    ERRATA.TXT      RELNOTES.HTM    compat20        doc             manpages
    HARDWARE.HTM    RELNOTES.TXT    compat21        docbook.css     packages
    HARDWARE.TXT    base            compat22        filename.txt    ports
    INSTALL.HTM     boot            compat3x        floppies        proflibs
    INSTALL.TXT     catpages        compat4x        games           src
    README.HTM      cdrom.inf       crypto          info            tools

If you want to do a CDROM, FTP or NFS installation from this distribution directory, all you need to do is make the 1.44MB boot floppies from the floppies directory (see Section 1.3 for instructions on how to do this), boot them and follow the instructions. The rest of the data needed during the installation will be obtained automatically based on your selections. If you've never installed FreeBSD before, you also want to read the entirety of this document (the installation instructions) file.

If you're trying to do some other type of installation or are merely curious about how a distribution is organized, what follows is a more thorough description of some of these items in more detail:

  1. The *.TXT and *.HTM files contain documentation (for example, this document is contained in both INSTALL.TXT and INSTALL.HTM) and should be read before starting an installation. The *.TXT files are plain text, while the *.HTM files are HTML files that can be read by almost any Web browser. Some distributions may contain documentation in other formats as well, such as PDF or PostScript.

  2. docbook.css is a Cascading Style Sheet (CSS) file used by some Web browsers for formatting the HTML documentation.

  3. The base, catpages, crypto, dict, doc, games, info, manpages, proflibs, and src directories contain the primary distribution components of FreeBSD itself and are split into smaller files for easy packing onto floppies (should that be necessary).

  4. The compat1x, compat20, compat21, compat22, compat3x, and compat4x directories contain distributions for compatibility with older releases and are distributed as single gzip'd tar files - they can be installed during release time or later by running their install.sh scripts.

  5. The floppies/ subdirectory contains the floppy installation images; further information on using them can be found in Section 1.3.

  6. The packages and ports directories contain the FreeBSD Packages and Ports Collections. Packages may be installed from the packages directory by running the command:

        #/stand/sysinstall configPackages
    

    Packages can also be installed by feeding individual filenames in packages/ to the pkg_add(1) command.

    The Ports Collection may be installed like any other distribution and requires about 100MB unpacked. More information on the ports collection may be obtained from http://www.FreeBSD.org/ports/ or locally from /usr/share/doc/handbook if you've installed the doc distribution.

  7. Last of all, the tools directory contains various DOS tools for discovering disk geometries, installing boot managers and the like. It is purely optional and provided only for user convenience.



A typical distribution directory (for example, the info distribution) looks like this internally:

    CHECKSUM.MD5    info.ab         info.ad         info.inf        install.sh
    info.aa         info.ac         info.ae         info.mtree

The CHECKSUM.MD5 file contains MD5 signatures for each file, should data corruption be suspected, and is purely for reference. It is not used by the actual installation and does not need to be copied with the rest of the distribution files. The info.a* files are split, gzip'd tar files, the contents of which can be viewed by doing:

    # cat info.a* | tar tvzf -

During installation, they are automatically concatenated and extracted by the installation procedure.

The info.inf file is also necessary since it is read by the installation program in order to figure out how many pieces to look for when fetching and concatenating the distribution. When putting distributions onto floppies, the .inf file must occupy the first floppy of each distribution set!

The info.mtree file is another non-essential file which is provided for user reference. It contains the MD5 signatures of the unpacked distribution files and can be later used with the mtree(8) program to verify the installation permissions and checksums against any possible modifications to the file. When used with the base distribution, this can be an excellent way of detecting trojan horse attacks on your system.

Finally, the install.sh file is for use by those who want to install the distribution after installation time. To install the info distribution from CDROM after a system was installed, for example, you'd do:

    # cd /cdrom/info
    # sh install.sh

3 Upgrading FreeBSD

These instructions describe a procedure for doing a binary upgrade from an older version of FreeBSD.

Warning: While the FreeBSD upgrade procedure does its best to safeguard against accidental loss of data, it is still more than possible to wipe out your entire disk with this installation! Please do not accept the final confirmation request unless you have adequately backed up any important data files.

Important: These notes assume that you are using the version of sysinstall(8) supplied with the version of FreeBSD to which you intend to upgrade. Using a mismatched version of sysinstall(8) is almost guaranteed to cause problems and has been known to leave systems in an unusable state. The most commonly made mistake in this regard is the use of an old copy of sysinstall(8) from an existing installation to upgrade to a newer version of FreeBSD. This is not recommended.

Warning: Binary upgrades to FreeBSD 5.0-RELEASE from FreeBSD 4-STABLE are not supported at this time. There are some files present in a FreeBSD 4-STABLE whose presence can be disruptive, but are not removed by a binary upgrade. One notable example is that an old /usr/include/g++ directory will cause C++ programs to compile incorrectly (or not at all).

These upgrade instructions are provided for the use of users upgrading from relatively recent FreeBSD 5-CURRENT snapshots.


3.1 Introduction

The upgrade procedure replaces distributions selected by the user with those corresponding to the new FreeBSD release. It preserves standard system configuration data, as well as user data, installed packages and other software.

Administrators contemplating an upgrade are encouraged to study this section in its entirety before commencing an upgrade. Failure to do so may result in a failed upgrade or loss of data.


3.1.1 Upgrade Overview

Upgrading of a distribution is performed by extracting the new version of the component over the top of the previous version. Files belonging to the old distribution are not deleted.

System configuration is preserved by retaining and restoring the previous version of the following files:

Xaccel.ini, XF86Config, adduser.conf, aliases, aliases.db, amd.map, crontab, csh.cshrc, csh.login, csh.logout, cvsupfile, dhclient.conf, disktab, dm.conf, dumpdates, exports, fbtab, fstab, ftpusers, gettytab, gnats, group, hosts, hosts.allow, hosts.equiv, hosts.lpd, inetd.conf, kerberosIV, localtime, login.access, login.conf, mail, mail.rc, make.conf, manpath.config, master.passwd, motd, namedb, networks, newsyslog.conf, nsmb.conf, nsswitch.conf, pam.conf, passwd, periodic, ppp, printcap, profile, pwd.db, rc.conf, rc.conf.local, rc.firewall, rc.local, remote, resolv.conf, rmt, sendmail.cf, sendmail.cw, services, shells, skeykeys, spwd.db, ssh, syslog.conf, ttys, uucp

The versions of these files which correspond to the new version are moved to /etc/upgrade/. The system administrator may peruse these new versions and merge components as desired. Note that many of these files are interdependent, and the best merge procedure is to copy all site-specific data from the current files into the new.

During the upgrade procedure, the administrator is prompted for a location into which all files from /etc/ are saved. In the event that local modifications have been made to other files, they may be subsequently retrieved from this location.


3.2 Procedure

This section details the upgrade procedure. Particular attention is given to items which substantially differ from a normal installation.


3.2.1 Backup

User data and system configuration should be backed up before upgrading. While the upgrade procedure does its best to prevent accidental mistakes, it is possible to partially or completely destroy data and configuration information.


3.2.2 Mount Filesystems

The disklabel editor is entered with the nominated disk's filesystem devices listed. Prior to commencing the upgrade, the administrator should make a note of the device names and corresponding mountpoints. These mountpoints should be entered here. Do not set the ``newfs flag'' for any filesystems, as this will cause data loss.


3.2.3 Select Distributions

When selecting distributions, there are no constraints on which must be selected. As a general rule, the base distribution should be selected for an update, and the man distribution if manpages are already installed. Other distributions may be selected beyond those originally installed if the administrator wishes to add additional functionality.


3.2.4 After Installation

Once the installation procedure has completed, the administrator is prompted to examine the new configuration files. At this point, checks should be made to ensure that the system configuration is valid. In particular, the /etc/rc.conf and /etc/fstab files should be checked.


3.3 Upgrading from Source Code

Those interested in an upgrade method that allows more flexibility and sophistication should take a look at The Cutting Edge in the FreeBSD Handbook. This procedure involves rebuilding all of FreeBSD from source code. It requires reliable network connectivity, extra disk space, and time, but has advantages for networks and other more complex installations. This is roughly the same procedure as is used for track the -STABLE or -CURRENT development branches.

/usr/src/UPDATING contains important information on updating a FreeBSD system from source code. It lists various issues resulting from changes in FreeBSD that may affect an upgrade.


4 Troubleshooting

4.1 Repairing an Existing FreeBSD Installation

FreeBSD features a ``Fixit'' option in the top menu of the boot floppy. To use it, you will also need either a fixit.flp image floppy, generated in the same fashion as the boot floppy, or the ``live filesystem'' CDROM; typically the second CDROM in a multi-disc FreeBSD distribution.

To invoke fixit, simply boot the kern.flp floppy, choose the ``Fixit'' item and insert the fixit floppy or CDROM when asked. You will then be placed into a shell with a wide variety of commands available (in the /stand and /mnt2/stand directories) for checking, repairing and examining filesystems and their contents. Some UNIX administration experience is required to use the fixit option.


This file, and other release-related documents, can be downloaded from ftp://ftp.FreeBSD.org/.

For questions about FreeBSD, read the documentation before contacting <questions@FreeBSD.org>.

For questions about this documentation, e-mail <doc@FreeBSD.org>.



++++ ",12369,False,2485.143500758525,median "// This is part of the documentation usually pulled in from Spring Data Commons // but in here, we copied it and removed Jpa, QueryDSL and other things that just dont fit in here. :springVersion: 5.2.0.RELEASE :spring-framework-docs: https://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference :spring-framework-javadoc: https://docs.spring.io/spring/docs/{springVersion}/javadoc-api [[repositories]] = Working with Spring Data Repositories The goal of the Spring Data repository abstraction is to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. [[repositories.core-concepts]] == Core concepts The central interface in the Spring Data repository abstraction is `Repository`. It takes the domain class to manage as well as the ID type of the domain class as type arguments. This interface acts primarily as a marker interface to capture the types to work with and to help you to discover interfaces that extend this one. The `CrudRepository` provides sophisticated CRUD functionality for the entity class that is being managed. [[repositories.repository]] .`CrudRepository` interface ==== [source, java] ---- public interface CrudRepository extends Repository { S save(S entity); <.> Optional findById(ID primaryKey); <.> Iterable findAll(); <.> long count(); <.> void delete(T entity); <.> boolean existsById(ID primaryKey); <.> // … more functionality omitted. } ---- <.> Saves the given entity. <.> Returns the entity identified by the given ID. <.> Returns all entities. <.> Returns the number of entities. <.> Deletes the given entity. <.> Indicates whether an entity with the given ID exists. ==== NOTE: We also provide a technology-specific abstraction: such as `Neo4jRepository` and the reactive variant, `ReactiveNeo4jRepository`. Those interfaces extend `CrudRepository` and expose the capabilities of the underlying persistence technology in addition to the rather generic persistence technology-agnostic interfaces such as `CrudRepository`. Also, methods returning an `Iterable` are narrowed down to return a `java.util.List` instead. On top of the `CrudRepository`, there is a `PagingAndSortingRepository` abstraction that adds additional methods to ease paginated access to entities: .`PagingAndSortingRepository` interface ==== [source, java] ---- public interface PagingAndSortingRepository extends CrudRepository { Iterable findAll(Sort sort); Page findAll(Pageable pageable); } ---- ==== To access the second page of `User` by a page size of 20, you could do something like the following: [source, java] ---- PagingAndSortingRepository repository = // … get access to a bean Page users = repository.findAll(PageRequest.of(1, 20)); ---- In addition to query methods, query derivation for both count and delete queries is available. The following list shows the interface definition for a derived count query: .Derived Count Query ==== [source, java] ---- interface UserRepository extends CrudRepository { long countByLastname(String lastname); } ---- ==== The following list shows the interface definition for a derived delete query: .Derived Delete Query ==== [source, java] ---- interface UserRepository extends CrudRepository { long deleteByLastname(String lastname); List removeByLastname(String lastname); } ---- ==== [[repositories.query-methods]] == Query methods Standard CRUD functionality repositories usually have queries on the underlying datastore. With Spring Data, declaring those queries becomes a four-step process: . Declare an interface extending Repository or one of its subinterfaces and type it to the domain class and ID type that it should handle, as shown in the following example: + [source, java] ---- interface PersonRepository extends Repository { … } ---- . Declare query methods on the interface. + [source, java] ---- interface PersonRepository extends Repository { List findByLastname(String lastname); } ---- . Provide some <> to set up Spring to create proxy instances for those interfaces. + [source, java] ---- include::../../examples/docs/src/main/java/org/neo4j/doc/springframework/data/docs/repositories/Config.java[tag=java-config-imperative-short] ---- + The `Driver` bean is required to provide the actual connection to the database. + Note that the configuration does not configure a package explicitly, because the package of the annotated class is used by default. To customize the package to scan, use one of the `basePackage…` attributes of the `@EnableNeo4jRepositories`-annotation. . Inject the repository instance and use it, as shown in the following example: + [source, java] ---- class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List persons = repository.findByLastname(""Matthews""); } } ---- The following sections explain each step in detail. [[repositories.definition]] == Defining Repository Interfaces First, define a domain class-specific repository interface. The interface must extend `Repository` and be typed to the domain class and an ID type. If you want to expose CRUD methods for that domain type, extend `CrudRepository` instead of `Repository`. [[repositories.definition-tuning]] === Fine-tuning Repository Definition Typically, your repository interface extends `Repository`, `CrudRepository`, or `PagingAndSortingRepository`. Alternatively, if you do not want to extend Spring Data interfaces, you can also annotate your repository interface with `@RepositoryDefinition`. Extending `CrudRepository` exposes a complete set of methods to manipulate your entities. If you prefer to be selective about the methods being exposed, copy the methods you want to expose from `CrudRepository` into your domain repository. NOTE: Doing so lets you define your own abstractions on top of the provided Spring Data Repositories functionality. The following example shows how to selectively expose CRUD methods (`findById` and `save`, in this case): .Selectively exposing CRUD methods ==== [source, java] ---- @NoRepositoryBean interface MyBaseRepository extends Repository { Optional findById(ID id); S save(S entity); } interface UserRepository extends MyBaseRepository { User findByEmailAddress(EmailAddress emailAddress); } ---- ==== In the prior example, you defined a common base interface for all your domain repositories and exposed `findById(…)` as well as `save(…)`. These methods are routed into the base repository implementation (for the imperative version, the implementation is `SimpleNeo4jRepository`), because they match the method signatures in `CrudRepository`. So the `UserRepository` can now save users, find individual users by ID, and trigger a query to find `Users` by email address. NOTE: The intermediate repository interface is annotated with `@NoRepositoryBean`. Make sure you add that annotation to all repository interfaces for which Spring Data should not create instances at runtime. [[repositories.multiple-modules]] === Using Repositories with Multiple Spring Data Modules Using a unique Spring Data module in your application makes things simple, because all repository interfaces in the defined scope are bound to one Spring Data module. Sometimes, applications require using more than one Spring Data module. In such cases, a repository definition must distinguish between persistence technologies. When it detects multiple repository factories on the class path, Spring Data enters strict repository configuration mode. Strict configuration uses details on the repository or the domain class to decide about Spring Data module binding for a repository definition: 1. If the repository definition <>, then it is a valid candidate for the particular Spring Data module. 2. If the domain class is <>, then it is a valid candidate for the particular Spring Data module. Spring Data modules accept either third-party annotations (such as JPA's `@Entity`) or provide their own annotations (such as `@Node` for Spring Data Neo4j⚡RX). The following example shows a repository that uses module-specific interfaces (JPA in this case): [[repositories.multiple-modules.types]] .Repository definitions using module-specific interfaces ==== [source, java] ---- interface MyRepository extends JpaRepository { } @NoRepositoryBean interface MyBaseRepository extends JpaRepository { … } interface UserRepository extends MyBaseRepository { … } ---- `MyRepository` and `UserRepository` extend `JpaRepository` in their type hierarchy. They are valid candidates for the Spring Data JPA module. ==== The following example shows a repository that uses generic interfaces: .Repository definitions using generic interfaces ==== [source, java] ---- interface AmbiguousRepository extends Repository { … } @NoRepositoryBean interface MyBaseRepository extends CrudRepository { … } interface AmbiguousUserRepository extends MyBaseRepository { … } ---- `AmbiguousRepository` and `AmbiguousUserRepository` extend only `Repository` and `CrudRepository` in their type hierarchy. While this is perfectly fine when using a unique Spring Data module, multiple modules cannot distinguish to which particular Spring Data these repositories should be bound. ==== The following example shows a repository that uses domain classes with annotations: [[repositories.multiple-modules.annotations]] .Repository definitions using domain classes with annotations ==== [source, java] ---- interface PersonRepository extends Repository { … } @Entity class Person { … } interface UserRepository extends Repository { … } @Node class User { … } ---- `PersonRepository` references `Person`, which is annotated with the JPA `@Entity` annotation, so this repository clearly belongs to Spring Data JPA. `UserRepository` references `User`, which is annotated with SDN/RX's `@Node` annotation. ==== The following bad example shows a repository that uses domain classes with mixed annotations: .Repository definitions using domain classes with mixed annotations ==== [source, java] ---- interface JpaPersonRepository extends Repository { … } interface Neo4jPersonRepository extends Repository { … } @Entity @Node class Person { … } ---- This example shows a domain class using both JPA and Spring Data Neo4j⚡RX annotations. It defines two repositories, `JpaPersonRepository` and `Neo4jPersonRepository`. One is intended for JPA and the other for Neo4j usage. Spring Data is no longer able to tell the repositories apart, which leads to undefined behavior. ==== <> and <> are used for strict repository configuration to identify repository candidates for a particular Spring Data module. Using multiple persistence technology-specific annotations on the same domain type is possible and enables reuse of domain types across multiple persistence technologies. However, Spring Data can then no longer determine a unique module with which to bind the repository. The last way to distinguish repositories is by scoping repository base packages. Base packages define the starting points for scanning for repository interface definitions, which implies having repository definitions located in the appropriate packages. The following example shows annotation-driven configuration of base packages: .Annotation-driven configuration of base packages ==== [source, java] ---- @Configuration @EnableJpaRepositories(basePackages = ""com.acme.repositories.jpa"") @EnableNeo4jRepositories(basePackages = ""com.acme.repositories.neo4j"") class Config { } ---- ==== [[repositories.query-methods.details]] == Defining Query Methods The repository proxy has two ways to derive a store-specific query from the method name: * By deriving the query from the method name directly. * By using a manually defined query. The next section describes the available options. [[repositories.query-methods.query-lookup-strategies]] === Query Lookup Strategies The following strategies are available for the repository infrastructure to resolve the query. In your Java configuration, you can use the `queryLookupStrategy` attribute of the `EnableNeo4jRepositories` annotation. - `CREATE` attempts to construct a store-specific query from the query method name. The general approach is to remove a given set of well known prefixes from the method name and parse the rest of the method. You can read more about query construction in ""`<>`"". - `USE_DECLARED_QUERY` tries to find a declared query and throws an exception if cannot find one. The query can be defined by an annotation somewhere or declared by other means. Consult the documentation of the specific store to find available options for that store. If the repository infrastructure does not find a declared query for the method at bootstrap time, it fails. - `CREATE_IF_NOT_FOUND` (default) combines `CREATE` and `USE_DECLARED_QUERY`. It looks up a declared query first, and, if no declared query is found, it creates a custom method name-based query. This is the default lookup strategy and, thus, is used if you do not configure anything explicitly. It allows quick query definition by method names but also custom-tuning of these queries by introducing declared queries as needed. [[repositories.query-methods.query-creation]] === Query Creation The query builder mechanism built into Spring Data repository infrastructure is useful for building constraining queries over entities of the repository. The mechanism strips the prefixes `find…By`, `read…By`, `query…By`, `count…By`, and `get…By` from the method and starts parsing the rest of it. The introducing clause can contain further expressions, such as a `Distinct` to set a distinct flag on the query to be created. However, the first `By` acts as delimiter to indicate the start of the actual criteria. At a very basic level, you can define conditions on entity properties and concatenate them with `And` and `Or`. The following example shows how to create a number of queries: .Query creation from method names ==== [source, java] ---- interface PersonRepository extends Repository { List findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname); // Enables the distinct flag for the query List findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname); List findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname); // Enabling ignoring case for an individual property List findByLastnameIgnoreCase(String lastname); // Enabling ignoring case for all suitable properties List findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname); // Enabling static ORDER BY for a query List findByLastnameOrderByFirstnameAsc(String lastname); List findByLastnameOrderByFirstnameDesc(String lastname); } ---- ==== There are some general things to notice: - The expressions are usually property traversals combined with operators that can be concatenated. You can combine property expressions with `AND` and `OR`. You also get support for operators such as `Between`, `LessThan`, `GreaterThan`, and `Like` for the property expressions. - The method parser supports setting an `IgnoreCase` flag for individual properties (for example, `findByLastnameIgnoreCase(…)`) or for all properties of a type that supports ignoring case (usually `String` instances -- for example, `findByLastnameAndFirstnameAllIgnoreCase(…)`). - You can apply static ordering by appending an `OrderBy` clause to the query method that references a property and by providing a sorting direction (`Asc` or `Desc`). To create a query method that supports dynamic sorting, see ""`<>`"". [[repositories.query-methods.query-property-expressions]] === Property Expressions Property expressions can refer only to a direct property of the managed entity, as shown in the preceding example. At query creation time, you already make sure that the parsed property is a property of the managed domain class. However, you can also define constraints by traversing nested properties. Consider the following method signature: [source, java] ---- List findByAddressZipCode(ZipCode zipCode); ---- Assume a `Person` has an `Address` with a `ZipCode`. In that case, the method creates the property traversal `x.address.zipCode`. The resolution algorithm starts by interpreting the entire part (`AddressZipCode`) as the property and checks the domain class for a property with that name (uncapitalized). If the algorithm succeeds, it uses that property. If not, the algorithm splits up the source at the camel case parts from the right side into a head and a tail and tries to find the corresponding property -- in our example, `AddressZip` and `Code`. If the algorithm finds a property with that head, it takes the tail and continues building the tree down from there, splitting the tail up in the way just described. If the first split does not match, the algorithm moves the split point to the left (`Address`, `ZipCode`) and continues. Although this should work for most cases, it is possible for the algorithm to select the wrong property. Suppose the `Person` class has an `addressZip` property as well. The algorithm would match in the first split round already, choose the wrong property, and fail (as the type of `addressZip` probably has no `code` property). To resolve this ambiguity you can use `_` inside your method name to manually define traversal points. So our method name would be as follows: [source, java] ---- List findByAddress_ZipCode(ZipCode zipCode); ---- Because we treat the underscore character as a reserved character, we strongly advise following standard Java naming conventions (that is, not using underscores in property names but using camel case instead). [[repositories.special-parameters]] === Special parameter handling To handle parameters in your query, define method parameters as already seen in the preceding examples. Besides that, the infrastructure recognizes certain specific types like `Pageable` and `Sort`, to apply pagination and sorting to your queries dynamically. The following example demonstrates these features: .Using `Pageable`, `Slice`, and `Sort` in query methods ==== [source, java] ---- Page findByLastname(String lastname, Pageable pageable); Slice findByLastname(String lastname, Pageable pageable); List findByLastname(String lastname, Sort sort); List findByLastname(String lastname, Pageable pageable); ---- ==== IMPORTANT: APIs taking `Sort` and `Pageable` expect non-`null` values to be handed into methods. If you don't want to apply any sorting or pagination use `Sort.unsorted()` and `Pageable.unpaged()`. The first method lets you pass an `org.springframework.data.domain.Pageable` instance to the query method to dynamically add paging to your statically defined query. A `Page` knows about the total number of elements and pages available. It does so by the infrastructure triggering a count query to calculate the overall number. As this might be expensive (depending on the store used), you can instead return a `Slice`. A `Slice` only knows about whether a next `Slice` is available, which might be sufficient when walking through a larger result set. Sorting options are handled through the `Pageable` instance, too. If you only need sorting, add an `org.springframework.data.domain.Sort` parameter to your method. As you can see, returning a `List` is also possible. In this case, the additional metadata required to build the actual `Page` instance is not created (which, in turn, means that the additional count query that would have been necessary is not issued). Rather, it restricts the query to look up only the given range of entities. NOTE: To find out how many pages you get for an entire query, you have to trigger an additional count query. By default, this query is derived from the query you actually trigger. [[repositories.paging-and-sorting]] ==== Paging and Sorting Simple sorting expressions can be defined by using property names. Expressions can be concatenated to collect multiple criterias into one expression. .Defining sort expressions ==== [source, java] ---- Sort sort = Sort.by(""firstname"").ascending() .and(Sort.by(""lastname"").descending()); ---- ==== For a more type-safe way of defining sort expressions, start with the type to define the sort expression for and use method references to define the properties to sort on. .Defining sort expressions using the type-safe API ==== [source, java] ---- TypedSort person = Sort.sort(Person.class); TypedSort sort = person.by(Person::getFirstname).ascending() .and(person.by(Person::getLastname).descending()); ---- ==== [[repositories.limit-query-result]] === Limiting Query Results The results of query methods can be limited by using the `first` or `top` keywords, which can be used interchangeably. An optional numeric value can be appended to `top` or `first` to specify the maximum result size to be returned. If the number is left out, a result size of 1 is assumed. The following example shows how to limit the query size: .Limiting the result size of a query with `Top` and `First` ==== [source, java] ---- User findFirstByOrderByLastnameAsc(); User findTopByOrderByAgeDesc(); Page queryFirst10ByLastname(String lastname, Pageable pageable); Slice findTop3ByLastname(String lastname, Pageable pageable); List findFirst10ByLastname(String lastname, Sort sort); List findTop10ByLastname(String lastname, Pageable pageable); ---- ==== The limiting expressions also support the `Distinct` keyword. Also, for the queries limiting the result set to one instance, wrapping the result into with the `Optional` keyword is supported. If pagination or slicing is applied to a limiting query pagination (and the calculation of the number of pages available), it is applied within the limited result. NOTE: Limiting the results in combination with dynamic sorting by using a `Sort` parameter lets you express query methods for the 'K' smallest as well as for the 'K' biggest elements. [[repositories.collections-and-iterables]] === Repository Methods Returning Collections or Iterables Query methods that return multiple results can use standard Java `Iterable`, `List`, `Set`. Beyond that we support returning Spring Data's `Streamable`, a custom extension of `Iterable`, as well as collection types provided by https://www.vavr.io/[Vavr]. [[repositories.collections-and-iterables.streamable]] ==== Using Streamable as Query Method Return Type `Streamable` can be used as alternative to `Iterable` or any collection type. It provides convenience methods to access a non-parallel `Stream` (missing from `Iterable`), the ability to directly `….filter(…)` and `….map(…)` over the elements and concatenate the `Streamable` to others: .Using Streamable to combine query method results ==== [source, java] ---- interface PersonRepository extends Repository { Streamable findByFirstnameContaining(String firstname); Streamable findByLastnameContaining(String lastname); } Streamable result = repository.findByFirstnameContaining(""av"") .and(repository.findByLastnameContaining(""ea"")); ---- ==== [[repositories.collections-and-iterables.streamable-wrapper]] ==== Returning Custom Streamable Wrapper Types Providing dedicated wrapper types for collections is a commonly used pattern to provide API on a query execution result that returns multiple elements. Usually these types are used by invoking a repository method returning a collection-like type and creating an instance of the wrapper type manually. That additional step can be avoided as Spring Data allows to use these wrapper types as query method return types if they meet the following criterias: . The type implements `Streamable`. . The type exposes either a constructor or a static factory method named `of(…)` or `valueOf(…)` taking `Streamable` as argument. A sample use case looks as follows: ==== [source, java] ---- class Product { <.> MonetaryAmount getPrice() { … } } @RequiredArgConstructor(staticName = ""of"") class Products implements Streamable { <.> private Streamable streamable; public MonetaryAmount getTotal() { <.> return streamable.stream() // .map(Priced::getPrice) .reduce(Money.of(0), MonetaryAmount::add); } } interface ProductRepository implements Repository { Products findAllByDescriptionContaining(String text); <.> } ---- <.> A `Product` entity that exposes API to access the product's price. <.> A wrapper type for a `Streamable` that can be constructed via `Products.of(…)` (factory method created via the Lombok annotation). <.> The wrapper type exposes additional API calculating new values on the `Streamable`. <.> That wrapper type can be used as query method return type directly. No need to return `Stremable` and manually wrap it in the repository client. ==== [[repositories.collections-and-iterables.vavr]] ==== Support for Vavr Collections https://www.vavr.io/[Vavr] is a library to embrace functional programming concepts in Java. It ships with a custom set of collection types that can be used as query method return types. [options=header] |==== |Vavr collection type|Used Vavr implementation type|Valid Java source types |`io.vavr.collection.Seq`|`io.vavr.collection.List`|`java.util.Iterable` |`io.vavr.collection.Set`|`io.vavr.collection.LinkedHashSet`|`java.util.Iterable` |`io.vavr.collection.Map`|`io.vavr.collection.LinkedHashMap`|`java.util.Map` |==== The types in the first column (or subtypes thereof) can be used as quer method return types and will get the types in the second column used as implementation type depending on the Java type of the actual query result (third column). Alternatively, `Traversable` (Vavr the `Iterable` equivalent) can be declared and we derive the implementation class from the actual return value, i.e. a `java.util.List` will be turned into a Vavr `List`/`Seq`, a `java.util.Set` becomes a Vavr `LinkedHashSet`/`Set` etc. [[repositories.nullability]] === Null Handling of Repository Methods As of Spring Data 2.0, repository CRUD methods that return an individual aggregate instance use Java 8's `Optional` to indicate the potential absence of a value. Besides that, Spring Data supports returning the following wrapper types on query methods: * `com.google.common.base.Optional` * `scala.Option` * `io.vavr.control.Option` Alternatively, query methods can choose not to use a wrapper type at all. The absence of a query result is then indicated by returning `null`. Repository methods returning collections, collection alternatives, wrappers, and streams are guaranteed never to return `null` but rather the corresponding empty representation. See ""`<>`"" for details. [[repositories.nullability.annotations]] ==== Nullability Annotations You can express nullability constraints for repository methods by using link:{spring-framework-docs}/core.html#null-safety[Spring Framework's nullability annotations]. They provide a tooling-friendly approach and opt-in `null` checks during runtime, as follows: * {spring-framework-javadoc}/org/springframework/lang/NonNullApi.html[`@NonNullApi`]: Used on the package level to declare that the default behavior for parameters and return values is to not accept or produce `null` values. * {spring-framework-javadoc}/org/springframework/lang/NonNull.html[`@NonNull`]: Used on a parameter or return value that must not be `null` (not needed on a parameter and return value where `@NonNullApi` applies). * {spring-framework-javadoc}/org/springframework/lang/Nullable.html[`@Nullable`]: Used on a parameter or return value that can be `null`. Spring annotations are meta-annotated with https://jcp.org/en/jsr/detail?id=305[JSR 305] annotations (a dormant but widely spread JSR). JSR 305 meta-annotations let tooling vendors such as https://www.jetbrains.com/help/idea/nullable-and-notnull-annotations.html[IDEA], https://help.eclipse.org/oxygen/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/task-using_external_null_annotations.htm[Eclipse], and link:https://kotlinlang.org/docs/reference/java-interop.html#null-safety-and-platform-types[Kotlin] provide null-safety support in a generic way, without having to hard-code support for Spring annotations. To enable runtime checking of nullability constraints for query methods, you need to activate non-nullability on the package level by using Spring’s `@NonNullApi` in `package-info.java`, as shown in the following example: .Declaring Non-nullability in `package-info.java` ==== [source, java] ---- @org.springframework.lang.NonNullApi package com.acme; ---- ==== Once non-null defaulting is in place, repository query method invocations get validated at runtime for nullability constraints. If a query execution result violates the defined constraint, an exception is thrown. This happens when the method would return `null` but is declared as non-nullable (the default with the annotation defined on the package the repository resides in). If you want to opt-in to nullable results again, selectively use `@Nullable` on individual methods. Using the result wrapper types mentioned at the start of this section continues to work as expected: An empty result is translated into the value that represents absence. The following example shows a number of the techniques just described: .Using different nullability constraints ==== [source, java] ---- package com.acme; <.> import org.springframework.lang.Nullable; interface UserRepository extends Repository { User getByEmailAddress(EmailAddress emailAddress); <.> @Nullable User findByEmailAddress(@Nullable EmailAddress emailAdress); <.> Optional findOptionalByEmailAddress(EmailAddress emailAddress); <.> } ---- <.> The repository resides in a package (or sub-package) for which we have defined non-null behavior. <.> Throws an `EmptyResultDataAccessException` when the query executed does not produce a result. Throws an `IllegalArgumentException` when the `emailAddress` handed to the method is `null`. <.> Returns `null` when the query executed does not produce a result. Also accepts `null` as the value for `emailAddress`. <.> Returns `Optional.empty()` when the query executed does not produce a result. Throws an `IllegalArgumentException` when the `emailAddress` handed to the method is `null`. ==== [[repositories.nullability.kotlin]] ==== Nullability in Kotlin-based Repositories Kotlin has the definition of https://kotlinlang.org/docs/reference/null-safety.html[nullability constraints] baked into the language. Kotlin code compiles to bytecode, which does not express nullability constraints through method signatures but rather through compiled-in metadata. Make sure to include the `kotlin-reflect` JAR in your project to enable introspection of Kotlin's nullability constraints. Spring Data repositories use the language mechanism to define those constraints to apply the same runtime checks, as follows: .Using nullability constraints on Kotlin repositories ==== [source, kotlin] ---- interface UserRepository : Repository { fun findByUsername(username: String): User <.> fun findByFirstname(firstname: String?): User? <.> } ---- <.> The method defines both the parameter and the result as non-nullable (the Kotlin default). The Kotlin compiler rejects method invocations that pass `null` to the method. If the query execution yields an empty result, an `EmptyResultDataAccessException` is thrown. <.> This method accepts `null` for the `firstname` parameter and returns `null` if the query execution does not produce a result. ==== [[repositories.query-streaming]] === Streaming query results The results of query methods can be processed incrementally by using a Java 8 `Stream` as return type. Instead of wrapping the query results in a `Stream` data store-specific methods are used to perform the streaming, as shown in the following example: .Stream the result of a query with Java 8 `Stream` ==== [source, java] ---- @Query(""MATCH (u:User) RETURN u"") Stream findAllByCustomQueryAndStream(); Stream readAllByFirstnameNotNull(); @Query(""MATCH (u:User) RETURN u) Stream streamAllPaged(Pageable pageable); ---- ==== NOTE: A `Stream` potentially wraps underlying data store-specific resources and must, therefore, be closed after usage. You can either manually close the `Stream` by using the `close()` method or by using a Java 7 `try-with-resources` block, as shown in the following example: .Working with a `Stream` result in a try-with-resources block ==== [source, java] ---- try (Stream stream = repository.findAllByCustomQueryAndStream()) { stream.forEach(…); } ---- ==== NOTE: Not all Spring Data modules currently support `Stream` as a return type. [[repositories.query-async]] === Async query results Repository queries can be run asynchronously by using link:{spring-framework-docs}/integration.html#scheduling[Spring's asynchronous method execution capability]. This means the method returns immediately upon invocation while the actual query execution occurs in a task that has been submitted to a Spring `TaskExecutor`. Asynchronous query execution is different from reactive query execution and should not be mixed. Refer to store-specific documentation for more details on reactive support. The following example shows a number of asynchronous queries: ==== [source, java] ---- @Async Future findByFirstname(String firstname); <.> @Async CompletableFuture findOneByFirstname(String firstname); <.> @Async ListenableFuture findOneByLastname(String lastname); <.> ---- <.> Use `java.util.concurrent.Future` as the return type. <.> Use a Java 8 `java.util.concurrent.CompletableFuture` as the return type. <.> Use a `org.springframework.util.concurrent.ListenableFuture` as the return type. ==== [[repositories.create-instances]] == Creating Repository Instances In this section, you create instances and bean definitions for the defined repository interfaces. NOTE: This section is only relevant if you don't work in a Spring Boot scenario. SDN/RX provides dedicated support for Spring Boot, including automatic configuration of the Neo4j driver, Repositories and entity scanning. + Please be aware that SDN/RX does not support XML based Spring configuration. [[repositories.create-instances.java-config]] === JavaConfig The repository infrastructure is triggered by using either `@EnableNeo4jRepositories` or `EnableReactiveNeo4jRepositories` annotation on a JavaConfig class. For an introduction into Java-based configuration of the Spring container, see link:{spring-framework-docs}/core.html#beans-java[JavaConfig in the Spring reference documentation]. WARNING: While the Neo4j driver contains support for blocking and reactive programming in one single jar, blocking and reactive programming style should not be mixed in one application. A sample configuration to enable Spring Data Neo4j repositories resembles the following: .Sample annotation based repository configuration ==== [source, java] ---- include::../../examples/docs/src/main/java/org/neo4j/doc/springframework/data/docs/repositories/Config.java[tag=java-config-imperative] ---- ==== <.> Mark this as a Spring Configuration class <.> Enable imperative Neo4j repositories <.> Enable transactions <.> `AbstractNeo4jConfig` provides all the beans needed for SDN/RX to work <.> Provide a connection to the database <.> This is optional: Preconfigure the list of packages where SDN/RX should look for `@Node`-annotated classes The configuration of reactive repositories looks very similar: .Sample annotation based reactive repository configuration ==== [source,java] ---- include::../../examples/docs/src/main/java/org/neo4j/doc/springframework/data/docs/repositories/ReactiveConfig.java[tag=java-config-reactive] ---- ==== The driver has the same type. Please note that you need at least Neo4j 4.0 to use the reactive sessions provided by the driver. [[repositories.custom-implementations]] == Custom Implementations for Spring Data Repositories This section covers repository customization and how fragments form a composite repository. When a query method requires a different behavior or cannot be implemented by query derivation, then it is necessary to provide a custom implementation. Spring Data repositories let you provide custom repository code and integrate it with generic CRUD abstraction and query method functionality. [[repositories.single-repository-behavior]] === Customizing Individual Repositories To enrich a repository with custom functionality, you must first define a fragment interface and an implementation for the custom functionality, as shown in the following example: .Interface for custom repository functionality ==== [source, java] ---- interface CustomizedUserRepository { void someCustomMethod(User user); } ---- ==== Then you can let your repository interface additionally extend from the fragment interface, as shown in the following example: .Implementation of custom repository functionality ==== [source, java] ---- class CustomizedUserRepositoryImpl implements CustomizedUserRepository { public void someCustomMethod(User user) { // Your custom implementation } } ---- ==== NOTE: The most important part of the class name that corresponds to the fragment interface is the `Impl` postfix. The implementation itself does not depend on Spring Data and can be a regular Spring bean. Consequently, you can use standard dependency injection behavior to inject references to other beans (such as a `Neo4jClient` or the `Neo4jTemplate`), take part in aspects, and so on. You can let your repository interface extend the fragment interface, as shown in the following example: .Changes to your repository interface ==== [source, java] ---- interface UserRepository extends CrudRepository, CustomizedUserRepository { // Declare query methods here } ---- ==== Extending the fragment interface with your repository interface combines the CRUD and custom functionality and makes it available to clients. Spring Data repositories are implemented by using fragments that form a repository composition. Fragments are the base repository, functional aspects and custom interfaces along with their implementation. Each time you add an interface to your repository interface, you enhance the composition by adding a fragment. The base repository and repository aspect implementations are provided by each Spring Data module. The following example shows custom interfaces and their implementations: .Fragments with their implementations ==== [source, java] ---- interface HumanRepository { void someHumanMethod(User user); } class HumanRepositoryImpl implements HumanRepository { public void someHumanMethod(User user) { // Your custom implementation } } interface ContactRepository { void someContactMethod(User user); User anotherContactMethod(User user); } class ContactRepositoryImpl implements ContactRepository { public void someContactMethod(User user) { // Your custom implementation } public User anotherContactMethod(User user) { // Your custom implementation } } ---- ==== The following example shows the interface for a custom repository that extends `CrudRepository`: .Changes to your repository interface ==== [source, java] ---- interface UserRepository extends CrudRepository, HumanRepository, ContactRepository { // Declare query methods here } ---- ==== Repositories may be composed of multiple custom implementations that are imported in the order of their declaration. Custom implementations have a higher priority than the base implementation and repository aspects. This ordering lets you override base repository and aspect methods and resolves ambiguity if two fragments contribute the same method signature. Repository fragments are not limited to use in a single repository interface. Multiple repositories may use a fragment interface, letting you reuse customizations across different repositories. The following example shows a repository fragment and its implementation: .Fragments overriding `save(…)` ==== [source, java] ---- interface CustomizedSave { S save(S entity); } class CustomizedSaveImpl implements CustomizedSave { public S save(S entity) { // Your custom implementation } } ---- ==== The following example shows a repository that uses the preceding repository fragment: .Customized repository interfaces ==== [source, java] ---- interface UserRepository extends CrudRepository, CustomizedSave { } interface PersonRepository extends CrudRepository, CustomizedSave { } ---- ==== ==== Configuration The repository infrastructure tries to autodetect custom implementation fragments by scanning for classes below the package in which it found a repository. These classes need to follow the naming convention of appending the store's `repositoryImplementationPostfix` attribute to the fragment interface name. This postfix defaults to `Impl`. The following example shows a configuration changing the default postfix to `MyPostfix`: .Configuration example ==== [source, java] ---- include::../../examples/docs/src/main/java/org/neo4j/doc/springframework/data/docs/repositories/CustomFragmentPostfix.java[tag=all] ---- ==== With this configuration, SDN/RX tries to look up a class called `com.acme.repository.CustomizedUserRepositoryMyPostfix` to act as a custom repository implementation. [[repositories.single-repository-behaviour.ambiguity]] ===== Resolution of Ambiguity If multiple implementations with matching class names are found in different packages, Spring Data uses the bean names to identify which one to use. Given the following two custom implementations for the `CustomizedUserRepository` shown earlier, the first implementation is used. Its bean name is `customizedUserRepositoryImpl`, which matches that of the fragment interface (`CustomizedUserRepository`) plus the postfix `Impl`. .Resolution of ambiguous implementations ==== [source, java] ---- package com.acme.impl.one; class CustomizedUserRepositoryImpl implements CustomizedUserRepository { // Your custom implementation } ---- [source, java] ---- package com.acme.impl.two; @Component(""specialCustomImpl"") class CustomizedUserRepositoryImpl implements CustomizedUserRepository { // Your custom implementation } ---- ==== If you annotate the `UserRepository` interface with `@Component(""specialCustom"")`, the bean name plus `Impl` then matches the one defined for the repository implementation in `com.acme.impl.two`, and it is used instead of the first one. [[repositories.manual-wiring]] ===== Manual Wiring If your custom implementation uses annotation-based configuration and autowiring only, the preceding approach shown works well, because it is treated as any other Spring bean. If your implementation fragment bean needs special wiring, you can declare the bean and name it according to the conventions described in the <>. The infrastructure then refers to the manually defined bean definition by name instead of creating one itself. [[repositories.customize-base-repository]] === Customize the Base Repository The approach described in the <> requires customization of each repository interfaces when you want to customize the base repository behavior so that all repositories are affected. To change behavior for all repositories instead, you can create an implementation that extends the repository base class. This class then acts as a custom base class for the repository proxies, as shown in the following example: .Custom repository base class ==== [source, java] ---- public class MyRepositoryImpl extends SimpleNeo4jRepository { MyRepositoryImpl( Neo4jOperations neo4jOperations, Neo4jEntityInformation entityInformation ) { super(neo4jOperations, entityInformation); } @Override public List findAll() { throw new UnsupportedOperationException( ""This implementation does not support `findAll`.""); } } ---- ==== CAUTION: The class needs to have a constructor matching `SimpleNeo4jRepository` or `SimpleReactiveNeo4jRepository`. The final step is to make the Spring Data infrastructure aware of the customized repository base class. In Java configuration, you can do so by using the `repositoryBaseClass` attribute of the `@Enable$Neo4jRepositories` annotation, as shown in the following example: .Configuring a custom repository base class using JavaConfig ==== [source, java] ---- @Configuration @EnableNeo4jRepositories(repositoryBaseClass = MyRepositoryImpl.class) @EnableTransactionManagement public class Config extends AbstractNeo4jConfig { @Bean public Driver driver() { return GraphDatabase .driver(""neo4j://localhost:7687"", AuthTokens.basic(""neo4j"", ""secret"")); } } ---- ==== [[core.domain-events]] == Publishing Events from Aggregate Roots Entities managed by repositories are aggregate roots. In a Domain-Driven Design application, these aggregate roots usually publish domain events. Spring Data provides an annotation called `@DomainEvents` that you can use on a method of your aggregate root to make that publication as easy as possible, as shown in the following example. First, define a custom event: .Defining a custom domain event: ==== [source, java] ---- include::../../examples/docs/src/test/java/org/neo4j/doc/springframework/data/docs/repositories/domain_events/SomeEvent.java[tag=domain-events] ---- <1> You have to inherit from Spring's `ApplicationEvent` ==== The next step is to expose these events from a `@Node` entity: .Exposing domain events from an aggregate root ==== [source, java] ---- include::../../examples/docs/src/test/java/org/neo4j/doc/springframework/data/docs/repositories/domain_events/AnAggregateRoot.java[tag=domain-events] ---- <.> Store your events in a collection and mark that collection as `@Transient` so that those events are not treated as a relationship to be stored <.> Whenever you need to log an event, add it to the events collection <.> Mark one method with `@DomainEvents`. The method must not take any arguments and can return either a single event instance or a collection of events. <.> After all events have been published, we have a method annotated with `@AfterDomainEventPublication`. It can be used to potentially clean the list of events to be published (among other uses). ==== The methods are called every time one of a Spring Data repository's `save(…)` methods is called as shown in the following snippets: .Store the aggregate root via standard repository calls ==== [source, java] ---- include::../../examples/docs/src/test/java/org/neo4j/doc/springframework/data/docs/repositories/domain_events/DomainEventsTest.java[tag=domain-events] ---- ==== To react on this events, register a standard Spring `ApplicationListener`, typed to your event: .Create a custom event listener ==== [source, java,indent=0] ---- include::../../examples/docs/src/test/java/org/neo4j/doc/springframework/data/docs/repositories/domain_events/DomainEventsApplication.java[tag=domain-events] ---- ==== [[core.extensions]] == Spring Data Extensions This section documents a set of Spring Data extensions that enable Spring Data usage in a variety of contexts. Currently, most of the integration is targeted towards Spring MVC. [[core.web]] === Web support Spring Data modules that support the repository programming model ship with a variety of web support. The web related components require Spring MVC JARs to be on the classpath. Some of them even provide integration with https://github.com/SpringSource/spring-hateoas[Spring HATEOAS]. In general, the integration support is enabled by using the `@EnableSpringDataWebSupport` annotation in your JavaConfig configuration class, as shown in the following example: .Enabling Spring Data web support ==== [source, java] ---- @Configuration @EnableWebMvc @EnableSpringDataWebSupport class WebConfiguration {} ---- ==== The `@EnableSpringDataWebSupport` annotation registers a few components we will discuss in a bit. It will also detect Spring HATEOAS on the classpath and register integration components for it as well if present. [[core.web.basic]] ==== Basic Web Support The configuration shown in the <> registers a few basic components: - A <> to let Spring MVC resolve instances of repository-managed domain classes from request parameters or path variables. - <> implementations to let Spring MVC resolve `Pageable` and `Sort` instances from request parameters. [[core.web.basic.domain-class-converter]] ===== `DomainClassConverter` The `DomainClassConverter` lets you use domain types in your Spring MVC controller method signatures directly, so that you need not manually lookup the instances through the repository, as shown in the following example: .A Spring MVC controller using domain types in method signatures ==== [source, java] ---- @Controller @RequestMapping(""/users"") class UserController { @RequestMapping(""/{id}"") String showUserForm(@PathVariable(""id"") User user, Model model) { model.addAttribute(""user"", user); return ""userForm""; } } ---- ==== As you can see, the method receives a `User` instance directly, and no further lookup is necessary. The instance can be resolved by letting Spring MVC convert the path variable into the `id` type of the domain class first and eventually access the instance through calling `findById(…)` on the repository instance registered for the domain type. NOTE: Currently, the repository has to implement `CrudRepository` to be eligible to be discovered for conversion. [[core.web.basic.paging-and-sorting]] ===== HandlerMethodArgumentResolvers for Pageable and Sort The configuration snippet shown in the <> also registers a `PageableHandlerMethodArgumentResolver` as well as an instance of `SortHandlerMethodArgumentResolver`. The registration enables `Pageable` and `Sort` as valid controller method arguments, as shown in the following example: .Using Pageable as controller method argument ==== [source, java] ---- @Controller @RequestMapping(""/users"") class UserController { private final UserRepository repository; UserController(UserRepository repository) { this.repository = repository; } @RequestMapping String showUsers(Model model, Pageable pageable) { model.addAttribute(""users"", repository.findAll(pageable)); return ""users""; } } ---- ==== The preceding method signature causes Spring MVC try to derive a `Pageable` instance from the request parameters by using the following default configuration: .Request parameters evaluated for `Pageable` instances [options = ""autowidth""] |=============== |`page`|Page you want to retrieve. 0-indexed and defaults to 0. |`size`|Size of the page you want to retrieve. Defaults to 20. |`sort`|Properties that should be sorted by in the format `property,property(,ASC\\|DESC)`. Default sort direction is ascending. Use multiple `sort` parameters if you want to switch directions -- for example, `?sort=firstname&sort=lastname,asc`. |=============== To customize this behavior, register a bean implementing the `PageableHandlerMethodArgumentResolverCustomizer` interface or the `SortHandlerMethodArgumentResolverCustomizer` interface, respectively. Its `customize()` method gets called, letting you change settings, as shown in the following example: [source, java] ---- @Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() { return s -> s.setPropertyDelimiter(""<-->""); } ---- If setting the properties of an existing `MethodArgumentResolver` is not sufficient for your purpose, extend either `SpringDataWebConfiguration` or the HATEOAS-enabled equivalent, override the `pageableResolver()` or `sortResolver()` methods, and import your customized configuration file instead of using the `@Enable` annotation. If you need multiple `Pageable` or `Sort` instances to be resolved from the request (for multiple tables, for example), you can use Spring's `@Qualifier` annotation to distinguish one from another. The request parameters then have to be prefixed with `${qualifier}_`. The following example shows the resulting method signature: [source, java] ---- String showUsers(Model model, @Qualifier(""thing1"") Pageable first, @Qualifier(""thing2"") Pageable second) { … } ---- you have to populate `thing1_page` and `thing2_page` and so on. The default `Pageable` passed into the method is equivalent to a `PageRequest.of(0, 20)` but can be customized by using the `@PageableDefault` annotation on the `Pageable` parameter. [[core.web.pageables]] ==== Hypermedia Support for Pageables Spring HATEOAS ships with a representation model class (`PagedResources`) that allows enriching the content of a `Page` instance with the necessary `Page` metadata as well as links to let the clients easily navigate the pages. The conversion of a Page to a `PagedResources` is done by an implementation of the Spring HATEOAS `ResourceAssembler` interface, called the `PagedResourcesAssembler`. The following example shows how to use a `PagedResourcesAssembler` as a controller method argument: .Using a PagedResourcesAssembler as controller method argument ==== [source, java] ---- @Controller class PersonController { @Autowired PersonRepository repository; @RequestMapping(value = ""/persons"", method = RequestMethod.GET) HttpEntity> persons(Pageable pageable, PagedResourcesAssembler assembler) { Page persons = repository.findAll(pageable); return new ResponseEntity<>(assembler.toResources(persons), HttpStatus.OK); } } ---- ==== Enabling the configuration as shown in the preceding example lets the `PagedResourcesAssembler` be used as a controller method argument. Calling `toResources(…)` on it has the following effects: - The content of the `Page` becomes the content of the `PagedResources` instance. - The `PagedResources` object gets a `PageMetadata` instance attached, and it is populated with information from the `Page` and the underlying `PageRequest`. - The `PagedResources` may get `prev` and `next` links attached, depending on the page's state. The links point to the URI to which the method maps. The pagination parameters added to the method match the setup of the `PageableHandlerMethodArgumentResolver` to make sure the links can be resolved later. Assume we have 30 Person instances in the database. You can now trigger a request (`GET http://localhost:8080/persons`) and see output similar to the following: [source, javascript] ---- { ""links"" : [ { ""rel"" : ""next"", ""href"" : ""http://localhost:8080/persons?page=1&size=20 } ], ""content"" : [ … // 20 Person instances rendered here ], ""pageMetadata"" : { ""size"" : 20, ""totalElements"" : 30, ""totalPages"" : 2, ""number"" : 0 } } ---- You see that the assembler produced the correct URI and also picked up the default configuration to resolve the parameters into a `Pageable` for an upcoming request. This means that, if you change that configuration, the links automatically adhere to the change. By default, the assembler points to the controller method it was invoked in, but that can be customized by handing in a custom `Link` to be used as base to build the pagination links, which overloads the `PagedResourcesAssembler.toResource(…)` method. [[core.repository-populators]] === Repository Populators If you work with the Spring JDBC module, you are probably familiar with the support to populate a `DataSource` with SQL scripts. A similar abstraction is available on the repositories level, although it does not use SQL as the data definition language because it must be store-independent. Thus, the populators support XML (through Spring's OXM abstraction) and JSON (through Jackson) to define data with which to populate the repositories. Assume you have a file `data.json` with the following content: .Data defined as JSON ==== [source, json] ---- include::../../examples/docs/src/test/resources/data.json[] ---- ==== The `_class` keys point to your domain class, in this case a `MovieEntity` .Corresponding entity ==== [source, java] ---- include::../../examples/docs/src/test/java/org/neo4j/doc/springframework/data/docs/repositories/populators/MovieEntity.java[tag=populators] ---- ==== If you don't provide a custom constructor, you need to help the Jackson JSON library a bit by providing a so called mixin, teaching Jackson how to instantiate the object: .Optional Jackson module helping Jackson with your domain ==== [source, java] ---- include::../../examples/docs/src/test/java/org/neo4j/doc/springframework/data/docs/repositories/populators/MovieModule.java[tag=populators] ---- ==== And finally, you declare a `FactoryBean It is important that you inject the `ObjectMapper` from the context as this takes care of all registered Jackson Modules <2> Here you point to `data.json` resource ==== The preceding declaration causes the `data.json` file to be read and deserialized by the Jackson `ObjectMapper`. The type to which the JSON object is unmarshalled is determined by inspecting the `_class` attribute of the JSON document. The infrastructure eventually selects the appropriate repository to handle the object that was deserialized. To instead use XML to define the data the repositories should be populated with, you need to use a `UnmarshallerRepositoryPopulatorFactoryBean` and a JAXB2 marshaller. ",12196,False,2112.910074122738,median "// // ******************************************************************** // * DISCLAIMER * // * * // * The following disclaimer summarizes all the specific disclaimers * // * of contributors to this software. The specific disclaimers,which * // * govern, are listed with their locations in: * // * http://cern.ch/geant4/license * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. * // * * // * This code implementation is the intellectual property of the * // * GEANT4 collaboration. * // * By copying, distributing or modifying the Program (or any work * // * based on the Program) you indicate your acceptance of this * // * statement, and all its terms. * // * * // * This version (C) 2018 Jayson Vavrek under the MIT License. * // ******************************************************************** // // ------------ G4NRF physics process -------- // // File name: G4NRF // Author: David Jordan (david.jordan@pnl.gov) // Creation date: October 2006 // // Modifications: Jayson Vavrek (jvavrek@mit.edu) // Moderate to major bug fixes, new cross section evaluation, // enhanced documentation. // Release date: August 2018 // // How to use this physics process: // // (1) Store ENSDF-derived nuclear level and gamma emission // files in a directory pointed to by the environment // variable $G4NRFGAMMADATA. These files include: // z[Z-value].a[A-value] -- default photon evaporation files // gamma_table_nnn.dat -- supplementary info for gamma emission // level_table_nnn.dat -- supplementary level info // ground_state_properties.dat // // // (2) At the top of the user's physicsList class, add: // // #include ""G4NRFPhysics.hh"" // // Then inside physicsList::ConstructPhysics(), add: // // RegisterPhysics(new G4NRFPhysics(""NRF"", use_xsec_tables, // use_xsec_integration, force_isotropic)); // // where use_xsec_tables, use_xsec_integration, force_isotropic // are boolean values for whether to use NRF cross section // table interpolation (instead of on-the-fly evaluation), // whether to use the high-accuracy numerically-integrated // form of the cross section, and whether to force isotropic // emission of NRF photons. Recommended: true, true, either. // Rather than set flags in the physicsList, the user may want // to use command-line arguments. // // // (3) Material definition requirements: Materials should be constructed // from elements containing G4Isotopes in order to trigger // calculation of NRF cross sections. NRF interactions can still // occur using, e.g. NIST-defined materials, but this has not been // tested extensively. // // Example (in user's DetectorConstruction class): // // // Natural Oxygen // // G4Isotope *O16 = new G4Isotope(name=""O16"", iz=8, n=16, a=15.995*g/mole); // G4Isotope *O17 = new G4Isotope(name=""O17"", iz=8, n=17, a=16.999*g/mole); // G4Isotope *O18 = new G4Isotope(name=""O18"", iz=8, n=18, a=17.992*g/mole); // G4Element *NatO = new G4Element // (name=""Natural Oxygen"", symbol=""O"", ncomponents=3); // NatO->AddIsotope(O16, abundance=99.757*perCent); // NatO->AddIsotope(O17, abundance= 0.038*perCent); // NatO->AddIsotope(O18, abundance= 0.205*perCent); // // ------------------------------------------------------------------- //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // ------------------------------------------------------------------- // // Description: // // G4NRF.cc is the main Geant4 code for simulating nuclear resonance fluorescence // (NRF). It primarily calculates the NRF cross section for gamma rays incident on // a properly-defined material, then calculates the final state if an NRF interaction // is determined to occur. // // // Major updates to the G4NRF class by Jayson Vavrek (2018): // // 0) Ended up replacing NRF_xsec_calc() entirely. Old version is now called // NRF_xsec_calc_gaus(). New version performs numerical integration of the // integral rather than a Gaussain approximation, and calulates the effective // temperature using the new Debye temperature database file. See the methods // PsiIntegral() and expIntegrand(). // // 1) Since the numerical integration can introduce a performance penalty, added // the option to build a table of numerically-integrated cross section values // vs photon energy at initialization instead of integrating on the fly. At // runtime, the sigma vs E table is interpolated using Geant4's c2_function // capabilities. This results in at least 40% faster event rates with much // higher accuracy, and could likely be optimized even further. See the // methods InterpolateCrossSection() and MakeCrossSectionTable(). // // 2) In NRF_xsec_calc(), added some basic functionality to interrupt the code // when an NRF event is triggered with a cross section above some level for // debugging of cross section formulae. User must manually set // const bool interrupt = false; // to take advantage of this if so desired, and un-comment the lines checking // for interrupt in NRF_xsec_calc, etc. // // 3) Introduction of the print_to_standalone() function, which can be used to // generate a standalone plaintext NRF gamma database. A full database print // takes about 10-15 minutes (with a 2.4 GHz i5 on a late 2011 Mac.) User must // manually set // const bool standalone = true; // in this file, and may manually adjust the Z/A ranges of isotopes in the // print_to_standalone() method below. // // 4) Encapsulation of G4NRF by the G4NRFPhysics class, which allows inheritance // from G4VPhysicsConstructor as per Geant4 standards for adding custom physics // processes. Furthermore, used SetProcessType() and SetProcessSubType(), both // of which are set to fHadronic. // // ------------------------------------------------------------------- #include ""G4NRF.hh"" #include #include #include ""G4ios.hh"" #include ""G4UnitsTable.hh"" #include ""G4Material.hh"" #include ""G4Element.hh"" #include ""G4NRFNuclearLevelStore.hh"" #include ""G4Exp.hh"" using std::cos; using std::pow; const bool interrupt = false; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** // constructor G4NRF::G4NRF(const G4String& processName, G4bool Verbose_in, G4bool use_xsec_tables_in, G4bool use_xsec_integration_in, G4bool force_isotropic_in) : G4VDiscreteProcess(processName), Verbose(Verbose_in), use_xsec_tables(use_xsec_tables_in), use_xsec_integration(use_xsec_integration_in), force_isotropic_ang_corr(force_isotropic_in) { if (Verbose) { G4cout << ""&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"" << G4endl; G4cout << ""G4NRF Constructor is being called. "" << G4endl; G4cout << ""Process name: "" << processName << G4endl; G4cout << ""&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"" << G4endl; } if (use_xsec_tables && !use_xsec_integration) { G4cout << ""Error! Table interpolation with Gaussian xsec approx not currently supported."" << G4endl; G4cout << ""Aborting..."" << G4endl; exit(48); } G4cout << std::boolalpha; G4cout << ""G4NRF settings:"" << G4endl; G4cout << "" use_xsec_tables = "" << use_xsec_tables << G4endl; G4cout << "" use_xsec_integration = "" << use_xsec_integration << G4endl; G4cout << "" force_isotropic = "" << force_isotropic_ang_corr << G4endl << G4endl;; pAngular_Correlation = new Angular_Correlation; SetProcessType(fHadronic); SetProcessSubType(fHadronic); // print gamma info to a datafile and disable some error checking in G4NRFNuclearLevelManager // user may change this manually to activate output const bool standalone = false; if (standalone) { ofstream standaloneFile(""standalone.dat""); print_to_standalone(standaloneFile); standaloneFile.close(); } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** // destructor G4NRF::~G4NRF() {;} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** void G4NRF::PrintInfoDefinition() { G4String comments = ""NRF process.\\n""; G4cout << G4endl << GetProcessName() << "": "" << comments; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... // **************************************************************************************************** // Calculates the mean free path for NRF excitation in GEANT4 internal units. // Note: If no nearby level for resonant gamma excitation, mean free path is // returned as DBL_MAX. G4double G4NRF::GetMeanFreePath(const G4Track& aTrack, G4double previousStepSize, // these two parameters G4ForceCondition* condition) { // are not used G4Material* aMaterial = aTrack.GetMaterial(); G4double GammaEnergy = aTrack.GetDynamicParticle()->GetKineticEnergy(); const G4int NumberOfElements = aMaterial->GetNumberOfElements(); const G4ElementVector* theElementVector = aMaterial->GetElementVector(); const G4double* NbOfAtomsPerVolume = aMaterial->GetVecNbOfAtomsPerVolume(); if (Verbose) { G4cout << ""In G4NRF::GetMeanFreePath."" << G4endl; G4cout << ""Name of current material: "" << aMaterial->GetName() << G4endl; G4cout << ""Number of elements: "" << NumberOfElements << G4endl; G4cout << ""List of element names: "" << G4endl; } // Search for nearest level for NRF excitation from ground // state. Search terminates at first (element, isotope, level) // such that the level energy is within E_TOL of the incoming // gamma energy, taking into account nuclear recoil upon absorption. // Note: Search is based on kinematics only, regardless of // the value of the NRF cross section for the level. const G4double E_TOL = 1.0 * keV; G4bool found_nearby_level = false; G4int jelm = 0; G4double xsec = 0.0; G4double sigma = 0.0; // default mean free path // Search elements contained in current material while ((jelm < NumberOfElements) && (!found_nearby_level)) { G4Element* pElement = (*theElementVector)[jelm]; G4double Atom_number_density = NbOfAtomsPerVolume[jelm]; G4int num_isotopes = pElement->GetNumberOfIsotopes(); if (Verbose) { G4cout << pElement->GetName() << G4endl; G4cout << ""G4NRF::GetMeanFreePath -- Atomic number density (#/cm^3): "" << Atom_number_density /(1.0/cm3) << G4endl; G4cout << ""Number of isotopes in this element: "" << num_isotopes << G4endl; } A_excited = -1; Z_excited = -1; pLevel_excited = NULL; // Search isotopes contained within current element G4int jisotope = 0; while ((jisotope < num_isotopes) && (!found_nearby_level)) { const G4Isotope* pIsotope = pElement->GetIsotope(jisotope); G4int A = pIsotope->GetN(); // n.b. N is # of nucleons, NOT neutrons! G4int Z = pIsotope->GetZ(); if (Verbose) { G4cout << ""G4NRF::GetMeanFreePath -- Isotope "" << pIsotope->GetName() << "" Z= "" << Z << "" A= "" << A << G4endl; G4cout << ""Fetching level manager from G4NuclearLevelStore."" << G4endl; } pNuclearLevelManager = G4NRFNuclearLevelStore::GetInstance()->GetManager(Z, A); // Can the incoming gamma excite a level in this isotope // (kinematic constraint only)? if (Verbose) { //pNuclearLevelManager->PrintAll(); // this is really verbose G4cout << ""G4NRFGetMeanFreePath -- Searching for nearby level to E_gamma= "" << GammaEnergy << G4endl; } G4NRFNuclearLevel* pLevel = pNuclearLevelManager->NearestLevelRecoilAbsorb(GammaEnergy, E_TOL); // If kinematics permit gamma excitation of a level, store (A, Z) // and pointer to the level for use in PostStepDoIt, and calculate // NRF cross section and mean free path. if (pLevel != NULL) { // i.e., kinematics permit gamma excitation if (Verbose) { G4cout << ""G4NRFGetMeanFreePath -- Found level at energy "" << pLevel->Energy() << G4endl; } found_nearby_level = true; // setting this ends the search A_excited = A; // stash A, Z, level pointer Z_excited = Z; // for use in PostStepDoIt pLevel_excited = pLevel; // Cross section & mean free path calculation follows if (use_xsec_integration) xsec = NRF_xsec_calc(GammaEnergy, pLevel, use_xsec_tables); else xsec = NRF_xsec_calc_gaus(GammaEnergy, pLevel); // Calculate isotope number density const G4double* pIsotopeAbundance = pElement->GetRelativeAbundanceVector(); G4double frac_abundance = pIsotopeAbundance[jisotope]; if (Verbose) { G4cout << ""G4NRF::GetMeanFreePath -- Fractional abundance: "" << frac_abundance << G4endl; } G4double Isotope_number_density = Atom_number_density * frac_abundance; // sigma is mean free path = (cross section)*(isotope number density) sigma = Isotope_number_density * xsec; if (Verbose) { G4cout << ""G4NRF::GetMeanFreePath: sigma (cm^-1): "" << sigma/(1.0/cm) << G4endl; } } else { if (Verbose) { G4cout << ""G4NRF::GetMeanFreePath -- Could not find nearby level."" << G4endl; } jisotope++; // move on to next isotope in current element } } // loop over isotopes (terminate if nearby level found) jelm++; // move on to next element in current material } // loop over elements (terminate if nearby level found) return sigma > DBL_MIN ? 1.0/sigma : DBL_MAX; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4double G4NRF::NRF_xsec_calc_gaus(G4double GammaEnergy, const G4NRFNuclearLevel* pLevel) { // Calculates Doppler-broadened NRF cross section using formulas from // Metzger, ""Resonance Fluorescence in Nuclei"", in Prog. Nuc. Phys. // 7 (1959), pp. 54-88. Currently the temperature is fixed at 300 K. // // Formula for Doppler-broadened cross section is // // xsec(E) = pi^(3/2) * (lamda_bar)^2 * (2J1+1)/(2J0+1) * (Tau0/Delta) * exp[-((E-Er)/Delta))^2], // // where // E = gamma energy // lamda_bar = corresponding gamma wavelength / 2pi // Er = resonance energy // J0 = angular momentum of ground state // J1 = angular momentum of excited state // Tau0 = partial width of excited state for transition to g.s. // and // Delta = E*sqrt(2kT/M) // // with // T = absolute temperature // M = nuclear mass // // This expression for xsec(E) is obtained from Metzger's equations (3), (11), // and the unlabeled equation between (7) and (8). // // Input parameters: // GammaEnergy -- internal Geant4 units // J0 -- g.s. spin // A -- isotope atomic weight // pLevel -- pointer to excited state level // // N.B. The excited state level pointer is used to fetch J1, // energy E1, and the partial width Tau0. // // Output: // xsec -- NRF cross section in Geant4 internal units const G4int Z = pLevel->Z(); // isotope Z const G4int A = pLevel->A(); // isotope A G4NRFNuclearLevelManager *pManager = G4NRFNuclearLevelStore::GetInstance()->GetManager(Z, A); const G4double E = GammaEnergy; const G4double J1 = pLevel->AngularMomentum(); const G4double J0 = pManager->GetGroundStateSpin(); const G4double E1 = pLevel->Energy(); const G4double Tau0 = pLevel->Width0(); //const G4double stat_fac = (2.0*J1 + 1.0)/(2.0*J0 + 1.0); // moved factor of 2 to fac1 below const G4double stat_fac = (2.0*J1 + 1.0)/(2.0*J0 + 1.0)/2.0; const G4double lamda_bar = hbarc/E; // should be E_r, but unimportant near resonance? // Calculate resonance energy, accounting // for nuclear recoil in non-relativistic // approximation (and neglecting nuclear // mass defect) const G4double M = A * amu_c2; const G4double E_recoil = E1*E1/M; const G4double E_r = E1 + E_recoil/2.0; // Assume room temperature for now const G4double T = 300.0*kelvin; const G4double Delta = E * sqrt(2.0*k_Boltzmann*T/M); const G4double Pi_To_1pt5 = 5.568328; const G4double fac1 = 2.0 * Pi_To_1pt5 * pow(lamda_bar, 2.0); // added factor of 2 here, which was previously in stat_fac const G4double fac2 = Tau0/Delta; const G4double tmp = (E-E_r)/Delta; const G4double fac3 = exp(-tmp*tmp); // the infamous Gaussian approximation const G4double xsec = fac1 * stat_fac * fac2 * fac3; if (Verbose) { G4cout << std::setprecision(12); G4cout << ""------------------------------------"" << G4endl; G4cout << ""In G4NRF::NRF_xsec_calc_gaus. "" << G4endl; G4cout << ""GammaEnergy (MeV): "" << GammaEnergy/MeV << G4endl; G4cout << ""J0: "" << J0 << G4endl; G4cout << ""J1: "" << J1 << G4endl; G4cout << ""A: "" << A << G4endl; G4cout << ""Level energy (MeV): "" << E1/MeV << G4endl; G4cout << ""Tau0 (eV): "" << Tau0/eV << G4endl; G4cout << ""lambda_bar (fm): "" << lamda_bar/fermi << G4endl; G4cout << ""Delta (eV): "" << Delta/eV << G4endl; G4cout << ""fac1: "" << fac1 << G4endl; G4cout << ""fac2: "" << fac2 << G4endl; G4cout << ""fac3: "" << fac3 << G4endl; G4cout << ""stat_fac: "" << stat_fac << G4endl; G4cout << ""E (MeV): "" << E/MeV << G4endl; G4cout << ""E_r (MeV): "" << E_r/MeV << G4endl; G4cout << ""tmp: "" << tmp << G4endl; G4cout << ""E_recoil (keV): "" << E_recoil/keV << G4endl; G4cout << ""xsec (barn): "" << xsec/barn << G4endl; G4cout << ""------------------------------------"" << G4endl; } //if (interrupt and xsec/barn > 1.0 /*and E_r/MeV > 2.14 and E_r/MeV < 2.15*/) exit(10); return xsec; } void G4NRF::SetParam_x(G4double x) {param_x = x;} G4double G4NRF::GetParam_x() const {return param_x;} void G4NRF::SetParam_t(G4double t) {param_t = t;} G4double G4NRF::GetParam_t() const {return param_t;} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4double G4NRF::NRF_xsec_calc(G4double GammaEnergy, G4NRFNuclearLevel* pLevel, G4bool useTables, G4int nMeshpoints, G4double sigmaBound) { // Calculate the Doppler-broadened NRF cross section without resorting to the Gaussian approximation // in Metzger (1959). Instead, do the numerical integration by calling PsiIntegral(). See the above // NRF_xsec_calc_gaus() and inline comments below for further documentation. Note: this method // returns the *absorption* cross section, and the decay selection happens in PostStepDoIt(). const G4int Z = pLevel->Z(); // isotope Z const G4int A = pLevel->A(); // isotope A G4NRFNuclearLevelManager *pManager = G4NRFNuclearLevelStore::GetInstance()->GetManager(Z, A); const G4double E = GammaEnergy; // incident gamma energy const G4double E1 = pLevel->Energy(); // excited state energy const G4double J1 = pLevel->AngularMomentum(); // excited state spin const G4double J0 = pManager->GetGroundStateSpin(); // ground state spin const G4double Gamma_r = pLevel->Width(); // level width const G4double Gamma_0r = pLevel->Width0(); // partial width // compute the statistical spin factor const G4double stat_fac = (2.0*J1 + 1.0)/(2.0*J0 + 1.0)/2.0; // compute the average recoil energy, and add half of it to the level energy // hitting the resonance requires just a little more energy on top of the level due to recoil // half the recoil comes in absorption step, half in decay const G4double M = A * amu_c2; const G4double E_recoil = E*E/M; const G4double E_r = E1 + E_recoil/2.0; // Get the effective temperature for Doppler broadening from the Manager; use 300 K if unknown const G4double T_Debye = pManager->GetTDebye(); const G4double T_eff_tmp = pManager->GetTeff(); const G4double T_eff = (T_eff_tmp > 0 ? T_eff_tmp : 300*kelvin); const G4double Delta_eff = E * sqrt(2.0*k_Boltzmann*T_eff/M); const G4double rootPi = 1.77245385; // dimensionless parameters for the numerical integration in PsiIntegral() const G4double x = 2.0 * (E-E_r) / Gamma_r; const G4double teff = Delta_eff * Delta_eff / Gamma_r / Gamma_r; SetParam_x(x); SetParam_t(teff); // Compute the NRF _absorption_ cross section. Decay to final state is handled in PostStepDoIt() const G4double fac1 = 2.0 * rootPi * stat_fac; const G4double fac2 = hbarc*hbarc/E_r/E_r; const G4double fac3 = Gamma_0r / Delta_eff; G4double xsec, fac4; if (useTables) { fac4 = 0; if (pLevel->GetCrossSectionTable() == NULL) MakeCrossSectionTable(pLevel, T_eff); xsec = InterpolateCrossSection(pLevel, E); } else { fac4 = PsiIntegral(x, teff, nMeshpoints, sigmaBound); xsec = fac1 * fac2 * fac3 * fac4; } if (Verbose || (interrupt && xsec/barn > 1.0)) { G4cout << std::setprecision(12); G4cout << ""------------------------------------"" << G4endl; G4cout << ""In G4NRF::NRF_xsec_calc. "" << G4endl; G4cout << ""Z: "" << Z << G4endl; G4cout << ""A: "" << A << G4endl; G4cout << ""E (MeV): "" << E << G4endl; G4cout << ""E_level (MeV): "" << E1/MeV << G4endl; G4cout << ""E_r (MeV): "" << E_r/MeV << G4endl; G4cout << ""E_recoil (eV): "" << E_recoil/eV << G4endl; G4cout << ""E_emit (MeV): "" << ""sampled in PostStepDoIt()"" << G4endl; G4cout << ""J0: "" << J0 << G4endl; G4cout << ""J1: "" << J1 << G4endl; G4cout << ""stat_fac: "" << stat_fac << G4endl; G4cout << ""T_eff: "" << T_eff/kelvin << G4endl; G4cout << ""T_Debye: "" << T_Debye/kelvin << G4endl; G4cout << ""Gamma_r (eV): "" << Gamma_r/eV << G4endl; G4cout << ""Gamma_r0 (eV): "" << Gamma_0r/eV << G4endl; G4cout << ""Delta_eff (eV): "" << Delta_eff/eV << G4endl; G4cout << ""x: "" << x << G4endl; G4cout << ""teff: "" << teff << G4endl; G4cout << ""fac1: "" << fac1 << G4endl; G4cout << ""fac2 (barn): "" << fac2/barn << G4endl; G4cout << ""fac3: "" << fac3 << G4endl; G4cout << ""fac4 (= Psi): "" << fac4 << G4endl; G4cout << ""Psi(0, teff) "" << PsiIntegral(0, teff) << G4endl; G4cout << ""xsec (barn): "" << xsec/barn << G4endl; G4cout << ""------------------------------------"" << G4endl; G4cout << G4endl; } if (interrupt && xsec/barn > 20.0 && E_r/MeV > 2.1 && E_r/MeV < 2.2) exit(11); //if (interrupt && xsec/barn > 1.0 && E_r/MeV > 2.20 && E_r/MeV < 2.30 && Z == 92 && A == 238) {exit(12);} return xsec; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4VParticleChange* G4NRF::PostStepDoIt(const G4Track& trackData, const G4Step& stepData) { aParticleChange.Initialize(trackData); const G4DynamicParticle* aDynamicParticle = trackData.GetDynamicParticle(); G4double KineticEnergy = aDynamicParticle->GetKineticEnergy(); // G4ParticleMomentum ParticleDirection = aDynamicParticle->GetMomentumDirection(); G4ThreeVector IncidentGammaDirection = aDynamicParticle->GetMomentumDirection(); if (Verbose) { G4cout << ""In G4NRF::PostStepDoIt."" << G4endl; G4cout << ""KineticEnergy (MeV): "" << KineticEnergy/MeV << G4endl; G4cout << ""Info on excited state nucleus follows:"" << G4endl; G4cout << ""Z_excited = "" << Z_excited << G4endl; G4cout << ""A_excited = "" << A_excited << G4endl; } G4bool first_pass = true; G4double energy_deposit = 0.0; pNuclearLevelManager = G4NRFNuclearLevelStore::GetInstance()->GetManager(Z_excited, A_excited); if (pNuclearLevelManager) { const G4NRFNuclearLevel* pLevel = pLevel_excited; if (!pLevel) { G4cout << ""ERROR in G4NRF::PostStepDoIt."" << G4endl; G4cout << ""pLevel is NULL."" << G4endl; G4cout << ""Z_excited = "" << Z_excited << G4endl; G4cout << ""A_excited = "" << A_excited << G4endl; G4cout << ""Gamma kinetic energy (MeV): "" << KineticEnergy/MeV << G4endl; G4cout << ""Aborting."" << G4endl; exit(13); } G4bool continue_cascade = true; while (continue_cascade) { G4double Level_energy = pLevel->Energy(); G4int nLevel = pLevel->nLevel(); if (Verbose) { G4cout << ""G4NRF::PostStepDoIt -- "" << G4endl; G4cout << "" Curent level index: nLevel = "" << nLevel << G4endl; G4cout << "" Current level energy (MeV) = "" << Level_energy/MeV << G4endl; } // At each step in the cascade: // (1) Select (gamma or c.e.) energy from current level // (2) Determine next level in the cascade // (3) If gamma, sample its direction & generate it // (4) Update local energy deposit // (1) Select gamma. Note: G4NRFLevel reports gamma energy as negative // if internal conversion has occurred. The integer index jgamma // (returned by reference) labels which gamma from the current // level (jgamma = 0, 1, ..., ngammas-1) was selected. The // nuclear recoil (for gamma emission) is added to the local // energy deposit. G4int jgamma; G4double E_gamma = pLevel->SelectGamma(jgamma); // randomly selects from the level's list of known gammas if (Verbose) { G4cout << "" Selected gamma energy (MeV): "" << E_gamma/MeV << G4endl; G4cout << "" Gamma index: "" << jgamma << G4endl; } // (2) Determine final level based on initial level energy // and sampled (gamma or c.e.) energy. Terminate the cascade if... // (i) Current level index is 1, indicating 1st excited state, so // transition to g.s. is the only possibility. // (ii) Current level index is > 1, and the gamma selected corresponds // to transition to g.s. (signature of this is that the final // level point is NULL, indicating that the level does not appear // in the excited-state levels database) const G4NRFNuclearLevel* pLevel_next = NULL; G4double Level_energy_next = 0.0; // default is transition to g.s. if (nLevel > 1) { // i.e. currently above 1st excited state pLevel_next = pNuclearLevelManager->NearestLevelRecoilEmit(Level_energy, fabs(E_gamma), 1.0*keV); if (pLevel_next) { // found excited state at lower energy than current state Level_energy_next = pLevel_next->Energy(); if (Verbose) G4cout << ""Found excited state at lower energy than current state"" << G4endl; } else { // could not find next excited state, so must be g.s. transition if (Verbose) { G4cout << ""Did not find deexcitation to excited state. Assume gs transition."" << G4endl; } continue_cascade = false; } } else { // i.e. currently at 1st excited state, so g.s. transition is only possibility continue_cascade = false; if (Verbose) { G4cout << ""Terminating cascade."" << G4endl; } } // (3) For gamma emission, sample gamma direction and generate it (i.e. // add it to the list of generated secondaries). N.B. Only worry about // multipolarity information on first pass, i.e. after initial excitation // from g.s. to the current excited state. This is because the ""standard"" // gamma angular correlation theoretical formalism assumes that the starting // state in the cascade has all magnetic sub-levels equally populated (e.g., // g.s. at thermal equilibrium, room temperature). This does not hold for // state populated by first stage (excitation, de-excitation) of NRF // cascade, i.e. after the first (gamma, gamma) correlation. Thus just give // up after 1st cascade photon emission and sample isotropically thereafter. G4ThreeVector emitted_gamma_direction; // NRF emission gamma direction G4bool gamma_emission = E_gamma > 0.0; // E_gamma < 0 if c.e. // Check for forbidden transition (i.e. no 0->0 allowed) only if the // event already passed the E_gamma > 0.0 test. if (gamma_emission) gamma_emission = !ForbiddenTransition(pLevel, pLevel_next); if (gamma_emission) { // i.e. gamma emission, not conversion electron if (first_pass) { G4double J0, J, Jf; // Spin of initial, intermediate, & final levels G4int L1, L2; // Angular momentum of excitation, de-excitation gammas G4double Delta1, Delta2; // mixing ratios for excitation, de-excitation if (Verbose) { G4cout << ""Input to SetupMultipolarityInfo:"" << G4endl; G4cout << "" nLevel = "" << nLevel << G4endl; G4cout << "" E_gamma (MeV) = "" << E_gamma/MeV << G4endl; G4cout << "" jgamma = "" << jgamma << G4endl; } if (!force_isotropic_ang_corr) { SetupMultipolarityInfo(nLevel, E_gamma, jgamma, pLevel, pLevel_next, J0, J, Jf, L1, L2, Delta1, Delta2); if (Verbose) { G4cout << ""Input to SampleCorrelation:"" << G4endl; G4cout << "" J0 = "" << J0 << G4endl; G4cout << "" J = "" << J << G4endl; G4cout << "" Jf = "" << Jf << G4endl; G4cout << "" L1 = "" << L1 << G4endl; G4cout << "" L2 = "" << L2 << G4endl; G4cout << "" Delta1 = "" << Delta1 << G4endl; G4cout << "" Delta2 = "" << Delta2 << G4endl; } emitted_gamma_direction = SampleCorrelation(J0, J, Jf, L1, L2, Delta1, Delta2); if (Verbose) { G4cout << ""emitted_gamma_direction after SampleCorrelation call: "" << emitted_gamma_direction << G4endl; } emitted_gamma_direction.rotateUz(IncidentGammaDirection); } else { // User has chosen to disable angular correlations emitted_gamma_direction = SampleIsotropic(); } } else { // angular correlations not included after first pass (i.e., after first (gamma, gamma) pair) emitted_gamma_direction = SampleIsotropic(); } if (Verbose) { G4cout << ""G4NRF::PostStepDoIt -- Creating new gamma, direction = "" << emitted_gamma_direction << G4endl; } // Create G4DynamicParticle object for the emitted gamma and add it to the tracking stack. // IMPORTANT NOTE: this currently produces _monoenergetic_ photons with energy E_gamma, rather // than the incident energy minus the recoil! G4DynamicParticle* aGamma = new G4DynamicParticle(G4Gamma::Gamma(), emitted_gamma_direction, E_gamma); aParticleChange.AddSecondary(aGamma); } // gamma emission? (i.e. E_gamma > 0?) // (4) Update local energy deposit. For gamma emission, // deposit the recoil energy of the nucleus. For // conversion electron, simply deposit difference in (pre- // emission, post-emission) level energies. if (gamma_emission) { // calculate nuclear recoil for gamma emission const G4double M = A_excited * amu_c2; const G4double E_recoil = E_gamma*E_gamma/M; energy_deposit += E_recoil; } else { // conversion electron energy_deposit += Level_energy - Level_energy_next; } first_pass = false; pLevel = pLevel_next; } // continue de-excitation cascade? } else { // pNuclearLevelManager is NULL -- anomalous condition, shouldn't have occurred if G4NRF::GetMeanFreePath() behaved G4cout << ""ERROR in G4NRF::PostStepDoIT."" << G4endl; G4cout << ""pNuclearLevelManager is NULL."" << G4endl; G4cout << ""A_excited: "" << A_excited << G4endl; G4cout << ""Z_excited: "" << Z_excited << G4endl; G4cout << ""Aborting."" << G4endl; exit(14); } // Deposited energy corresponds to sum over entire cascade // (nuclear recoil & conversion electrons) aParticleChange.ProposeLocalEnergyDeposit(energy_deposit); // Kill the incident photon. Secondaries produced will consist // of 0, 1, ... NRF emission gammas. aParticleChange.ProposeTrackStatus(fStopAndKill); return G4VDiscreteProcess::PostStepDoIt(trackData, stepData); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** void G4NRF::SetupMultipolarityInfo(const G4int nLevel, const G4double E_gamma, const G4int jgamma, const G4NRFNuclearLevel* pLevel, const G4NRFNuclearLevel* pLevel_next, G4double& J0, G4double& J, G4double& Jf, G4int& L1, G4int& L2, G4double& Delta1, G4double& Delta2) { // Determines information on excitation & de-excitation gamma transition // multipolarity required for angular correlation sampling. // // Input quantities: // nLevel -- index of current level (i.e., excited state) // E_gamma -- energy of cascade gamma // jgamma -- index of cascade gamma emitted by current level // pLevel -- pointer to current level // pLevel_next -- point to de-excitation level (NULL if transition to g.s.) // // Output quantities (all passed back by reference): // J0 -- spin of starting level (ground state by assumption) // J -- spin of current level (i.e., excited state -- this is the intermediate state) // Jf -- spin of final level (may be g.s. or excited state of lower energy than current state) // L1 -- angular momentum of excitation gamma // L2 -- angular momentum of de-excitation gamma // Delta1 -- mixing coefficient for excitation channel // Delta2 -- mixing coefficient for de-excitation channel J0 = pNuclearLevelManager->GetGroundStateSpin(); G4double P0 = pNuclearLevelManager->GetGroundStateParity(); J = pLevel -> AngularMomentum(); G4double P = pLevel -> Parity(); G4double Pf; // If current level is above the excited state, then level following de-excitation could // be either g.s. or a lower-energy excited state. if (nLevel > 1) { // current level is higher than 1st excited if (pLevel_next) { // pointer to next level isn't NULL, so it's another excited state Jf = pLevel_next->AngularMomentum(); Pf = pLevel_next->Parity(); } else { // de-excitation to g.s. Jf = J0; Pf = P0; } } else { // currently at 1st excited state, so g.s. de-excitation is only possibility Jf = J0; Pf = P0; } // Need index to highest-energy gamma emitted from this level G4int ngamma = pLevel->NumberOfGammas(); // Excitation gamma multipole information: Assumption is that // the highest-energy gamma for the level is the gamma connecting // the level to the g.s. (On first pass, this is the only gamma // transition that could have led to the excitation.) So excitation // channel gamma MUST correspond to gamma index ngamma-1. De-excitation // can be through any gamma, jgamma = 0, 1, ..., ngamma-1. AssignMultipoles(pLevel, E_gamma, ngamma-1, J0, P0, J, P, L1, Delta1); if (jgamma != ngamma-1) { AssignMultipoles(pLevel, E_gamma, jgamma, J, P, Jf, Pf, L2, Delta2); } else { L2 = L1; Delta2 = Delta1; } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** void G4NRF::AssignMultipoles(const G4NRFNuclearLevel* pLevel, const G4double E_gamma, const G4int jgamma, const G4double Ji, const G4double Pi, const G4double Jf, const G4double Pf, G4int& L, G4double& Delta) { // Determine multipolarity information (multipole mode and mixing coefficient) // for a single gamma transition. // // Input quantitites: // pLevel -- point to current level // E_gamma -- gamma energy // jgamma -- index of gamma in set of gammas emitted by current level // Ji -- initial nuclear level's angular momentum // Jf -- final nuclear level's angular momentum // Pi -- initial parity // Pf -- final parity // // Output quantities (passed by reference): // L -- angular momentum of gamma // Delta -- multipole mixing coefficient // // Precondition: // Ji and Jf are not both equal to zero (i.e. info not sought for a forbidden transition) G4int Gamma_num_mult = (pLevel->MultipoleNumModes() )[jgamma]; char Gamma_multipole_mode1 = (pLevel->MultipoleMode1() )[jgamma]; G4int Gamma_multipole_L1 = (pLevel->MultipoleL1() )[jgamma]; // char Gamma_multipole_mode2 = (pLevel->MultipoleMode2() )[jgamma]; // G4int Gamma_multipole_L2 = (pLevel->MultipoleL2() )[jgamma]; G4double Gamma_mixing_ratio = (pLevel->MultipoleMixingRatio() )[jgamma]; G4int Gamma_mixing_sign_flag = (pLevel->MultipoleMixRatioSignFlag())[jgamma]; if (Verbose) { G4cout << ""G4NRF::AssignMultipoles:"" << G4endl; G4cout << "" Input Ji = "" << Ji << G4endl; G4cout << "" Jf = "" << Jf << G4endl; G4cout << "" Pi = "" << Pi << G4endl; G4cout << "" Pf = "" << Pf << G4endl; G4cout << "" Gamma_num_mult = "" << Gamma_num_mult << G4endl; G4cout << "" Gamma_multipole_mode1 = "" << Gamma_multipole_mode1 << G4endl; G4cout << "" Gamma_multipole_L1 = "" << Gamma_multipole_L1 << G4endl; G4cout << "" Gamma_mixing_ratio = "" << Gamma_mixing_ratio << G4endl; G4cout << "" Gamma_mixing_sign_flag = "" << Gamma_mixing_sign_flag << G4endl; } // Several possibilities for availability of ENSDF multipole info: // (1) No ENSDF multipolarity information available (this is indicated by // MultipoleNumModes() = 0.) // (2) There is one dominant multipole mode, indicated by // MultipoleNumModes() = 1. In this case the MultipoleMode1() returned // is 'E', 'M', or 'D', 'Q', or 'O' (for dipole, quadrupole, octupole, // respectively), and the MultipoleL1 is known. // (3) There are two multipole modes, MultipoleNumModes() = 2. MultipoleMode // and MultipoleL are known for both. Mixing ratio information may be // known: absolute value of ratio and the sign of the ratio. // Diagnostic for Weisskopf estimate of delta: Uncomment next line // Gamma_num_mult = 0; //force Weisskopf delta calc char transition; switch (Gamma_num_mult) { case 0: // No ENSDF info available. In this case, determine minimum L permitted // by selection rules, and calculate mixing coefficient based on // single-particle (Weisskopf) estimates. L = FindMin_L(Ji, Pi, Jf, Pf, transition); Delta = MixingRatio_WeisskopfEstimate(transition, L, E_gamma, Pi, Pf); if (Verbose) { G4cout << "" L from FindMin_L: "" << L << G4endl; G4cout << "" Delta from Weisskopf estimate: "" << Delta << G4endl; } break; case 1: // A single (presumably dominant) transition multipole according to // ENSDF. In this case, return the ENSDF multipolarity and set // the mixing coefficient to zero. L = Gamma_multipole_L1; Delta = 0.0; break; case 2: // ENSDF reports (at least) two multipoles. Return the // lowest multipole. If the mixing ratio is not known, // then return the Weisskopf estimate. N.B. if the // sign of the mixing ratio is not known, positive // will be assumed. L = Gamma_multipole_L1; if (Gamma_mixing_sign_flag != -1) { // N.B. mixing_sign_flag = -1 accompanies Delta = Gamma_mixing_ratio; // mixing_ratio = -999 for unknown ratio in ENSDF_parser_3.f } else { transition = Gamma_multipole_mode1; Delta = MixingRatio_WeisskopfEstimate(transition, L, E_gamma, Pi, Pf); } break; default: // Shouldn't get to this default case if ENSDF data parsing went as expected. G4cout << ""ERROR in G4NRF::AssignMultipoles."" << G4endl; G4cout << ""Unexpected value of Gamma_num_mult: "" << Gamma_num_mult << G4endl; G4cout << ""Aborting."" << G4endl; exit(15); break; } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4int G4NRF::FindMin_L(const G4double Ji, const G4double Pi, const G4double Jf, const G4double Pf, char& transition) { // Determine minimum multipolarity compatible with // angular momentum & polarity selection rules. See // e.g. Krane, Introductory Nuclear Physics, // (New York: John Wiley, 1988), pp. 334. G4double L; if (Ji != Jf) L = fabs(Ji-Jf); else L = 1.0; G4int Lint = int(L + 0.001); if (Lint % 2 == 0) { // L is even if (Pi == Pf) transition = 'E'; else transition = 'M'; } else { // L is odd if (Pi == Pf) transition = 'M'; else transition = 'E'; } return Lint; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4double G4NRF::MixingRatio_WeisskopfEstimate(char transition, const G4int L, const G4double E_gamma, const G4double Pi, const G4double Pf) { // Calcualate multipole mixing ratio based on single-particle (Weisskopf) // formulas for the transition probabilities. See Krane, Introductory Nuclear // Physics (New York: John Wiley, 1988), pp. 332-335. if (Verbose) { G4cout << ""In G4NRF::MixingRatio_WeisskopfEstimate."" << G4endl; G4cout << ""Input:"" << G4endl; G4cout << "" transition = "" << transition << G4endl; G4cout << "" L = "" << L << G4endl; G4cout << "" E_gamma (MeV) = "" << E_gamma/MeV << G4endl; G4cout << "" Pi = "" << Pi << G4endl; G4cout << "" Pf = "" << Pf << G4endl; } if (L > 3) return 0.0; const G4int L_prime = L + 1; char multipole; char multipole_prime; switch (transition) { case 'E': multipole = 'E'; break; case 'M': multipole = 'M'; break; case 'Q': // L is even if (Pi == Pf) multipole = 'E'; else multipole = 'M'; break; case 'D': // L is odd case 'O': if (Pi == Pf) multipole = 'M'; else multipole = 'E'; break; default: G4cout << ""Error in G4NRF::MixingRatio_WeisskopfEstimate."" << G4endl; G4cout << ""Unrecognized transition: "" << transition << G4endl; G4cout << ""Aborting."" << G4endl; exit(16); } if (multipole == 'E') multipole_prime = 'M'; else multipole_prime = 'E'; G4double lamda, lamda_prime; if (Verbose) { G4cout << "" Calling Lamda_Weisskopf with following arguments:"" << G4endl; G4cout << "" multipole = "" << multipole << G4endl; G4cout << "" multipole_prime = "" << multipole_prime << G4endl; G4cout << "" L = "" << L << G4endl; G4cout << "" L_prime = "" << L_prime << G4endl; G4cout << "" E_gamma (MeV) = "" << E_gamma/MeV << G4endl; } lamda = Lamda_Weisskopf(multipole, L, E_gamma); lamda_prime = Lamda_Weisskopf(multipole_prime, L_prime, E_gamma); G4double Delta = lamda_prime/lamda; if (Verbose) { G4cout << "" After calls to Lamda_Weisskopf:"" << G4endl; G4cout << "" lamda (1/sec): "" << lamda/(1.0/second) << G4endl; G4cout << "" lamda_prime (1/sec): "" << lamda_prime/(1.0/second) << G4endl; G4cout << "" Delta: "" << Delta << G4endl; } return Delta; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4double G4NRF::Lamda_Weisskopf(char multipole, const G4int L, const G4double E_gamma) { // Calculates single-particle (Weisskopf) transition // probability per unit time for multipole 'E' // or 'M', angular momentum L = 1, 2, 3, or 4, gamma // energy E_gamma. Uses approximate formulas taken // from Krane, Introductory Nuclear Physics, (New York: // John Wiley, 1988), p. 332 (formulas 10.13 and 10.15). // // Restrictions: // For L outside the range [1, 4], returns 0. // // Transition rate is returned in G4 internal units. G4double Lamda = 0.0; if ((L < 0) || (L > 4)) return Lamda; G4double A = double(A_excited); G4double E_MeV = E_gamma/MeV; if (multipole == 'E') { switch (L) { case 1: Lamda = (1.0e14) * pow(A, 0.666) * pow(E_MeV, 3.0); break; case 2: Lamda = (7.3e7) * pow(A, 1.333) * pow(E_MeV, 5.0); break; case 3: Lamda = (34.0) * pow(A, 2.0) * pow(E_MeV, 7.0); break; case 4: Lamda = (1.1e-5) * pow(A, 2.666) * pow(E_MeV, 9.0); break; } } else { // 'M' switch (L) { case 1: Lamda = (5.6e13) * pow(E_MeV, 3.0); break; case 2: Lamda = (2.5e7) * pow(A, 0.666) * pow(E_MeV, 5.0); break; case 3: Lamda = (16.0) * pow(A, 1.333) * pow(E_MeV, 7.0); break; case 4: Lamda = (4.5e-6) * pow(A, 2.0) * pow(E_MeV, 9.0); break; } } return Lamda * (1.0/second); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4ThreeVector G4NRF::SampleCorrelation(const G4double Ji, const G4double J, const G4double Jf, const G4int L1, const G4int L2, const G4double Delta1, const G4double Delta2) { // Samples gamma-gamma angular correlation. // // Input parameters: // Ji -- angular momentum of initial state // J -- "" "" of intermediate state // Jf -- "" "" of final state // L1 -- "" "" of initial->intemediate transition gamma // L2 -- "" "" of intemediate->final transition gamma // Delta1 -- multipole mixing ratio for initial->intermediate transition // Delta2 -- multipole mixing ratio for intermediate->final transition // // Output: // G4ThreeVector containing emission gamma momentum direction, in // frame of reference in which incident gamma direction defines // the positive z-axis. // // Calls: // Member functions ReInit() and Sample() of Angular_Correlation // class (via pointer to Angular_Correlation object). // // Limitation/restriction: // If the angular momentum parameters fall outside the range of // valid entries in the Angular_Correlation coefficient tables, // the emitted gamma direction is sampled isotropically. if (Verbose) { G4cout << ""In G4NRF::SampleCorrelation:"" << G4endl; G4cout << "" Ji = "" << Ji << G4endl; G4cout << "" J = "" << J << G4endl; G4cout << "" Jf = "" << Jf << G4endl; G4cout << "" L1 = "" << L1 << G4endl; G4cout << "" L2 = "" << L2 << G4endl; G4cout << "" Delta1 = "" << Delta1 << G4endl; G4cout << "" Delta2 = "" << Delta2 << G4endl; } // Are the input angular momentum parameters included in the // angular correlation coefficient tables contained in the // Angular_Correlation class? G4bool correlation_info_available = pAngular_Correlation->ReInit(J, Ji, Jf, L1, L2, Delta1, Delta2); if (correlation_info_available) { G4double y_rnd = G4UniformRand(); G4double cos_theta = pAngular_Correlation->Sample(y_rnd); G4double theta = acos(cos_theta); G4double sin_theta = sin(theta); G4double phi = 2.0*pi*G4UniformRand(); G4double cos_x = sin_theta*cos(phi); G4double cos_y = sin_theta*sin(phi); G4double cos_z = cos_theta; if (Verbose) { G4cout << "" G4NRF::SampleCorrelation --"" << G4endl; G4cout << "" y_rnd = "" << y_rnd << G4endl; G4cout << "" cos_theta = "" << cos_theta << G4endl; G4cout << "" pi = "" << pi << G4endl; G4cout << "" theta = "" << theta << G4endl; G4cout << "" sin_theta = "" << sin_theta << G4endl; G4cout << "" phi = "" << theta << G4endl; G4cout << "" cos_x = "" << cos_x << G4endl; G4cout << "" cos_y = "" << cos_y << G4endl; G4cout << "" cos_z = "" << cos_z << G4endl; } G4ThreeVector new_direc(cos_x, cos_y, cos_z); return new_direc; } else { // angular momenta aren't in Angular_Correlation coefficient tables -- bail out with isotropic emission direction return SampleIsotropic(); } } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4ThreeVector G4NRF::SampleIsotropic() { G4double cos_theta = -1.0 + 2.0*G4UniformRand(); G4double phi = 2.0*pi*G4UniformRand(); G4double theta = acos(cos_theta); G4double sin_theta = sin(theta); G4double cos_x = sin_theta*cos(phi); G4double cos_y = sin_theta*sin(phi); G4double cos_z = cos_theta; G4ThreeVector new_direc(cos_x, cos_y, cos_z); return new_direc; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo.... // **************************************************************************************************** G4bool G4NRF::ForbiddenTransition(const G4NRFNuclearLevel* pLevel, const G4NRFNuclearLevel* pLevel_next) { // Checks for forbidden 0 -> 0 gamma transitions. // // Returns true if the transition is forbidden, false if allowed. // Extracts initial (Ji) and final (Jf) angular momenta from // pointers to the initial and final levels, respectively. // If the final-level pointer is NULL, transition to ground // state is assumed. G4double Ji = pLevel->AngularMomentum(); G4double Jf; G4bool forbidden = false; if (pLevel_next) Jf = pLevel_next->AngularMomentum(); else Jf = pNuclearLevelManager->GetGroundStateSpin(); if ((Ji == 0.0) && (Jf == 0.0)) forbidden = true; return forbidden; } // perform the integral for doppler broadening numerically // this gives the most stable results G4double G4NRF::expIntegrand(G4double y) const { const G4double x = GetParam_x(); const G4double t = GetParam_t(); return G4Exp(-(x-y)*(x-y)/4.0/t) / (1.0+y*y); } // Numerical integration of the NRF cross section. Gives stable and fairly accurate results, // for only a ~20% speed penalty over the original Gaussian evaluation, when using the default // arguments nMeshpoints=300 (number of meshpoints) and sigmaBound=4.0 (number of 'sigma' in // the integrand to integrate between). For table building, will want to increase both args. G4double G4NRF::PsiIntegral(G4double x, G4double t, G4int nMeshpoints, G4double sigmaBound) { // Establish a cut to avoid integrations for obviously off-resonance photons. // Note that the integrand is a convolution of a Gaussian and Lorentzian, and thus has fat tails. // As a result, need to set the cuts fairly wide. (Ignoring fat tails has never caused any harm, right?) // Adjustable parameter ztol sets tolerance for far-off-resonance evaluations. // Since z = x/sqrt(t) = 2(E-E_r)/Delta, a ztol = 1.0e3 with Delta ~ 1 eV corresponds to (E-E_r) = 500 eV. // Use z2, ztol2 to avoid costly sqrt G4double z2 = x*x/t; G4double ztol2 = 1.0e6; if (z2 > ztol2) return 0; // Roundabout way of passing these to expIntegrand SetParam_x(x); SetParam_t(t); // integrate out to plus/minus 4 ""sigma"" for numerical stability const G4double theLowerLimit = -sigmaBound*sqrt(2.0*t); const G4double theUpperLimit = -theLowerLimit; // perform the integration G4double sum = integrator.Simpson(this, &G4NRF::expIntegrand, theLowerLimit, theUpperLimit, nMeshpoints); return sum; } void G4NRF::MakeCrossSectionTable(G4NRFNuclearLevel* pLevel, G4double Teff) { G4int A = pLevel->A(); G4int Z = pLevel->Z(); G4double E1 = pLevel->Energy(); G4double M = A * amu_c2; G4double Er = E1 + E1*E1/(2.0*M); // small approximation to use E1 instead of E, but it makes it constant for the table G4double Delta_eff = Er * sqrt(2.0*k_Boltzmann*Teff/M); G4cout << ""Building cross section table for Z = "" << Z << "", A = "" << A << "", Er/MeV = "" << Er << G4endl; std::vector cross_sec_tab; std::vector E_tab; // user may adjust the for loop bounds to change the NRF xsec table bounds // user may also adjust the inputs to NRF_xsec_calc below to change the accuracy of the table build for (G4double e = -10.0*Delta_eff; e <= 10.0*Delta_eff; e += Delta_eff/100.0) { G4double xsec = 0.0; if (use_xsec_integration) { xsec = NRF_xsec_calc(Er + e, pLevel, false, 10000, 10.0); } else { xsec = NRF_xsec_calc_gaus(Er + e, pLevel); } cross_sec_tab.push_back(xsec); E_tab.push_back(Er + e); } interpolating_function_p *cross_sec_interp_func = new interpolating_function_p(); cross_sec_interp_func->load(E_tab, cross_sec_tab, true, 0, true, 0, true); pLevel->SetCrossSectionTable(cross_sec_interp_func); G4cout << ""...built"" << G4endl; } G4double G4NRF::InterpolateCrossSection(const G4NRFNuclearLevel* pLevel, G4double GammaEnergy) { const interpolating_function_p *xsec_table = pLevel->GetCrossSectionTable(); if (GammaEnergy < xsec_table->xmin() || GammaEnergy > xsec_table->xmax()) return 0; else return xsec_table->value_with_derivatives(GammaEnergy, NULL, NULL); } // print cross section data to a standalone data file for later analysis by standalone.py // runs fairly quickly for small Z, A ranges of interest; takes ~15 minutes for entire database void G4NRF::print_to_standalone(ofstream& file) { G4cout << G4endl; G4cout << ""Calling G4NRF::print_to_standalone()"" << G4endl; for (int z = 4; z <= 100; ++z) { for (int a = z; a <= 3*z; ++a) { G4NRFNuclearLevelManager* pManager = G4NRFNuclearLevelStore::GetInstance()->GetManager(z, a, true); if (pManager) pManager->PrintAllTabular(file); } } G4cout << G4endl; } ",16325,True,2764.277417839276,median "/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include #include #include #include /////////////////////////////////////////////////////////////////////////////// bool TestExtArray::RunTests(const std::string &which) { bool ret = true; DECLARE_TEST_FUNCTIONS(""function odd($s1) {"" "" return $s1 & 1;"" ""}"" ""function even($s1) {"" "" return !($s1 & 1);"" ""}"" ""function cube($s1) {"" "" return $s1*$s1*$s1;"" ""}"" ""function rsum($s1,$s2) {"" "" return (int)$s1 + (int)$s2;"" ""}"" ""function rmul($s1,$s2) {"" "" return (int)$s1 * (int)$s2;"" ""}"" ""function test_print($item,$key) {"" "" echo \\""$key: $item\\\\n\\"";"" ""}"" ""function test_alter(&$item,$key,$prefix) {"" "" $item = $prefix.': '.$item;"" ""}"" ""function comp_func($n1,$n2) {"" "" $n1=(int)$n1; $n2=(int)$n2;"" "" return $n1 === $n2 ? 0 : ($n1 > $n2 ? 1 : -1);"" ""}"" ""function reverse_comp_func($n1,$n2) {"" "" $n1=(int)$n1; $n2=(int)$n2;"" "" return $n1 === $n2 ? 0 : ($n1 > $n2 ? -1 : 1);"" ""}"" ""function reverse_strcasecmp($s1,$s2) {"" "" return strcasecmp($s2,$s1);"" ""}"" ); RUN_TEST(test_array_change_key_case); RUN_TEST(test_array_chunk); RUN_TEST(test_array_combine); RUN_TEST(test_array_count_values); RUN_TEST(test_array_fill_keys); RUN_TEST(test_array_fill); RUN_TEST(test_array_filter); RUN_TEST(test_array_flip); RUN_TEST(test_array_key_exists); RUN_TEST(test_array_keys); RUN_TEST(test_array_map); RUN_TEST(test_array_merge_recursive); RUN_TEST(test_array_merge); RUN_TEST(test_array_replace_recursive); RUN_TEST(test_array_replace); RUN_TEST(test_array_multisort); RUN_TEST(test_array_pad); RUN_TEST(test_array_pop); RUN_TEST(test_array_product); RUN_TEST(test_array_push); RUN_TEST(test_array_rand); RUN_TEST(test_array_reduce); RUN_TEST(test_array_reverse); RUN_TEST(test_array_search); RUN_TEST(test_array_shift); RUN_TEST(test_array_slice); RUN_TEST(test_array_splice); RUN_TEST(test_array_sum); RUN_TEST(test_array_unique); RUN_TEST(test_array_unshift); RUN_TEST(test_array_values); RUN_TEST(test_array_walk_recursive); RUN_TEST(test_array_walk); RUN_TEST(test_compact); RUN_TEST(test_shuffle); RUN_TEST(test_count); RUN_TEST(test_sizeof); RUN_TEST(test_each); RUN_TEST(test_current); RUN_TEST(test_next); RUN_TEST(test_pos); RUN_TEST(test_prev); RUN_TEST(test_reset); RUN_TEST(test_end); RUN_TEST(test_in_array); RUN_TEST(test_key); RUN_TEST(test_range); RUN_TEST(test_array_diff); RUN_TEST(test_array_udiff); RUN_TEST(test_array_diff_assoc); RUN_TEST(test_array_diff_uassoc); RUN_TEST(test_array_udiff_assoc); RUN_TEST(test_array_udiff_uassoc); RUN_TEST(test_array_diff_key); RUN_TEST(test_array_diff_ukey); RUN_TEST(test_array_intersect); RUN_TEST(test_array_uintersect); RUN_TEST(test_array_intersect_assoc); RUN_TEST(test_array_intersect_uassoc); RUN_TEST(test_array_uintersect_assoc); RUN_TEST(test_array_uintersect_uassoc); RUN_TEST(test_array_intersect_key); RUN_TEST(test_array_intersect_ukey); RUN_TEST(test_sort); RUN_TEST(test_rsort); RUN_TEST(test_asort); RUN_TEST(test_arsort); RUN_TEST(test_ksort); RUN_TEST(test_krsort); RUN_TEST(test_usort); RUN_TEST(test_uasort); RUN_TEST(test_uksort); RUN_TEST(test_natsort); RUN_TEST(test_natcasesort); RUN_TEST(test_i18n_loc_get_default); return ret; } /////////////////////////////////////////////////////////////////////////////// bool TestExtArray::test_array_change_key_case() { Array input_array = CREATE_MAP2(""FirSt"", 1, ""SecOnd"", 4); VS(f_print_r(f_array_change_key_case(input_array, k_CASE_UPPER), true), ""Array\\n"" ""(\\n"" "" [FIRST] => 1\\n"" "" [SECOND] => 4\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_chunk() { Array input_array = CREATE_VECTOR5(""a"", ""b"", ""c"", ""d"", ""e""); VS(f_print_r(f_array_chunk(input_array, 2), true), ""Array\\n"" ""(\\n"" "" [0] => Array\\n"" "" (\\n"" "" [0] => a\\n"" "" [1] => b\\n"" "" )\\n"" ""\\n"" "" [1] => Array\\n"" "" (\\n"" "" [0] => c\\n"" "" [1] => d\\n"" "" )\\n"" ""\\n"" "" [2] => Array\\n"" "" (\\n"" "" [0] => e\\n"" "" )\\n"" ""\\n"" "")\\n""); VS(f_print_r(f_array_chunk(input_array, 2, true), true), ""Array\\n"" ""(\\n"" "" [0] => Array\\n"" "" (\\n"" "" [0] => a\\n"" "" [1] => b\\n"" "" )\\n"" ""\\n"" "" [1] => Array\\n"" "" (\\n"" "" [2] => c\\n"" "" [3] => d\\n"" "" )\\n"" ""\\n"" "" [2] => Array\\n"" "" (\\n"" "" [4] => e\\n"" "" )\\n"" ""\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_combine() { Array a = CREATE_VECTOR3(""green"", ""red"", ""yellow""); Array b = CREATE_VECTOR3(""avocado"", ""apple"", ""banana""); Array c = f_array_combine(a, b); VS(f_print_r(c, true), ""Array\\n"" ""(\\n"" "" [green] => avocado\\n"" "" [red] => apple\\n"" "" [yellow] => banana\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_count_values() { Array array = CREATE_VECTOR5(1, ""hello"", 1, ""world"", ""hello""); VS(f_print_r(f_array_count_values(array), true), ""Array\\n"" ""(\\n"" "" [1] => 2\\n"" "" [hello] => 2\\n"" "" [world] => 1\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_fill_keys() { Array keys = CREATE_VECTOR4(""foo"", 5, 10, ""bar""); Array a = f_array_fill_keys(keys, ""banana""); VS(f_print_r(a, true), ""Array\\n"" ""(\\n"" "" [foo] => banana\\n"" "" [5] => banana\\n"" "" [10] => banana\\n"" "" [bar] => banana\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_fill() { Array a = f_array_fill(5, 6, ""banana""); Array b = f_array_fill(-2, 2, ""pear""); VS(f_print_r(a, true), ""Array\\n"" ""(\\n"" "" [5] => banana\\n"" "" [6] => banana\\n"" "" [7] => banana\\n"" "" [8] => banana\\n"" "" [9] => banana\\n"" "" [10] => banana\\n"" "")\\n""); VS(f_print_r(b, true), ""Array\\n"" ""(\\n"" "" [-2] => pear\\n"" "" [0] => pear\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_filter() { Array array1 = CREATE_MAP5(""a"", 1, ""b"", 2, ""c"", 3, ""d"", 4, ""e"", 5); Array array2(ArrayInit(7).set(6).set(7).set(8).set(9). set(10).set(11).set(12).create()); VS(f_print_r(f_array_filter(array1, ""odd""), true), ""Array\\n"" ""(\\n"" "" [a] => 1\\n"" "" [c] => 3\\n"" "" [e] => 5\\n"" "")\\n""); VS(f_print_r(f_array_filter(array2, ""even""), true), ""Array\\n"" ""(\\n"" "" [0] => 6\\n"" "" [2] => 8\\n"" "" [4] => 10\\n"" "" [6] => 12\\n"" "")\\n""); Array entry = CREATE_MAP5(0, ""foo"", 1, false, 2, -1, 3, null, 4, """"); VS(f_print_r(f_array_filter(entry), true), ""Array\\n"" ""(\\n"" "" [0] => foo\\n"" "" [2] => -1\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_flip() { Array trans = CREATE_MAP3(""a"", 1, ""b"", 1, ""c"", 2); trans = f_array_flip(trans); VS(f_print_r(trans, true), ""Array\\n"" ""(\\n"" "" [1] => b\\n"" "" [2] => c\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_key_exists() { Array search_array = CREATE_MAP2(""first"", 1, ""second"", 4); VERIFY(f_array_key_exists(""first"", search_array)); search_array = CREATE_MAP2(""first"", null, ""second"", 4); //VERIFY(!isset(search_array.lvalAt(""first""))); VERIFY(f_array_key_exists(""first"", search_array)); return Count(true); } bool TestExtArray::test_array_keys() { { Array array = CREATE_MAP2(0, 100, ""color"", ""red""); VS(f_print_r(f_array_keys(array), true), ""Array\\n"" ""(\\n"" "" [0] => 0\\n"" "" [1] => color\\n"" "")\\n""); } { Array array = CREATE_VECTOR5(""blue"", ""red"", ""green"", ""blue"", ""blue""); VS(f_print_r(f_array_keys(array, ""blue""), true), ""Array\\n"" ""(\\n"" "" [0] => 0\\n"" "" [1] => 3\\n"" "" [2] => 4\\n"" "")\\n""); } { Array array = CREATE_MAP2(""color"", CREATE_VECTOR3(""blue"", ""red"", ""green""), ""size"", CREATE_VECTOR3(""small"", ""medium"", ""large"")); VS(f_print_r(f_array_keys(array), true), ""Array\\n"" ""(\\n"" "" [0] => color\\n"" "" [1] => size\\n"" "")\\n""); } return Count(true); } bool TestExtArray::test_array_map() { Array a = CREATE_VECTOR5(1, 2, 3, 4, 5); Array b = f_array_map(2, ""cube"", a); VS(f_print_r(b, true), ""Array\\n"" ""(\\n"" "" [0] => 1\\n"" "" [1] => 8\\n"" "" [2] => 27\\n"" "" [3] => 64\\n"" "" [4] => 125\\n"" "")\\n""); b = f_array_map(2, null, a); VS(f_print_r(b, true), ""Array\\n"" ""(\\n"" "" [0] => 1\\n"" "" [1] => 2\\n"" "" [2] => 3\\n"" "" [3] => 4\\n"" "" [4] => 5\\n"" "")\\n""); b = f_array_map(2, null, CREATE_MAP2(""x"", 6, 0, 7)); VS(f_print_r(b, true), ""Array\\n"" ""(\\n"" "" [x] => 6\\n"" "" [0] => 7\\n"" "")\\n""); VS(f_print_r(f_array_map(3, null, CREATE_MAP2(""x"", 6, 0, 7), CREATE_VECTOR1(CREATE_VECTOR2(""a"",""b""))), true), ""Array\\n"" ""(\\n"" "" [0] => Array\\n"" "" (\\n"" "" [0] => 6\\n"" "" [1] => a\\n"" "" )\\n"" ""\\n"" "" [1] => Array\\n"" "" (\\n"" "" [0] => 7\\n"" "" [1] => b\\n"" "" )\\n"" ""\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_merge_recursive() { { Variant a1 = Array::Create(); Variant a2 = CREATE_MAP1(""key1"", ref(a1)); a1 = f_array_merge_recursive(a1, a2); } { Array ar1(ArrayInit(2). set(""color"", CREATE_MAP1(""favorite"", ""red"")). set(1, 5). create()); Array ar2(ArrayInit(2).set(10). set(""color"", Array(ArrayInit(2). set(""favorite"", ""green""). set(""blue"").create())). create()); Array result = f_array_merge_recursive(2, ar1, CREATE_VECTOR1(ar2)); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [color] => Array\\n"" "" (\\n"" "" [favorite] => Array\\n"" "" (\\n"" "" [0] => red\\n"" "" [1] => green\\n"" "" )\\n"" ""\\n"" "" [0] => blue\\n"" "" )\\n"" ""\\n"" "" [0] => 5\\n"" "" [1] => 10\\n"" "")\\n""); } return Count(true); } bool TestExtArray::test_array_merge() { { Array array1(ArrayInit(3).set(""color"", ""red""). set(2).set(4).create()); Array array2(ArrayInit(5).set(""a"").set(""b""). set(""color"", ""green""). set(""shape"", ""trapezoid""). set(4).create()); Array result = f_array_merge(2, array1, CREATE_VECTOR1(array2)); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [color] => green\\n"" "" [0] => 2\\n"" "" [1] => 4\\n"" "" [2] => a\\n"" "" [3] => b\\n"" "" [shape] => trapezoid\\n"" "" [4] => 4\\n"" "")\\n""); } { Array array1 = Array::Create(); Array array2 = CREATE_MAP1(1, ""data""); Array result = f_array_merge(2, array1, CREATE_VECTOR1(array2)); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0] => data\\n"" "")\\n""); } { Array array1 = Array::Create(); Array array2 = CREATE_MAP1(1, ""data""); Array result = array1 + array2; VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [1] => data\\n"" "")\\n""); } { String beginning = ""foo""; Array end = CREATE_MAP1(1, ""bar""); Array result = f_array_merge(2, toArray(beginning), CREATE_VECTOR1(end)); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0] => foo\\n"" "" [1] => bar\\n"" "")\\n""); } { Variant v = 1; Array a = CREATE_MAP1(""one"", 1); Array b = CREATE_MAP1(""two"", ref(v)); Array r = f_array_merge(2, a, CREATE_VECTOR1(b)); v = 2; VS(f_print_r(r, true), ""Array\\n"" ""(\\n"" "" [one] => 1\\n"" "" [two] => 2\\n"" "")\\n""); } { int64 id = 100000000000022LL; Array a = CREATE_MAP1(id, 1); Array b = CREATE_MAP1(id, 2); Array r = f_array_merge(2, a, CREATE_VECTOR1(b)); VS(f_print_r(r, true), ""Array\\n"" ""(\\n"" "" [0] => 1\\n"" "" [1] => 2\\n"" "")\\n""); } { Variant a = CREATE_MAP2(1, 50, 5, 60); Variant b = null; VS(f_array_merge(2, a, CREATE_VECTOR1(b)), null); } return Count(true); } bool TestExtArray::test_array_replace_recursive() { Array ar1(ArrayInit(2). set(""color"", CREATE_MAP1(""favorite"", ""red"")). set(5).create()); Array ar2(ArrayInit(2). set(10). set(""color"", Array(ArrayInit(2). set(""favorite"", ""green""). set(""blue"").create())). create()); Array result = f_array_replace_recursive(2, ar1, CREATE_VECTOR1(ar2)); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [color] => Array\\n"" "" (\\n"" "" [favorite] => green\\n"" "" [0] => blue\\n"" "" )\\n"" ""\\n"" "" [0] => 10\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_replace() { { Array array1(ArrayInit(3).set(""color"", ""red""). set(2).set(4).create()); Array array2(ArrayInit(5).set(""a"").set(""b""). set(""color"", ""green""). set(""shape"", ""trapezoid""). set(4).create()); Array result = f_array_replace(2, array1, CREATE_VECTOR1(array2)); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [color] => green\\n"" "" [0] => a\\n"" "" [1] => b\\n"" "" [shape] => trapezoid\\n"" "" [2] => 4\\n"" "")\\n""); } { Array array1 = Array::Create(); Array array2 = CREATE_MAP1(1, ""data""); Array result = f_array_replace(2, array1, CREATE_VECTOR1(array2)); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [1] => data\\n"" "")\\n""); } { String beginning = ""foo""; Array end = CREATE_MAP1(1, ""bar""); Array result = f_array_replace(2, toArray(beginning), CREATE_VECTOR1(end)); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0] => foo\\n"" "" [1] => bar\\n"" "")\\n""); } { Variant v = 1; Array a = CREATE_MAP1(""one"", 1); Array b = CREATE_MAP1(""two"", ref(v)); Array r = f_array_replace(2, a, CREATE_VECTOR1(b)); v = 2; VS(f_print_r(r, true), ""Array\\n"" ""(\\n"" "" [one] => 1\\n"" "" [two] => 2\\n"" "")\\n""); } { int64 id = 100000000000022LL; Array a = CREATE_MAP1(id, 1); Array b = CREATE_MAP1(id, 2); Array r = f_array_replace(2, a, CREATE_VECTOR1(b)); VS(f_print_r(r, true), ""Array\\n"" ""(\\n"" "" [100000000000022] => 2\\n"" "")\\n""); } { Variant a = CREATE_MAP2(1, 50, 5, 60); Variant b = null; VS(f_array_replace(2, a, CREATE_VECTOR1(b)), null); } return Count(true); } bool TestExtArray::test_array_multisort() { { Variant ar1 = CREATE_VECTOR4(10, 100, 100, 0); Variant ar2 = CREATE_VECTOR4(1, 3, 2, 4); f_array_multisort(2, ref(ar1), CREATE_VECTOR1(ref(ar2))); VS(f_print_r(ar1, true), ""Array\\n"" ""(\\n"" "" [0] => 0\\n"" "" [1] => 10\\n"" "" [2] => 100\\n"" "" [3] => 100\\n"" "")\\n""); VS(f_print_r(ar2, true), ""Array\\n"" ""(\\n"" "" [0] => 4\\n"" "" [1] => 1\\n"" "" [2] => 2\\n"" "" [3] => 3\\n"" "")\\n""); } { Variant ar = CREATE_VECTOR2 (CREATE_VECTOR5(""10"", 11, 100, 100, ""a""), CREATE_VECTOR5( 1, 2, ""2"", 3, 1)); f_array_multisort(6, ref(lval(ar.lvalAt(0))), CREATE_VECTOR5(k_SORT_ASC, k_SORT_STRING, ref(lval(ar.lvalAt(1))), k_SORT_NUMERIC, k_SORT_DESC)); VS(f_print_r(ar, true), ""Array\\n"" ""(\\n"" "" [0] => Array\\n"" "" (\\n"" "" [0] => 10\\n"" "" [1] => 100\\n"" "" [2] => 100\\n"" "" [3] => 11\\n"" "" [4] => a\\n"" "" )\\n"" ""\\n"" "" [1] => Array\\n"" "" (\\n"" "" [0] => 1\\n"" "" [1] => 3\\n"" "" [2] => 2\\n"" "" [3] => 2\\n"" "" [4] => 1\\n"" "" )\\n"" ""\\n"" "")\\n""); } { Variant array = CREATE_VECTOR4(""Alpha"", ""atomic"", ""Beta"", ""bank""); Variant array_lowercase = f_array_map(2, ""strtolower"", array); f_array_multisort(4, ref(array_lowercase), CREATE_VECTOR3(k_SORT_ASC, k_SORT_STRING, ref(array))); VS(f_print_r(array, true), ""Array\\n"" ""(\\n"" "" [0] => Alpha\\n"" "" [1] => atomic\\n"" "" [2] => bank\\n"" "" [3] => Beta\\n"" "")\\n""); } return Count(true); } bool TestExtArray::test_array_pad() { Array input = CREATE_VECTOR3(12, 10, 9); VS(f_array_pad(input, 5, 0), CREATE_VECTOR5(12, 10, 9, 0, 0)); VS(f_array_pad(input, -7, -1), Array(ArrayInit(7).set(-1).set(-1).set(-1).set(-1). set(12).set(10).set(9).create())); VS(f_array_pad(input, 2, ""noop""), input); Array a = CREATE_MAP1(""9"", ""b""); VS(f_array_pad(a, -3, ""test""), CREATE_VECTOR3(""test"", ""test"", ""b"")); return Count(true); } bool TestExtArray::test_array_pop() { { Variant input = CREATE_VECTOR4(""orange"", ""banana"", ""apple"", ""raspberry""); String fruit = f_array_pop(ref(input)); VS(f_print_r(input, true), ""Array\\n"" ""(\\n"" "" [0] => orange\\n"" "" [1] => banana\\n"" "" [2] => apple\\n"" "")\\n""); VS(fruit, ""raspberry""); } { Variant input = CREATE_VECTOR1(""orange""); String fruit = f_array_pop(ref(input)); f_array_push(2, ref(input), ""banana""); VS(f_print_r(input, true), ""Array\\n"" ""(\\n"" "" [0] => banana\\n"" "")\\n""); VS(fruit, ""orange""); } return Count(true); } bool TestExtArray::test_array_product() { Array a = CREATE_VECTOR4(2, 4, 6, 8); VS(f_array_product(a), 384); VS(f_array_product(Array::Create()), 0); return Count(true); } bool TestExtArray::test_array_push() { Variant input = CREATE_VECTOR2(""orange"", ""banana""); Variant size = f_array_push(3, ref(input), ""apple"", CREATE_VECTOR1(""raspberry"")); VS(f_print_r(input, true), ""Array\\n"" ""(\\n"" "" [0] => orange\\n"" "" [1] => banana\\n"" "" [2] => apple\\n"" "" [3] => raspberry\\n"" "")\\n""); VS(size.toInt64(), 4); return Count(true); } bool TestExtArray::test_array_rand() { Array input = CREATE_VECTOR5(""Neo"", ""Morpheus"", ""Trinity"", ""Cypher"", ""Tank""); Array rand_keys = f_array_rand(input, 2); VS(rand_keys.size(), 2); std::set strs; strs.insert(""Neo""); strs.insert(""Morpheus""); strs.insert(""Trinity""); strs.insert(""Cypher""); strs.insert(""Tank""); VERIFY(strs.find(input[rand_keys[0]].toString().data()) != strs.end()); VERIFY(strs.find(input[rand_keys[1]].toString().data()) != strs.end()); return Count(true); } bool TestExtArray::test_array_reduce() { Array a = CREATE_VECTOR5(1, 2, 3, 4, 5); Variant b = f_array_reduce(a, ""rsum""); VS(b, 15); Variant c = f_array_reduce(a, ""rmul"", 10); VS(c, 1200); Variant d = f_array_reduce(a, ""rmul""); VS(d, 0); Array x = Array::Create(); Variant e = f_array_reduce(x, ""rsum"", 1); VS(e, 1); return Count(true); } bool TestExtArray::test_array_reverse() { { Array input = CREATE_VECTOR3(""php"", 4.0, CREATE_VECTOR2(""green"", ""red"")); Array result = f_array_reverse(input); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0] => Array\\n"" "" (\\n"" "" [0] => green\\n"" "" [1] => red\\n"" "" )\\n"" ""\\n"" "" [1] => 4\\n"" "" [2] => php\\n"" "")\\n""); Array result_keyed = f_array_reverse(input, true); VS(f_print_r(result_keyed, true), ""Array\\n"" ""(\\n"" "" [2] => Array\\n"" "" (\\n"" "" [0] => green\\n"" "" [1] => red\\n"" "" )\\n"" ""\\n"" "" [1] => 4\\n"" "" [0] => php\\n"" "")\\n""); } { Array input = CREATE_MAP3(""php"", 4.0, 10, 5.0, ""blab"", ""b""); Array result = f_array_reverse(input); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [blab] => b\\n"" "" [0] => 5\\n"" "" [php] => 4\\n"" "")\\n""); } return Count(true); } bool TestExtArray::test_array_search() { Array array = CREATE_MAP4(0, ""blue"", 1, ""red"", 2, ""green"", 3, ""red""); VS(f_array_search(""green"", array), 2); VS(f_array_search(""red"", array), 1); return Count(true); } bool TestExtArray::test_array_shift() { { Variant input = CREATE_MAP2(""a"", 1, ""b"", 2); f_array_shift(ref(input)); VS(f_print_r(input, true), ""Array\\n"" ""(\\n"" "" [b] => 2\\n"" "")\\n""); } { Variant input = CREATE_MAP2(""a"", 1, 23, 2); f_array_shift(ref(input)); VS(f_print_r(input, true), ""Array\\n"" ""(\\n"" "" [0] => 2\\n"" "")\\n""); } { Variant input = CREATE_MAP2(""a"", 1, -23, 2); f_array_shift(ref(input)); VS(f_print_r(input, true), ""Array\\n"" ""(\\n"" "" [0] => 2\\n"" "")\\n""); } { Variant input = CREATE_VECTOR4(""orange"", ""banana"", ""apple"", ""raspberry""); String fruit = f_array_shift(ref(input)); VS(f_print_r(input, true), ""Array\\n"" ""(\\n"" "" [0] => banana\\n"" "" [1] => apple\\n"" "" [2] => raspberry\\n"" "")\\n""); VS(fruit, ""orange""); } return Count(true); } bool TestExtArray::test_array_slice() { Array input = CREATE_VECTOR5(""a"", ""b"", ""c"", ""d"", ""e""); VS(f_array_slice(input, 2), CREATE_VECTOR3(""c"", ""d"", ""e"")); VS(f_array_slice(input, 2, Variant()), CREATE_VECTOR3(""c"", ""d"", ""e"")); VS(f_array_slice(input, -2, 1), CREATE_VECTOR1(""d"")); VS(f_array_slice(input, 0, 3), CREATE_VECTOR3(""a"", ""b"", ""c"")); // note the differences in the array keys VS(f_print_r(f_array_slice(input, 2, -1), true), ""Array\\n"" ""(\\n"" "" [0] => c\\n"" "" [1] => d\\n"" "")\\n""); VS(f_print_r(f_array_slice(input, 2, -1, true), true), ""Array\\n"" ""(\\n"" "" [2] => c\\n"" "" [3] => d\\n"" "")\\n""); VS(f_array_slice(CREATE_VECTOR3(""a"", ""b"", ""c""), 1, 2, true), CREATE_MAP2(1, ""b"", 2, ""c"")); VS(f_array_slice(CREATE_VECTOR3(""a"", ""b"", ""c""), 1, 2, false), CREATE_VECTOR2(""b"", ""c"")); Array a = CREATE_MAP4(""a"", ""g"", 0, ""a"", 1, ""b"", 2, ""c""); a.remove(""a""); VS(f_array_slice(a, 1, 2, true), CREATE_MAP2(1, ""b"", 2, ""c"")); VS(f_array_slice(a, 1, 2, false), CREATE_VECTOR2(""b"", ""c"")); a = CREATE_MAP4(""a"", 123, 0, ""a"", 1, ""b"", 2, ""c""); a.remove(""a""); VS(f_array_slice(a, 1, 2, true), CREATE_MAP2(1, ""b"", 2, ""c"")); VS(f_array_slice(a, 1, 2, false), CREATE_VECTOR2(""b"", ""c"")); VS(f_array_slice(CREATE_VECTOR3(123, ""b"", ""c""), 1, 2, true), CREATE_MAP2(1, ""b"", 2, ""c"")); VS(f_array_slice(CREATE_VECTOR3(123, ""b"", ""c""), 1, 2, false), CREATE_VECTOR2(""b"", ""c"")); return Count(true); } bool TestExtArray::test_array_splice() { Variant params = CREATE_MAP2(""a"", ""aaa"", ""0"", ""apple""); params.remove(""a""); f_array_splice(ref(params), 0, 0, CREATE_MAP1(123, ""test"")); VS(params, CREATE_VECTOR2(""test"", ""apple"")); params = CREATE_MAP2(""a"", ""aaa"", ""1"", ""apple""); params.remove(""a""); f_array_splice(ref(params), 0, 0, CREATE_MAP1(123, ""test"")); VS(params, CREATE_VECTOR2(""test"", ""apple"")); Variant input = CREATE_VECTOR4(""red"", ""green"", ""blue"", ""yellow""); f_array_splice(ref(input), 2); VS(input, CREATE_VECTOR2(""red"", ""green"")); input = CREATE_VECTOR4(""red"", ""green"", ""blue"", ""yellow""); f_array_splice(ref(input), 2, Variant()); VS(input, CREATE_VECTOR2(""red"", ""green"")); input = CREATE_VECTOR4(""red"", ""green"", ""blue"", ""yellow""); f_array_splice(ref(input), 1, -1); VS(input, CREATE_VECTOR2(""red"", ""yellow"")); input = CREATE_VECTOR4(""red"", ""green"", ""blue"", ""yellow""); f_array_splice(ref(input), 1, 4, ""orange""); VS(input, CREATE_VECTOR2(""red"", ""orange"")); input = CREATE_VECTOR4(""red"", ""green"", ""blue"", ""yellow""); f_array_splice(ref(input), -1, 1, CREATE_VECTOR2(""black"", ""maroon"")); VS(input, CREATE_VECTOR5(""red"", ""green"", ""blue"", ""black"", ""maroon"")); input = CREATE_VECTOR4(""red"", ""green"", ""blue"", ""yellow""); f_array_splice(ref(input), 3, 0, ""purple""); VS(input, CREATE_VECTOR5(""red"", ""green"", ""blue"", ""purple"", ""yellow"")); return Count(true); } bool TestExtArray::test_array_sum() { Array a = CREATE_VECTOR4(2, 4, 6, 8); VS(f_array_sum(a), 20); Array b = CREATE_MAP3(""a"", 1.2, ""b"", 2.3, ""c"", 3.4); VS(f_array_sum(b), 6.9); return Count(true); } bool TestExtArray::test_array_unique() { { Array input(ArrayInit(5). set(""a"", ""green"").set(""red"").set(""b"", ""green""). set(""blue"").set(""red"").create()); Array result = f_array_unique(input); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [a] => green\\n"" "" [0] => red\\n"" "" [1] => blue\\n"" "")\\n""); } { Array input(ArrayInit(6).set(4).set(""4"").set(""3""). set(4).set(3).set(""3"").create()); Array result = f_array_unique(input); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0] => 4\\n"" "" [2] => 3\\n"" "")\\n""); } { Array input(CREATE_MAP6(""a"", ""A"", ""b"", ""C"", 0, ""1"", 2 ,""01"", 1, 1, ""c"", ""C"")); VS(f_print_r(f_array_unique(input, k_SORT_STRING), true), ""Array\\n"" ""(\\n"" "" [a] => A\\n"" "" [b] => C\\n"" "" [0] => 1\\n"" "" [2] => 01\\n"" "")\\n""); VS(f_print_r(f_array_unique(input, k_SORT_NUMERIC), true), ""Array\\n"" ""(\\n"" "" [a] => A\\n"" "" [0] => 1\\n"" "")\\n""); VS(f_print_r(f_array_unique(input, k_SORT_REGULAR), true), ""Array\\n"" ""(\\n"" "" [a] => A\\n"" "" [b] => C\\n"" "" [0] => 1\\n"" "")\\n""); } { Array input(CREATE_MAP6(1, 1, ""a"", ""A"", ""b"", ""C"", 0, ""1"", 2 ,""01"", ""c"", ""C"")); VS(f_print_r(f_array_unique(input, k_SORT_REGULAR), true), ""Array\\n"" ""(\\n"" "" [1] => 1\\n"" "" [a] => A\\n"" "" [b] => C\\n"" "" [0] => 1\\n"" "")\\n""); } return Count(true); } bool TestExtArray::test_array_unshift() { Variant q = CREATE_VECTOR2(""orange"", ""banana""); f_array_unshift(3, ref(q), ""apple"", CREATE_VECTOR1(""raspberry"")); VS(f_print_r(q, true), ""Array\\n"" ""(\\n"" "" [0] => apple\\n"" "" [1] => raspberry\\n"" "" [2] => orange\\n"" "" [3] => banana\\n"" "")\\n""); q = CREATE_MAP3(0, ""orange"", 1, ""banana"", ""a"", ""dummy""); q.remove(""a""); f_array_unshift(3, ref(q), ""apple"", CREATE_VECTOR1(""raspberry"")); VS(f_print_r(q, true), ""Array\\n"" ""(\\n"" "" [0] => apple\\n"" "" [1] => raspberry\\n"" "" [2] => orange\\n"" "" [3] => banana\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_values() { Array array = CREATE_MAP2(""size"", ""XL"", ""color"", ""gold""); VS(f_print_r(f_array_values(array), true), ""Array\\n"" ""(\\n"" "" [0] => XL\\n"" "" [1] => gold\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_walk_recursive() { Array sweet = CREATE_MAP2(""a"", ""apple"", ""b"", ""banana""); Array fruits = CREATE_MAP2(""sweet"", sweet, ""sour"", ""lemon""); g_context->obStart(); f_array_walk_recursive(fruits, ""test_print""); String output = g_context->obCopyContents(); g_context->obEnd(); VS(output, ""a: apple\\nb: banana\\nsour: lemon\\n""); return Count(true); } bool TestExtArray::test_array_walk() { Variant fruits = CREATE_MAP4(""d"", ""lemon"", ""a"", ""orange"", ""b"", ""banana"", ""c"", ""apple""); g_context->obStart(); f_array_walk(ref(fruits), ""test_print""); f_array_walk(ref(fruits), ""test_alter"", ""fruit""); f_array_walk(ref(fruits), ""test_print""); String output = g_context->obCopyContents(); g_context->obEnd(); VS(output, ""d: lemon\\n"" ""a: orange\\n"" ""b: banana\\n"" ""c: apple\\n"" ""d: fruit: lemon\\n"" ""a: fruit: orange\\n"" ""b: fruit: banana\\n"" ""c: fruit: apple\\n""); return Count(true); } bool TestExtArray::test_compact() { // compact() was tested in TestCodeRun. return Count(true); } bool TestExtArray::test_shuffle() { Variant numbers = f_range(1, 4); f_srand(5); f_shuffle(ref(numbers)); Array numArr = numbers.toArray(); VS(numArr[0], 3); VS(numArr[1], 4); VS(numArr[2], 1); VS(numArr[3], 2); return Count(true); } bool TestExtArray::test_count() { Array a; a.set(0, 1); a.set(1, 3); a.set(2, 5); VS(f_count(a), 3); Array b; b.set(0, 7); b.set(5, 9); b.set(10, 11); VS(f_count(b), 3); VS(f_count(null), 0); VS(f_count(false), 1); Array food = CREATE_MAP2(""fruits"", CREATE_VECTOR3(""orange"", ""banana"", ""apple""), ""veggie"", CREATE_VECTOR3(""carrot"", ""collard"", ""pea"")); VS(f_count(food, k_COUNT_RECURSIVE), 8); VS(f_count(food), 2); return Count(true); } bool TestExtArray::test_sizeof() { Array a; a.set(0, 1); a.set(1, 3); a.set(2, 5); VS(f_sizeof(a), 3); Array b; b.set(0, 7); b.set(5, 9); b.set(10, 11); VS(f_sizeof(b), 3); VS(f_sizeof(null), 0); VS(f_sizeof(false), 1); Array food = CREATE_MAP2(""fruits"", CREATE_VECTOR3(""orange"", ""banana"", ""apple""), ""veggie"", CREATE_VECTOR3(""carrot"", ""collard"", ""pea"")); VS(f_sizeof(food, k_COUNT_RECURSIVE), 8); VS(f_sizeof(food), 2); return Count(true); } bool TestExtArray::test_each() { { Variant foo = CREATE_VECTOR6(""bob"", ""fred"", ""jussi"", ""jouni"", ""egon"", ""marliese""); Array bar = f_each(ref(foo)); VS(f_print_r(bar, true), ""Array\\n"" ""(\\n"" "" [1] => bob\\n"" "" [value] => bob\\n"" "" [0] => 0\\n"" "" [key] => 0\\n"" "")\\n""); } { Variant foo = CREATE_MAP2(""Robert"", ""Bob"", ""Seppo"", ""Sepi""); Array bar = f_each(ref(foo)); VS(f_print_r(bar, true), ""Array\\n"" ""(\\n"" "" [1] => Bob\\n"" "" [value] => Bob\\n"" "" [0] => Robert\\n"" "" [key] => Robert\\n"" "")\\n""); } { Variant fruit = CREATE_MAP3(""a"", ""apple"", ""b"", ""banana"", ""c"", ""cranberry""); f_reset(ref(fruit)); String output; while (true) { Variant item = f_each(ref(fruit)); if (same(item, false)) break; output += item[0]; output += "": ""; output += item[1]; output += ""\\n""; } VS(output, ""a: apple\\n"" ""b: banana\\n"" ""c: cranberry\\n""); } return Count(true); } bool TestExtArray::test_current() { { Variant transport = CREATE_VECTOR4(""foot"", ""bike"", ""car"", ""plane""); VS(f_current(ref(transport)), ""foot""); VS(f_next(ref(transport)), ""bike""); VS(f_current(ref(transport)), ""bike""); VS(f_prev(ref(transport)), ""foot""); VS(f_end(ref(transport)), ""plane""); VS(f_current(ref(transport)), ""plane""); } { Variant arr = Array::Create(); VS(f_current(ref(arr)), false); } { Variant arr = CREATE_VECTOR1(Array::Create()); VS(f_current(ref(arr)), Array::Create()); } return Count(true); } bool TestExtArray::test_next() { Variant transport = CREATE_VECTOR4(""foot"", ""bike"", ""car"", ""plane""); VS(f_current(ref(transport)), ""foot""); VS(f_next(ref(transport)), ""bike""); VS(f_next(ref(transport)), ""car""); VS(f_prev(ref(transport)), ""bike""); VS(f_end(ref(transport)), ""plane""); return Count(true); } bool TestExtArray::test_pos() { { Variant transport = CREATE_VECTOR4(""foot"", ""bike"", ""car"", ""plane""); VS(f_pos(ref(transport)), ""foot""); VS(f_next(ref(transport)), ""bike""); VS(f_pos(ref(transport)), ""bike""); VS(f_prev(ref(transport)), ""foot""); VS(f_end(ref(transport)), ""plane""); VS(f_pos(ref(transport)), ""plane""); } { Variant arr = Array::Create(); VS(f_pos(ref(arr)), false); } { Variant arr = CREATE_VECTOR1(Array::Create()); VS(f_pos(ref(arr)), Array::Create()); } return Count(true); } bool TestExtArray::test_prev() { Variant transport = CREATE_VECTOR4(""foot"", ""bike"", ""car"", ""plane""); VS(f_current(ref(transport)), ""foot""); VS(f_next(ref(transport)), ""bike""); VS(f_next(ref(transport)), ""car""); VS(f_prev(ref(transport)), ""bike""); VS(f_end(ref(transport)), ""plane""); return Count(true); } bool TestExtArray::test_reset() { Variant array = CREATE_VECTOR4(""step one"", ""step two"", ""step three"", ""step four""); // by default, the pointer is on the first element VS(f_current(ref(array)), ""step one""); // skip two steps f_next(ref(array)); f_next(ref(array)); VS(f_current(ref(array)), ""step three""); // reset pointer, start again on step one f_reset(ref(array)); VS(f_current(ref(array)), ""step one""); return Count(true); } bool TestExtArray::test_end() { Variant fruits = CREATE_VECTOR3(""apple"", ""banana"", ""cranberry""); VS(f_end(ref(fruits)), ""cranberry""); return Count(true); } bool TestExtArray::test_in_array() { { Array os = CREATE_VECTOR4(""Mac"", ""NT"", ""Irix"", ""Linux""); VERIFY(f_in_array(""Irix"", os)); VERIFY(!f_in_array(""mac"", os)); } { Array a = CREATE_VECTOR3(""1.10"", 12.4, 1.13); VERIFY(!f_in_array(""12.4"", a, true)); VERIFY(f_in_array(1.13, a, true)); } { Array a = CREATE_VECTOR3(CREATE_VECTOR2(""p"", ""h""), CREATE_VECTOR2(""p"", ""r""), ""o""); VERIFY(f_in_array(CREATE_VECTOR2(""p"", ""h""), a)); VERIFY(!f_in_array(CREATE_VECTOR2(""f"", ""i""), a)); VERIFY(f_in_array(""o"", a)); } return Count(true); } bool TestExtArray::test_key() { Variant array = CREATE_MAP5(""fruit1"", ""apple"", ""fruit2"", ""orange"", ""fruit3"", ""grape"", ""fruit4"", ""apple"", ""fruit5"", ""apple""); // this cycle echoes all associative array // key where value equals ""apple"" String output; while (true) { Variant fruit_name = f_current(ref(array)); if (same(fruit_name, false)) break; if (same(fruit_name, ""apple"")) { output += f_key(ref(array)); } f_next(ref(array)); } VS(output, ""fruit1fruit4fruit5""); return Count(true); } bool TestExtArray::test_range() { Array ret = f_range(0, 12); VS(ret.size(), 13); VS(ret[0], 0); VS(ret[12], 12); // The step parameter was introduced in 5.0.0 ret = f_range(0, 100, 10); VS(ret.size(), 11); VS(ret[0], 0); VS(ret[5], 50); VS(ret[10], 100); // Use of character sequences introduced in 4.1.0 // array(""a"", ""b"", ""c"", ""d"", ""e"", ""f"", ""g"", ""h"", ""i""); ret = f_range(""a"", ""i""); VS(ret.size(), 9); VS(ret[0], ""a""); VS(ret[4], ""e""); VS(ret[8], ""i""); VS(f_range(""c"", ""a""), CREATE_VECTOR3(""c"", ""b"", ""a"")); return Count(true); } bool TestExtArray::test_array_diff() { Array array1(ArrayInit(4).set(""a"", ""green"").set(""red""). set(""blue"").set(""red"").create()); Array array2(ArrayInit(3).set(""b"", ""green"").set(""yellow""). set(""red"").create()); Array result = f_array_diff(2, array1, array2); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [1] => blue\\n"" "")\\n""); Array a = CREATE_VECTOR1(""b""); Array b = CREATE_VECTOR2(""b"", ""c""); VS(f_array_diff(2, b, a), CREATE_MAP1(1, ""c"")); return Count(true); } bool TestExtArray::test_array_udiff() { Array a = CREATE_MAP5(""0.1"", 9, ""0.5"", 12, 0, 23, 1, 4, 2, -15); Array b = CREATE_MAP5(""0.2"", 9, ""0.5"", 22, 0, 3, 1, 4, 2, -15); Array result = f_array_udiff(3, a, b, ""comp_func""); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0.5] => 12\\n"" "" [0] => 23\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_diff_assoc() { { Array array1(ArrayInit(4).set(""a"", ""green""). set(""b"", ""brown""). set(""c"", ""blue""). set(""red"").create()); Array array2(ArrayInit(3).set(""a"", ""green""). set(""yellow""). set(""red"").create()); Array result = f_array_diff_assoc(2, array1, array2); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [b] => brown\\n"" "" [c] => blue\\n"" "" [0] => red\\n"" "")\\n""); } { Array array1 = CREATE_VECTOR3(0, 1, 2); Array array2 = CREATE_VECTOR3(""00"", ""01"", ""2""); Array result = f_array_diff_assoc(2, array1, array2); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0] => 0\\n"" "" [1] => 1\\n"" "")\\n""); } return Count(true); } bool TestExtArray::test_array_diff_uassoc() { { Array array1(ArrayInit(4).set(""a"", ""green""). set(""b"", ""brown""). set(""c"", ""blue""). set(""red"").create()); Array array2(ArrayInit(3).set(""a"", ""green""). set(""yellow""). set(""red"").create()); Array result = f_array_diff_uassoc(3, array1, array2, ""comp_func""); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [b] => brown\\n"" "" [c] => blue\\n"" "" [0] => red\\n"" "")\\n""); } return Count(true); } bool TestExtArray::test_array_udiff_assoc() { Array a = CREATE_MAP5(""0.1"", 9, ""0.5"", 12, 0, 23, 1, 4, 2, -15); Array b = CREATE_MAP5(""0.2"", 9, ""0.5"", 22, 0, 3, 1, 4, 2, -15); Array result = f_array_udiff_assoc(3, a, b, ""comp_func""); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0.1] => 9\\n"" "" [0.5] => 12\\n"" "" [0] => 23\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_udiff_uassoc() { Array a = CREATE_MAP5(""0.1"", 9, ""0.5"", 12, 0, 23, 1, 4, 2, -15); Array b = CREATE_MAP5(""0.2"", 9, ""0.5"", 22, 0, 3, 1, 4, 2, -15); Array result = f_array_udiff_uassoc(4, a, b, ""comp_func"", ""comp_func""); VS(f_print_r(result, true), ""Array\\n"" ""(\\n"" "" [0.5] => 12\\n"" "" [0] => 23\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_diff_key() { Array array1 = CREATE_MAP4(""blue"", 1, ""red"", 2, ""green"", 3, ""purple"", 4); Array array2 = CREATE_MAP4(""green"", 5, ""blue"", 6, ""yellow"", 7, ""cyan"", 8); VS(f_array_diff_key(2, array1, array2), CREATE_MAP2(""red"", 2, ""purple"", 4)); return Count(true); } bool TestExtArray::test_array_diff_ukey() { Array array1 = CREATE_MAP4(""blue"", 1, ""red"", 2, ""green"", 3, ""purple"", 4); Array array2 = CREATE_MAP4(""green"", 5, ""blue"", 6, ""yellow"", 7, ""cyan"", 8); VS(f_array_diff_ukey(3, array1, array2, ""strcasecmp""), CREATE_MAP2(""red"", 2, ""purple"", 4)); return Count(true); } bool TestExtArray::test_array_intersect() { Array array1(ArrayInit(3).set(""a"", ""green""). set(""red""). set(""blue"").create()); Array array2(ArrayInit(3).set(""b"", ""green""). set(""yellow""). set(""red"").create()); VS(f_array_intersect(2, array1, array2), CREATE_MAP2(""a"", ""green"", ""0"", ""red"")); return Count(true); } bool TestExtArray::test_array_uintersect() { Array array1(ArrayInit(4).set(""a"", ""green""). set(""b"", ""brown""). set(""c"", ""blue""). set(""red"").create()); Array array2(ArrayInit(4).set(""a"", ""GREEN""). set(""B"", ""brown""). set(""yellow""). set(""red"").create()); VS(f_print_r(f_array_uintersect(3, array1, array2, ""strcasecmp""), true), ""Array\\n"" ""(\\n"" "" [a] => green\\n"" "" [b] => brown\\n"" "" [0] => red\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_array_intersect_assoc() { Array array1(ArrayInit(4).set(""a"", ""green""). set(""b"", ""brown""). set(""c"", ""blue""). set(""red"").create()); Array array2(ArrayInit(3).set(""a"", ""green""). set(""yellow""). set(""red"").create()); VS(f_array_intersect_assoc(2, array1, array2), CREATE_MAP1(""a"", ""green"")); return Count(true); } bool TestExtArray::test_array_intersect_uassoc() { Array array1(ArrayInit(4).set(""a"", ""green""). set(""b"", ""brown""). set(""c"", ""blue""). set(""red"").create()); Array array2(ArrayInit(4).set(""a"", ""GREEN""). set(""B"", ""brown""). set(""yellow""). set(""red"").create()); VS(f_array_intersect_uassoc(3, array1, array2, ""strcasecmp""), CREATE_MAP1(""b"", ""brown"")); return Count(true); } bool TestExtArray::test_array_uintersect_assoc() { Array array1(ArrayInit(4).set(""a"", ""green""). set(""b"", ""brown""). set(""c"", ""blue""). set(""red"").create()); Array array2(ArrayInit(4).set(""a"", ""GREEN""). set(""B"", ""brown""). set(""yellow""). set(""red"").create()); VS(f_array_uintersect_assoc(3, array1, array2, ""strcasecmp""), CREATE_MAP1(""a"", ""green"")); return Count(true); } bool TestExtArray::test_array_uintersect_uassoc() { Array array1(ArrayInit(4).set(""a"", ""green""). set(""b"", ""brown""). set(""c"", ""blue""). set(""red"").create()); Array array2(ArrayInit(4).set(""a"", ""GREEN""). set(""B"", ""brown""). set(""yellow""). set(""red"").create()); VS(f_array_uintersect_uassoc(4, array1, array2, ""strcasecmp"", ""strcasecmp""), CREATE_MAP2(""a"", ""green"", ""b"", ""brown"")); return Count(true); } bool TestExtArray::test_array_intersect_key() { Array array1 = CREATE_MAP4(""blue"", 1, ""red"", 2, ""green"", 3, ""purple"", 4); Array array2 = CREATE_MAP4(""green"", 5, ""blue"", 6, ""yellow"", 7, ""cyan"", 8); VS(f_array_intersect_key(2, array1, array2), CREATE_MAP2(""blue"", 1, ""green"", 3)); VS(f_array_intersect_key(2, null, CREATE_MAP1(1, 1)), null); return Count(true); } bool TestExtArray::test_array_intersect_ukey() { Array array1 = CREATE_MAP4(""blue"", 1, ""red"", 2, ""green"", 3, ""purple"", 4); Array array2 = CREATE_MAP4(""green"", 5, ""blue"", 6, ""yellow"", 7, ""cyan"", 8); VS(f_array_intersect_ukey(3, array1, array2, ""strcasecmp""), CREATE_MAP2(""blue"", 1, ""green"", 3)); return Count(true); } bool TestExtArray::test_sort() { Variant fruits = CREATE_VECTOR4(""lemon"", ""orange"", ""banana"", ""apple""); f_sort(ref(fruits)); VS(f_print_r(fruits, true), ""Array\\n"" ""(\\n"" "" [0] => apple\\n"" "" [1] => banana\\n"" "" [2] => lemon\\n"" "" [3] => orange\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_rsort() { Variant fruits = CREATE_VECTOR4(""lemon"", ""orange"", ""banana"", ""apple""); f_rsort(ref(fruits)); VS(f_print_r(fruits, true), ""Array\\n"" ""(\\n"" "" [0] => orange\\n"" "" [1] => lemon\\n"" "" [2] => banana\\n"" "" [3] => apple\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_asort() { Variant fruits = CREATE_MAP4(""d"", ""lemon"", ""a"", ""orange"", ""b"", ""banana"", ""c"", ""apple""); f_asort(ref(fruits)); VS(f_print_r(fruits, true), ""Array\\n"" ""(\\n"" "" [c] => apple\\n"" "" [b] => banana\\n"" "" [d] => lemon\\n"" "" [a] => orange\\n"" "")\\n""); Variant arr = CREATE_VECTOR3(""at"", ""\\xe0s"", ""as""); f_i18n_loc_set_default(""en_US""); f_asort(ref(arr), 0, true); arr = CREATE_VECTOR3(""num2ber"", ""num1ber"", ""num10ber""); f_i18n_loc_set_default(""en_US""); f_i18n_loc_set_attribute(k_UCOL_NUMERIC_COLLATION, k_UCOL_ON); f_i18n_loc_set_strength(k_UCOL_PRIMARY); f_asort(ref(arr), k_SORT_REGULAR, true); f_i18n_loc_set_attribute(k_UCOL_NUMERIC_COLLATION, k_UCOL_DEFAULT); f_i18n_loc_set_strength(k_UCOL_DEFAULT); VS(f_print_r(arr, true), ""Array\\n"" ""(\\n"" "" [1] => num1ber\\n"" "" [0] => num2ber\\n"" "" [2] => num10ber\\n"" "")\\n""); arr = CREATE_VECTOR4(""G\\xediron"", // í (Latin-1) ""G\\xc3\\xb3nzales"", // ó (UTF-8) ""G\\xc3\\xa9 ara"", // é (UTF-8) ""G\\xe1rcia""); // á (Latin-1) f_i18n_loc_set_default(""en_US""); f_i18n_loc_set_attribute(k_UCOL_NUMERIC_COLLATION, k_UCOL_ON); f_i18n_loc_set_strength(k_UCOL_PRIMARY); f_asort(ref(arr), k_SORT_REGULAR, true); f_i18n_loc_set_attribute(k_UCOL_NUMERIC_COLLATION, k_UCOL_DEFAULT); f_i18n_loc_set_strength(k_UCOL_DEFAULT); VS(f_print_r(arr, true), ""Array\\n"" ""(\\n"" "" [0] => G\\xediron\\n"" "" [1] => G\\xc3\\xb3nzales\\n"" "" [2] => G\\xc3\\xa9 ara\\n"" "" [3] => G\\xe1rcia\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_arsort() { Variant fruits = CREATE_MAP4(""d"", ""lemon"", ""a"", ""orange"", ""b"", ""banana"", ""c"", ""apple""); f_arsort(ref(fruits)); VS(f_print_r(fruits, true), ""Array\\n"" ""(\\n"" "" [a] => orange\\n"" "" [d] => lemon\\n"" "" [b] => banana\\n"" "" [c] => apple\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_ksort() { Variant fruits = CREATE_MAP4(""d"", ""lemon"", ""a"", ""orange"", ""b"", ""banana"", ""c"", ""apple""); f_ksort(ref(fruits)); VS(f_print_r(fruits, true), ""Array\\n"" ""(\\n"" "" [a] => orange\\n"" "" [b] => banana\\n"" "" [c] => apple\\n"" "" [d] => lemon\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_krsort() { Variant fruits = CREATE_MAP4(""d"", ""lemon"", ""a"", ""orange"", ""b"", ""banana"", ""c"", ""apple""); f_krsort(ref(fruits)); VS(f_print_r(fruits, true), ""Array\\n"" ""(\\n"" "" [d] => lemon\\n"" "" [c] => apple\\n"" "" [b] => banana\\n"" "" [a] => orange\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_usort() { { Variant a = CREATE_VECTOR5(3, 2, 5, 6, 10); f_usort(ref(a), ""reverse_comp_func""); VS(a, CREATE_VECTOR5(10, 6, 5, 3, 2)); } return Count(true); } bool TestExtArray::test_uasort() { Variant fruits = CREATE_MAP4(""d"", ""lemon"", ""a"", ""orange"", ""b"", ""banana"", ""c"", ""apple""); f_uasort(ref(fruits), ""reverse_strcasecmp""); VS(f_print_r(fruits, true), ""Array\\n"" ""(\\n"" "" [a] => orange\\n"" "" [d] => lemon\\n"" "" [b] => banana\\n"" "" [c] => apple\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_uksort() { Variant fruits = CREATE_MAP4(""d"", ""lemon"", ""a"", ""orange"", ""b"", ""banana"", ""c"", ""apple""); f_uksort(ref(fruits), ""reverse_strcasecmp""); VS(f_print_r(fruits, true), ""Array\\n"" ""(\\n"" "" [d] => lemon\\n"" "" [c] => apple\\n"" "" [b] => banana\\n"" "" [a] => orange\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_natsort() { Variant array1 = CREATE_VECTOR4(""img12.png"", ""img10.png"", ""img2.png"", ""img1.png""); Variant array2 = array1; f_sort(ref(array1)); VS(f_print_r(array1, true), ""Array\\n"" ""(\\n"" "" [0] => img1.png\\n"" "" [1] => img10.png\\n"" "" [2] => img12.png\\n"" "" [3] => img2.png\\n"" "")\\n""); f_natsort(ref(array2)); VS(f_print_r(array2, true), ""Array\\n"" ""(\\n"" "" [3] => img1.png\\n"" "" [2] => img2.png\\n"" "" [1] => img10.png\\n"" "" [0] => img12.png\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_natcasesort() { Variant array1 = CREATE_VECTOR6(""IMG0.png"", ""img12.png"", ""img10.png"", ""img2.png"", ""img1.png"", ""IMG3.png""); Variant array2 = array1; f_sort(ref(array1)); VS(f_print_r(array1, true), ""Array\\n"" ""(\\n"" "" [0] => IMG0.png\\n"" "" [1] => IMG3.png\\n"" "" [2] => img1.png\\n"" "" [3] => img10.png\\n"" "" [4] => img12.png\\n"" "" [5] => img2.png\\n"" "")\\n""); f_natcasesort(ref(array2)); VS(f_print_r(array2, true), ""Array\\n"" ""(\\n"" "" [0] => IMG0.png\\n"" "" [4] => img1.png\\n"" "" [3] => img2.png\\n"" "" [5] => IMG3.png\\n"" "" [2] => img10.png\\n"" "" [1] => img12.png\\n"" "")\\n""); return Count(true); } bool TestExtArray::test_i18n_loc_get_default() { VERIFY(f_i18n_loc_set_default(""en_UK"")); VS(f_i18n_loc_get_default(), ""en_UK""); VERIFY(f_i18n_loc_set_default(""en_US"")); VS(f_i18n_loc_get_default(), ""en_US""); return Count(true); } ",16316,True,3559.750247841966,median "== Migration Changes === Migrating to 8.0.0 ==== New Default Hostname provider The old request and fixed hostname providers have been replaced with a new default hostname provider. The request and fixed hostname providers are now deprecated and it is recommended to switch to the default hostname provider as soon as possible. ==== Upgrade to Wildfly 18 The {project_name} server was upgraded to use Wildfly 18 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are a few changes related to the migration, which are worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 18 server. For example, Infinispan is now 9.4.16.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. ==== Deploying Scripts to the Server Until now, administrators were allowed to upload scripts to the server through the {project_name} Administration Console as well as through the RESTful Admin API. For now on, this capability is *disabled* by default and users should prefer to deploy scripts directly to the server. For more details, please take a look at link:{developerguide_jsproviders_link}[{developerguide_jsproviders_name}]. ==== Client Credentials in the JavaScript adapter In the previous releases, developers were allowed to provide client credentials to the JavaScript adapter. For now on, this capability was *removed*, because client-side apps are not safe to keep secrets. ==== Authentication flows changes We did some refactoring and improvements related to the authentication flows, which requires some attention during migration. OPTIONAL execution requirement removed:: Regarding migration, the most important change is removing the support for the OPTIONAL requirement from authentication executions and replacing it with the CONDITIONAL requirement, which allows more flexibility. The existing OPTIONAL authenticators configured in the previous version will be replaced with the CONDITIONAL subflows. These subflows will have the `Condition - User Configured` condition configured as first execution, and the previously OPTIONAL authenticator (for example `OTP Form`) as second execution. From the user's point of view, the behavior during authentication should be same as in the previous version. Changes in the Java SPI:: There are some changes in the Java Authentication SPI and Credential Provider SPI. The interface `Authenticator` is not changed, but you may be affected if you're developing more advanced authenticators, which introduce some new credential types (subclasses of `CredentialModel`). There are changes on the `CredentialProvider` interface and introduction of some new interfaces like `CredentialValidator`. Also you may be affected if your authenticator supported the OPTIONAL execution requirement. It is recommended to double check the latest authentication examples in the server development guide for more details. Freemarker template changes:: There are also some changes in the freemarker templates. You may be affected if you have your own theme with custom freemarker templates for login forms or some account forms, especially for the forms related to OTP. It is recommended to double check changes in the Freemarker templates in the latest {project_name} and align your templates according to it. ==== User credentials changes We added more flexibility around storing of user credentials. Among other things, every user can have multiple credentials of the same type, for example multiple OTP credentials. There are some changes in the database schema in relation to that, however the credentials from the previous version should be automatically updated to the new format and users should be still able to login with their passwords or OTP credentials set in the previous version. === Migrating to 7.0.0 ==== Upgrade to Wildfly 17 The {project_name} server was upgraded to use Wildfly 17 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are a few changes related to the migration, which are worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 17 server. For example, Infinispan is now 9.4.14.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. === Migrating to 6.0.0 ==== Upgrade to Wildfly 16 The {project_name} server was upgraded to use Wildfly 16 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are few changes related to the migration, which worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 16 server. For example, Infinispan is now 9.4.8.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. ==== New optional client scope We have added a new `microprofile-jwt` optional client scope to handle the claims defined in the https://wiki.eclipse.org/MicroProfile/JWT_Auth[MicroProfile/JWT Auth Specification]. This new client scope defines protocol mappers to set the username of the authenticated user to the `upn` claim and to set the realm roles to the `groups` claim. ==== Ability to propagate prompt=none to default IDP We have added a new switch in the OIDC identity provider configuration named `Accepts prompt=none forward from client` to identify IDPs that are able to handle forwarded requests that include the `prompt=none` query parameter. Until now, when receiving an auth request with `prompt=none` a realm would return a `login_required` error if the user is not authenticated in the realm without checking if the user has been authenticated by an IDP. From now on, if a default IDP can be determined for the auth request (either by the use of the `kc_idp_hint` query param or by setting up a default IDP for the realm) and if the `Accepts prompt=none forward from client` switch has been enabled for the IDP, the auth request is forwarded to the IDP to check if the user has been authenticated there. It is important to note that this switch is only taken into account if a default IDP is specified, in which case we know where to forward the auth request without having to prompt the user to select an IDP. If a default IDP cannot be determined we cannot assume which one will be used to fulfill the auth request so the request forwarding is not performed. === Migrating to 5.0.0 ==== Upgrade to Wildfly 15 The {project_name} server was upgraded to use Wildfly 15 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are few changes related to the migration, which worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 15 server. For example, Infinispan is now 9.4.3.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. === Migrating to 4.8.2 ==== Google Identity Provider updated to use Google Sign-in authentication system The Google Identity Provider implementation in {project_name} up to version 4.8.1 relies on the Google+ API endpoints endpoints for authorization and obtaining the user profile. From March 2019 onwards, Google is removing support for the Google+ API in favor of the new Google Sign-in authentication system. The {project_name} identity provider has been updated to use the new endpoints so if this integration is in use make sure you upgrade to {project_name} version 4.8.2 or later. If you run into an error saying that the application identifier was not found in the directory, you will have to register the client application again in the https://console.developers.google.com/apis/credentials[Google API Console] portal to obtain a new application id and secret. It is possible that you will need to adjust custom mappers for non-standard claims that were provided by Google+ user information endpoint and are provided under different name by Google Sign-in API. Please consult Google documentation for the most up-to-date information on available claims. ==== LinkedIn Social Broker Updated to Version 2 of LinkedIn APIs Accordingly with LinkedIn, all developers need to migrate to version 2.0 of their APIs and OAuth 2.0. As such, we have updated our LinkedIn Social Broker. Existing deployments using this broker may start experiencing errors when fetching user's profile using version 2 of LinkedIn APIs. This error may be related with the lack of permissions granted to the client application used to configure the broker which may not be authorized to access the Profile API or request specific OAuth2 scopes during the authentication process. Even for newly created LinkedIn client applications, you need to make sure that the client is able to request the `r_liteprofile` and `r_emailaddress` OAuth2 scopes, at least, as well that the client application can fetch current member's profile from the `https://api.linkedin.com/v2/me` endpoint. Due to these privacy restrictions imposed by LinkedIn in regards to access to member's information and the limited set of claims returned by the current member's Profile API, the LinkedIn Social Broker is now using the member's email address as the default username. That means that the `r_emailaddress` is always set when sending authorization requests during the authentication. === Migrating to 4.6.0 ==== New default client scopes We have added new realm default client scopes `roles` and `web-origins`. These client scopes contain protocol mappers to add the roles of the user and allowed web origins to the token. During migration, these client scopes should be automatically added to all the OpenID Connect clients as default client scopes. Hence no setup should be required after database migration is finished. ===== Protocol mapper SPI addition Related to this, there is a small addition in the (unsupported) Protocol Mappers SPI. You can be affected only if you implemented a custom ProtocolMapper. There is a new `getPriority()` method on the ProtocolMapper interface. The method has the default implementation set to return 0. If your protocol mapper implementation relies on the roles in the access token `realmAccess` or `resourceAccess` properties, you may need to increase the priority of your mapper. ===== Audience resolving Audiences of all the clients, for which authenticated user has at least one client role in the token, are automatically added to the `aud` claim in the access token now. On the other hand, an access token may not automatically contain the audience of the frontend client, for which it was issued. Read the link:{adminguide_link}#_audience[{adminguide_name}] for more details. ==== JavaScript Adapter Promise To use native JavaScript promise with the JavaScript adapter it is now required to set `promiseType` to `native` in the init options. In the past if native promise was available a wrapper was returned that provided both the legacy Keycloak promise and the native promise. This was causing issues as the error handler was not always set prior to the native error event, which resulted in `Uncaught (in promise)` error. ==== Microsoft Identity Provider updated to use the Microsoft Graph API The Microsoft Identity Provider implementation in {project_name} up to version 4.5.0 relies on the Live SDK endpoints for authorization and obtaining the user profile. From November 2018 onwards, Microsoft is removing support for the Live SDK API in favor of the new Microsoft Graph API. The {project_name} identity provider has been updated to use the new endpoints so if this integration is in use make sure you upgrade to {project_name} version 4.6.0 or later. Legacy client applications registered under ""Live SDK applications"" won't work with the Microsoft Graph endpoints due to changes in the id format of the applications. If you run into an error saying that the application identifier was not found in the directory, you will have to register the client application again in the https://account.live.com/developers/applications/create[Microsoft Application Registration] portal to obtain a new application id. ==== Upgrade to Wildfly 14 The {project_name} server was upgraded to use Wildfly 14 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are few changes related to the migration, which worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 14 server. For example, Infinispan is now 9.3.1.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. ifeval::[{project_product}==true] * There is a need to add `protocolVersion` property with the value `2.6` to the configuration of the `remote-store` element in the {project_name} configuration. This is required as there is a need to downgrade the version of HotRod protocol to be compatible with the version used by {jdgserver_name} {jdgserver_version}. endif::[] === Migrating to 4.4.0 ==== Upgrade to Wildfly 13 The {project_name} server was upgraded to use Wildfly 13 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are few changes related to the migration, which worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 13 server. For example, Infinispan is now 9.2.4.Final and Undertow is 2.0.9.Final Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. If more detail is needed, because, for example, you did some configuration changes on your own, here is a list of the most important changes: * Element `eviction` on infinispan caches is now deprecated (unused) and was replaced by element `object-memory` * There is no `jndi-attribute` on `cache-container` element in infinispan subsystem. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. * You don't need to configure security anymore in the {jdgserver_name} server configuration file. ifeval::[{project_community}==true] * There is a need to remove `transaction` element from the configuration of replicated caches in the {jdgserver_name} server configuration file. This is needed because of the infinispan bug https://issues.redhat.com/browse/ISPN-9323. endif::[] === Migration to 4.3.0 ==== Hostname configuration In previous versions it was recommended to use a filter to specify permitted hostnames. It is now possible to set a fixed hostname which makes it easier to make sure the valid hostname is used and also allows internal applications to invoke {project_name} through an alternative URL, for example an internal IP address. It is recommended that you switch to this approach in production. === Migrating to 4.0.0 ==== Client Templates changed to Client Scopes We added support for Client Scopes, which requires some attention during migration. Client Templates changed to Client Scopes:: Client Templates were changed to Client Scopes. If you had any Client Templates, their protocol mappers and role scope mappings will be preserved. Spaces replaced in the names:: Client templates with the space character in the name were renamed by replacing spaces with an underscore, because spaces are not allowed in the name of client scopes. For example, a client template `my template` will be changed to client scope `my_template`. Linking Client Scopes to Clients:: For clients which had the client template, the corresponding client scope is now added as `Default Client Scope` to the client. So protocol mappers and role scope mappings will be preserved on the client. Realm Default Client Scopes not linked with existing clients:: During the migration, the list of built-in client scopes is added to each realm as well as list of `Realm Default Client Scopes`. However, existing clients are NOT upgraded and new client scopes are NOT automatically added to them. Also all the protocol mappers and role scope mappings are kept on existing clients. In the new version, when you create a new client, it automatically has Realm Default Client Scopes attached to it and it does not have any protocol mappers attached to it. We did not change existing clients during migration as it would be impossible to properly detect customizations, which you will have for protocol mappers of the clients, for example. If you want to update existing clients (remove protocol mappers from them and link them with client scopes), you will need to do it manually. Consents need to be confirmed again:: The client scopes change required the refactoring of consents. Consents now point to client scopes, not to roles or protocol mappers. Because of this change, the previously confirmed persistent consents by users are not valid anymore and users need to confirm the consent page again after the migration. Some configuration switches removed:: The switch `Scope Param Required` was removed from Role Detail. The switches `Consent Required` and `Consent Text` were removed from the Protocol Mapper details. Those switches were replaced by the Client Scope feature. ==== Changes to Authorization Services We added support for UMA 2.0. This version of the UMA specification introduced some important changes on how permissions are obtained from the server. Here are the main changes introduced by UMA 2.0 support. See link:{authorizationguide_link}[{authorizationguide_name}] for details. Authorization API was removed:: Prior to UMA 2.0 (UMA 1.0), client applications were using the Authorization API to obtain permissions from the server in the format of a RPT. The new version of UMA specification has removed the Authorization API which was also removed from {project_name}. In UMA 2.0, RPTs can now be obtained from the token endpoint by using a specific grant type. See link:{authorizationguide_link}#_service_obtaining_permissions[{authorizationguide_name}] for details. Entitlement API was removed:: With the introduction of UMA 2.0, we decided to leverage the token endpoint and UMA grant type to allow obtaining RPTs from {project_name} and avoid having different APIs. The functionality provided by the Entitlement API was kept the same and is still possible to obtain permissions for a set of one or more resources and scopes or all permissions from the server in case no resource or scope is provided. See link:{authorizationguide_link}#_service_obtaining_permissions[{authorizationguide_name}] for details. Changes to UMA Discovery Endpoint:: UMA Discovery document changed, see link:{authorizationguide_link}#_service_authorization_api[{authorizationguide_name}] for details. Changes to {project_name} Authorization JavaScript Adapter:: The {project_name} Authorization JavaScript Adapter (keycloak-authz.js) changed in order to comply with the changes introduced by UMA 2.0 while keeping the same behavior as before. The main change is on how you invoke both `authorization` and `entitlement` methods which now expect a specific object type representing an authorization request. This new object type provides more flexibility on how permissions can be obtained from the server by supporting the different parameters supported by the UMA grant type. See link:{authorizationguide_link}#_enforcer_js_adapter[{authorizationguide_name}] for details. One of the main changes introduced by this release is that you are no longer required to exchange access tokens with RPTs in order to access resources protected by a resource server (when not using UMA). Depending on how the policy enforcer is configured on the resource server side, you can just send regular access tokens as a bearer token and permissions will still be enforced. Changes to {project_name} Authorization Client Java API:: When upgrading to the new version of {project_name} Authorization Client Java API, you'll notice that some representation classes were moved to a different package in `org.keycloak:keycloak-core`. === Migrating to 3.4.2 ==== Added session_state parameter to OpenID Connect Authentication Response The OpenID Connect Session Management specification requires that the parameter `session_state` is present in the OpenID Connect Authentication Response. In past releases, we did not have this parameter, but now {project_name} adds this parameter by default, as required by the specification. However, some OpenID Connect / OAuth2 adapters, and especially older {project_name} adapters, may have issues with this new parameter. For example, the parameter will be always present in the browser URL after successful authentication to the client application. In these cases, it may be useful to disable adding the `session_state` parameter to the authentication response. This can be done for the particular client in the {project_name} admin console, in client details in the section with `OpenID Connect Compatibility Modes`, described in <<_compatibility_with_older_adapters>>. There is the `Exclude Session State From Authentication Response` switch, which can be turned on to prevent adding the `session_state` parameter to the Authentication Response. NOTE: The parameter `session_state` was added in 3.4.2, however the switch `Exclude Session State From Authentication Response` was added in 4.0.0.Beta1. If your {project_name} server is on 3.4.2 or 3.4.3 and you have issues with `session_state` parameter, you will need to upgrade the server to 4.0.0.Beta1 or newer. === Migrating to 3.2.0 ==== New Password Hashing algorithms We've added two new password hashing algorithms (pbkdf2-sha256 and pbkdf2-sha512). New realms will use the pbkdf2-sha256 hashing algorithm with 27500 hashing iterations. Since pbkdf2-sha256 is slightly faster than pbkdf2 the iterations was increased to 27500 from 20000. Existing realms are upgraded if the password policy contains the default value for hashing algorithm (not specified) and iteration (20000). If you have changed the hashing iterations you need to manually change to pbkdf2-sha256 if you'd like to use the more secure hashing algorithm. ==== ID Token requires scope=openid OpenID Connect specification requires that parameter `scope` with value `openid` is used in initial authorization request. So in {project_name} 2.1.0 we changed our adapters to use `scope=openid` in the redirect URI to {project_name}. Now we changed the server part too and ID token will be sent to the application just if `scope=openid` is really used. If it's not used, then ID token will be skipped and just Access token and Refresh token will be sent to the application. This also allows that you can omit the generation of ID Token on purpose - for example for space or performance purposes. Direct grants (OAuth2 Resource Owner Password Credentials Grant) and Service accounts login (OAuth2 Client credentials grant) also don't use ID Token by default now. You need to explicitly add `scope=openid` parameter to have ID Token included. ==== Authentication sessions and Action tokens We are working on support for multiple datacenters. As the initial step, we introduced authentication session and action tokens. Authentication session replaces Client session, which was used in previous versions. Action tokens are currently used especially for the scenarios, where the authenticator or requiredActionProvider requires sending email to the user and requires user to click on the link in email. Here are concrete changes related to this, which may affect you for the migration. First change related to this is introducing new Infinispan caches `authenticationSessions` and `actionTokens` in `standalone.xml` or `standalone-ha.xml`. If you use our migration CLI, you don't need to care much as your `standalone(-ha).xml` files will be migrated automatically. Second change is changing of some signatures in methods of authentication SPI. This may affect you if you use custom `Authenticator` or `RequiredActionProvider`. Classes `AuthenticationFlowContext` and `RequiredActionContext` now allow to retrieve authentication session instead of client session. We also added some initial support for sticky sessions. You may want to change your loadbalancer/proxy server and configure it if you don't want to suffer from it and want to have better performance. The route is added to the new `AUTH_SESSION_ID` cookie. More info in the clustering documentation. Another change is, that `token.getClientSession()` was removed. This may affect you for example if you're using Client Initiated Identity Broker Linking feature. The `ScriptBasedAuthenticator` changed the binding name from `clientSession` to `authenticationSession`, so you would need to update your scripts if you're using this authenticator. Finally we added some new timeouts to the admin console. This allows you for example to specify different timeouts for the email actions triggered by admin and by user himself. === Migrating to 2.5.1 ==== Migration of old offline tokens If you migrate from version 2.2.0 or older and you used offline tokens, then your offline tokens didn't have KID in the token header. We added KID to the token header in 2.3.0 together with the ability to have multiple realm keys, so {project_name} is able to find the correct key based on the token KID. For the offline tokens without KID, {project_name} 2.5.1 will always use the active realm key to find the proper key for the token verification. In other words, migration of old offline tokens will work. So for example, your user requested offline token in 1.9.8, then you migrate from 1.9.8 to 2.5.1 and then your user will be still able to refresh his old offline token in 2.5.1 version. But there is limitation, that once you change the realm active key, the users won't be able to refresh old offline tokens anymore. So you shouldn't change the active realm key until all your users with offline tokens refreshed their tokens. Obviously newly refreshed tokens will have KID in the header, so after all users exchange their old offline tokens, you are free to change the active realm key. === Migrating to 2.5.0 ==== Changes to the Infinispan caches The `realms` cache defined in the infinispan subsystem in `standalone.xml` or `standalone-ha.xml` configuration file, now has the eviction with the 10000 records by default. This is the same default like the `users` cache. Also the `authorization` cache now doesn't have any eviction on it by default. === Migrating to 2.4.0 ==== Server SPI split into Server SPI and Sever SPI Private The keycloak-server-spi module has been split into keycloak-server-spi and keycloak-server-spi-private. APIs within keycloak-server-spi will not change between minor releases, while we reserve the right and may quite likely change APIs in keycloak-server-spi-private between minor releases. ==== Key encryption algorithm in SAML assertions Key in SAML assertions and documents are now encrypted using RSA-OAEP encryption scheme. If you want to use encrypted assertions, make sure that service providers understand this encryption scheme. In the unlikely case that SP would not be able to handle the new scheme, {project_name} can be made to use legacy RSA-v1.5 encryption scheme when started with system property `keycloak.saml.key_trans.rsa_v1.5` set to `true`. ==== Infinispan caches realms and users are always local Even if you use {project_name} in cluster, the caches `realms` and `users` defined in infinispan subsystem in `standalone-ha.xml` are always local caches now. There is separate cache `work`, which handles sending invalidation messages between cluster nodes and informing whole cluster what records in underlying `realms` and `users` caches should be invalidated. === Migrating to 2.3.0 ==== Default max results on paginated endpoints All Admin REST API endpoints that support pagination now have a default max results set to 100. If you want to return more than 100 entries you need to explicitly specify that with `?max=`. ==== `realm-public-key` adapter property not recommended In 2.3.0 release we added support for Public Key Rotation. When admin rotates the realm keys in Keycloak admin console, the Client Adapter will be able to recognize it and automatically download new public key from Keycloak. However this automatic download of new keys is done just if you don't have `realm-public-key` option in your adapter with the hardcoded public key. For this reason, we don't recommend to use `realm-public-key` option in adapter configuration anymore. Note this option is still supported, but it may be useful just if you really want to have hardcoded public key in your adapter configuration and never download the public key from Keycloak. In theory, one reason for this can be to avoid man-in-the-middle attack if you have untrusted network between adapter and Keycloak, however in that case, it is much better option to use HTTPS, which will secure all the requests between adapter and Keycloak. ==== Added Infinispan cache `keys` In this release, we added new cache `keys` to the infinispan subsystem, which is defined in `standalone.xml` or `standalone-ha.xml` configuration file. It has also some eviction and expiration defined. This cache is internally used for caching the external public keys of the entities trusted by the server (Identity providers or clients, which uses authentication with signed JWT). === Migrating to 2.2.0 ==== `databaseSchema` property deprecated The `databaseSchema` property for both JPA and Mongo is now deprecated and has been replaced by `initializeEmpty` and `migrationStrategy`. `initializeEmpty` can bet set to `true` or `false` and controls if an empty database should be initialized. `migrationStrategy` can be set to `update`, `validate` and `manual`. `manual` is only supported for relational databases and will write an SQL file with the required changes to the database schema. Please note that for Oracle database, the created SQL file contains `SET DEFINE OFF` command understood by Oracle SQL clients. Should the script be consumed by any other client, please replace the lines with equivalent command of the tool of your choice that disables variable expansion or remove it completely if such functionality is not applicable. ==== Changes in Client's Valid Redirect URIs The following scenarios are affected: * When a Valid Redirect URI with query component is saved in a Client (e.g. `\\http://localhost/auth?foo=bar`), `redirect_uri` in authorization request must exactly match this URI (or other registered URI in this Client). * When a Valid Redirect URI without a query component is saved in a Client, `redirect_uri` must exactly match as well. * Wildcards in registered Valid Redirect URIs are no longer supported when query component is present in this URI, so the `redirect_uri` needs to exactly match this saved URI as well. * Fragments in registered Valid Redirect URIs (like `\\http://localhost/auth#fragment`) are no longer allowed. ==== Authenticate by default removed from Identity Providers Identity providers no longer has an option to set it as a default authentication provider. Instead go to Authentication, select the `Browser` flow and configure the `Identity Provider Redirector`. It has an option to set the default identity provider. === Migrating to 2.0.0 ==== Upgrading from 1.0.0.Final no longer supported Upgrading from 1.0.0.Final is no longer supported. To upgrade to this version upgrade to 1.9.8.Final prior to upgrading to 2.0.0. === Migrating to 1.9.5 ==== Default password hashing interval increased to 20K The default password hashing interval for new realms has been increased to 20K (from 1 previously). This change will have an impact on performance when users authenticate. For example with the old default (1) it takes less than 1 ms to hash a password, but with the new default (20K) the same operation can take 50-100 ms. === Migrating to 1.9.3 ==== Add User script renamed The script to add admin users to Keycloak has been renamed to `add-user-keycloak`. === Migrating to 1.9.2 ==== Adapter option auth-server-url-for-backend-requests removed We've removed the option auth-server-url-for-backend-requests as there were issues in some scenarios when it was used. In more details, it was possible to access the Keycloak server from 2 different contexts (internal and external), which was causing issues in token validations etc. If you still want to use the optimization of network, which this option provided (avoid the application to send backchannel requests through loadbalancer but send them to local Keycloak server directly) you may need to handle it at hosts configuration (DNS) level. === Migrating to 1.9.0 ==== Themes and providers directory moved We've moved the themes and providers directories from `standalone/configuration/themes` and `standalone/configuration/providers` to `themes` and `providers` respectively. If you have added custom themes and providers you need to move them to the new location. You also need to update `keycloak-server.json` as it's changed due to this. ==== Adapter Subsystems only bring in dependencies if Keycloak is on Previously, if you had installed our SAML or OIDC Keycloak subsystem adapters into WildFly or JBoss EAP, we would automatically include Keycloak client jars into EVERY application irregardless if you were using Keycloak or not. These libraries are now only added to your deployment if you have Keycloak authentication turned on for that adapter (via the subsystem, or auth-method in web.xml) ==== Client Registration service endpoints moved The Client Registration service endpoints have been moved from `{realm-name}/clients` to `{realm-name}/clients-registrations`. ==== Session state parameter in authentication response renamed In the OpenID Connect authentication response we used to return the session state as `session-state` this is not correct according to the specification and has been renamed to `session_state`. ==== Deprecated OpenID Connect endpoints In 1.2 we deprecated a number of endpoints that where not consistent with the OpenID Connect specifications, these have now been removed. This also applies to the validate token endpoints that was replaced with the new introspect endpoint in 1.8. ==== Updates to theme templates Feedback in template.ftl has been moved and format has changed slightly. ==== Module and Source Code Re-org Most of our modules and source code have been consolidated into two maven modules: keycloak-server-spi and keycloak-services. SPI interfaces are in server-spi, implementations are in keycloak-services. All JPA dependent modules have been consolidated under keycloak-model-jpa. Same goes with mongo and Infinispan under modules keycloak-model-mongo and keycloak-model-infinispan. ==== For adapters, session id changed after login To plug a security attack vector, for platforms that support it (Tomcat 8, Undertow/WildFly, Jetty 9), the Keycloak OIDC and SAML adapters will change the session id after login. You can turn off this behavior check adapter config switches. ==== SAML SP Client Adapter Changes Keycloak SAML SP Client Adapter now requires a specific endpoint, `/saml` to be registered with your IDP. === Migrating to 1.8.0 ==== Admin account In previous releases we shipped with a default admin user with a default password, this has now been removed. If you are doing a new installation of 1.8 you will have to create an admin user as a first step. ==== OAuth2 Token Introspection In order to add more compliance with OAuth2 specification, we added a new endpoint for token introspection. The new endpoint can reached at `/realms/{realm-name}/protocols/openid-connect/token/introspect` and it is solely based on `RFC-7662`. The `/realms/{realm-name}/protocols/openid-connect/validate` endpoint is now deprecated and we strongly recommend you to move to the new introspection endpoint as soon as possible. The reason for this change is that RFC-7662 provides a more standard and secure introspection endpoint. The new token introspection URL can now be obtained from OpenID Connect Provider's configuration at `/realms/{realm-name}/.well-known/openid-configuration`. There you will find a claim with name `token_introspection_endpoint` within the response. Only `confidential clients` are allowed to invoke the new endpoint, where these clients will be usually acting as a resource server and looking for token metadata in order to perform local authorization checks. === Migrating to 1.7.0.CR1 ==== Direct access grants disabled by default for clients In order to add more compliance with OpenID Connect specification, we added flags into admin console to Client Settings page, where you can enable/disable various kinds of OpenID Connect/OAuth2 flows (Standard flow, Implicit flow, Direct Access Grants, Service Accounts). As part of this, we have `Direct Access Grants` (corresponds to OAuth2 `Resource Owner Password Credentials Grant`) disabled by default for new clients. Clients migrated from previous version have `Direct Access Grants` enabled just if they had flag `Direct Grants Only` on. The `Direct Grants Only` flag was removed as if you enable Direct Access Grants and disable both Standard+Implicit flow, you will achieve same effect. We also added built-in client `admin-cli` to each realm. This client has `Direct Access Grants` enabled. So if you're using Admin REST API or Keycloak admin-client, you should update your configuration to use `admin-cli` instead of `security-admin-console` as the latter one doesn't have direct access grants enabled anymore by default. ==== Option 'Update Profile On First Login' moved from Identity provider to Review Profile authenticator In this version, we added `First Broker Login`, which allows you to specify what exactly should be done when new user is logged through Identity provider (or Social provider), but there is no existing Keycloak user yet linked to the social account. As part of this work, we added option `First Login Flow` to identity providers where you can specify the flow and then you can configure this flow under `Authentication` tab in admin console. We also removed the option `Update Profile On First Login` from the Identity provider settings and moved it to the configuration of `Review Profile` authenticator. So once you specify which flow should be used for your Identity provider (by default it's `First Broker Login` flow), you go to `Authentication` tab, select the flow and then you configure the option under `Review Profile` authenticator. ==== Element 'form-error-page' in web.xml not supported anymore form-error-page in web.xml will no longer work for client adapter authentication errors. You must define an error-page for the various HTTP error codes. See documentation for more details if you want to catch and handle adapter error conditions. ==== IdentityProviderMapper changes There is no change in the interface itself or method signatures. However there is some change in behavior. We added `First Broker Login` flow in this release and the method `IdentityProviderMapper.importNewUser` is now called after `First Broker Login` flow is finished. So if you want to have any attribute available in `Review Profile` page, you would need to use the method `preprocessFederatedIdentity` instead of `importNewUser` . You can set any attribute by invoke `BrokeredIdentityContext.setUserAttribute` and that will be available on `Review profile` page. === Migrating to 1.6.0.Final ==== Option that refresh tokens are not reusable anymore Old versions of Keycloak allowed reusing refresh tokens multiple times. Keycloak still permits this, but also have an option `Revoke refresh token` to disallow it. Option is under token settings in admin console. When a refresh token is used to obtain a new access token a new refresh token is also included. When option is enabled, then this new refresh token should be used next time the access token is refreshed. It won't be possible to reuse old refresh token multiple times. ==== Some packages renamed We did a bit of restructure and renamed some packages. It is mainly about renaming internal packages of util classes. The most important classes used in your application ( for example AccessToken or KeycloakSecurityContext ) as well as the SPI are still unchanged. However there is slight chance that you will be affected and will need to update imports of your classes. For example if you are using multitenancy and KeycloakConfigResolver, you will be affected as for example class HttpFacade was moved to different package - it is `org.keycloak.adapters.spi.HttpFacade` now. ==== Persisting user sessions We added support for offline tokens in this release, which means that we are persisting ""offline"" user sessions into database now. If you are not using offline tokens, nothing will be persisted for you, so you don't need to care about worse performance for more DB writes. However in all cases, you will need to update `standalone/configuration/keycloak-server.json` and add `userSessionPersister` like this: [source,json] ---- ""userSessionPersister"": { ""provider"": ""jpa"" }, ---- If you want sessions to be persisted in Mongo instead of classic RDBMS, use provider `mongo` instead. === Migrating to 1.5.0.Final ==== Realm and User cache providers Infinispan is now the default and only realm and user cache providers. In non-clustered mode a local Infinispan cache is used. We've also removed our custom in-memory cache and the no cache providers. If you have realmCache or userCache set in keycloak-server.json to mem or none please remove these. As Infinispan is the only provider there's no longer any need for the realmCache and userCache objects so these can be removed. ==== Uses Session providers Infinispan is now the default and only user session provider. In non-clustered mode a local Infinispan cache is used. We've also removed the JPA and Mongo user session providers. If you have userSession set in keycloak-server.json to mem, jpa or mongo please remove it. As Infinispan is the only provider there's no longer any need for the userSession object so it can be removed. For anyone that wants to achieve increased durability of user sessions this can be achieved by configuring the user session cache with more than one owner or use a replicated cache. It's also possible to configure Infinispan to persist caches, although that would have impacts on performance. ==== Contact details removed from registration and account management In the default theme we have now removed the contact details from the registration page and account management. The admin console now lists all the users attributes, not just contact specific attributes. The admin console also has the ability to add/remove attributes to a user. If you want to add contact details, please refer to the address theme included in the examples. === Migrating to 1.3.0.Final ==== Direct Grant API always enabled In the past Direct Grant API (or Resource Owner Password Credentials) was disabled by default and there was an option on a realm to enable it. The Direct Grant API is now always enabled and the option to enable/disable for a realm is removed. ==== Database changed There are again few database changes. Remember to backup your database prior to upgrading. ==== UserFederationProvider changed There are few minor changes in UserFederationProvider interface. You may need to sync your implementation when upgrade to newer version and upgrade few methods, which has changed signature. Changes are really minor, but were needed to improve performance of federation. ==== WildFly 9.0.0.Final Following on from the distribution changes that was done in the last release the standalone download of Keycloak is now based on WildFly 9.0.0.Final. This also affects the overlay which can only be deployed to WildFly 9.0.0.Final or JBoss EAP 6.4.0.GA. WildFly 8.2.0.Final is no longer supported for the server. ==== WildFly, JBoss EAP and JBoss AS7 adapters There are now 3 separate adapter downloads for WildFly, JBoss EAP and JBoss AS7: * eap6 * wf9 * wf8 * as7 Make sure you grab the correct one. You also need to update standalone.xml as the extension module and subsystem definition has changed. See link:{adapterguide_link}[{adapterguide_name}] for details. === Migrating from 1.2.0.Beta1 to 1.2.0.RC1 ==== Distribution changes Keycloak is now available in 3 downloads: standalone, overlay and demo bundle. The standalone is intended for production and non-JEE developers. Overlay is aimed at adding Keycloak to an existing WildFly 8.2 or EAP 6.4 installation and is mainly for development. Finally we have a demo (or dev) bundle that is aimed at developers getting started with Keycloak. This bundle contains a WildFly server, with Keycloak server and adapter included. It also contains all documentation and examples. ==== Database changed This release contains again a number of changes to the database. The biggest one is Application and OAuth client merge. Remember to backup your database prior to upgrading. ==== Application and OAuth client merge Application and OAuth clients are now merged into `Clients`. The UI of admin console is updated and database as well. Your data from database should be automatically updated. The previously set Applications will be converted into Clients with `Consent required` switch off and OAuth Clients will be converted into Clients with this switch on. === Migrating from 1.1.0.Final to 1.2.0.Beta1 ==== Database changed This release contains a number of changes to the database. Remember to backup your database prior to upgrading. ==== `iss` in access and id tokens The value of `iss` claim in access and id tokens have changed from `realm name` to `realm url`. This is required by OpenID Connect specification. If you're using our adapters there's no change required, other than if you've been using bearer-only without specifying `auth-server-url` you have to add it now. If you're using another library (or RSATokenVerifier) you need to make the corresponding changes when verifying `iss`. ==== OpenID Connect endpoints To comply with OpenID Connect specification the authentication and token endpoints have been changed to having a single authentication endpoint and a single token endpoint. As per-spec `response_type` and `grant_type` parameters are used to select the required flow. The old endpoints (`/realms/{realm-name}/protocols/openid-connect/login`, `/realms/{realm-name}/protocols/openid-connect/grants/access`, `/realms/{realm-name}/protocols/openid-connect/refresh`, `/realms/{realm-name}/protocols/openid-connect/access/codes`) are now deprecated and will be removed in a future version. ==== Theme changes The layout of themes has changed. The directory hierarchy used to be `type/name` this is now changed to `name/type`. For example a login theme named `sunrise` used to be deployed to `standalone/configuration/themes/login/sunrise`, which is now moved to `standalone/configuration/themes/sunrise/login`. This change was done to make it easier to have groups of the different types for the same theme into one folder. If you deployed themes as a JAR in the past you had to create a custom theme loader which required Java code. This has been simplified to only requiring a plain text file (`META-INF/keycloak-themes.json`) to describe the themes included in a JAR. ==== Claims changes Previously there was `Claims` tab in admin console for application and OAuth clients. This was used to configure which attributes should go into access token for particular application/client. This was removed and replaced with protocol mappers which are more flexible. You don't need to care about migration of database from previous version. We did migration scripts for both RDBMS and Mongo, which should ensure that claims configured for particular application/client will be converted into corresponding protocol mappers (Still it's safer to backup DB before migrating to newer version though). Same applies for exported JSON representation from previous version. ==== Social migration to identity brokering We refactored social providers SPI and replaced it with Identity Brokering SPI, which is more flexible. The `Social` tab in admin console is renamed to `Identity Provider` tab. Again you don't need to care about migration of database from previous version similarly like for Claims/protocol mappers. Both configuration of social providers and ""social links"" to your users will be converted to corresponding Identity providers. Only required action from you would be to change allowed `Redirect URI` in the admin console of particular 3rd party social providers. You can first go to the Keycloak admin console and copy Redirect URI from the page where you configure the identity provider. Then you can simply paste this as allowed Redirect URI to the admin console of 3rd party provider (IE. Facebook admin console). === Migrating from 1.1.0.Beta1 to 1.1.0.Beta2 * Adapters are now a separate download. They are not included in appliance and war distribution. We have too many now and the distro is getting bloated. * `org.keycloak.adapters.tomcat7.KeycloakAuthenticatorValve` +`org.keycloak.adapters.tomcat.KeycloakAuthenticatorValve` * JavaScript adapter now has idToken and idTokenParsed properties. If you use idToken to retrieve first name, email, etc. you need to change this to idTokenParsed. * The as7-eap-subsystem and keycloak-wildfly-subsystem have been merged into one keycloak-subsystem. If you have an existing standalone.xml or domain.xml, you will need edit near the top of the file and change the extension module name to org.keycloak.keycloak-subsystem. For AS7 only, the extension module name is org.keycloak.keycloak-as7-subsystem. * Server installation is no longer supported on AS7. You can still use AS7 as an application client. === Migrating from 1.0.x.Final to 1.1.0.Beta1 * RealmModel JPA and Mongo storage schema has changed * UserSessionModel JPA and Mongo storage schema has changed as these interfaces have been refactored * Upgrade your adapters, old adapters are not compatible with Keycloak 1.1. We interpreted JSON Web Token and OIDC ID Token specification incorrectly. 'aud' claim must be the client id, we were storing the realm name in there and validating it. === Migrating from 1.0 RC-1 to RC-2 * A lot of info level logging has been changed to debug. Also, a realm no longer has the jboss-logging audit listener by default. If you want log output when users login, logout, change passwords, etc. enable the jboss-logging audit listener through the admin console. === Migrating from 1.0 Beta 4 to RC-1 * logout REST API has been refactored. The GET request on the logout URI does not take a session_state parameter anymore. You must be logged in in order to log out the session. You can also POST to the logout REST URI. This action requires a valid refresh token to perform the logout. The signature is the same as refresh token minus the grant type form parameter. See documentation for details. === Migrating from 1.0 Beta 1 to Beta 4 * LDAP/AD configuration is changed. It is no longer under the ""Settings"" page. It is now under Users->Federation. Add Provider will show you an ""ldap"" option. * Authentication SPI has been removed and rewritten. The new SPI is UserFederationProvider and is more flexible. * `ssl-not-required` +`ssl-required` +`all` +`external` +`none` * DB Schema has changed again. * Created applications now have a full scope by default. This means that you don't have to configure the scope of an application if you don't want to. * Format of JSON file for importing realm data was changed. Now role mappings is available under the JSON record of particular user. === Migrating from 1.0 Alpha 4 to Beta 1 * DB Schema has changed. We have added export of the database to Beta 1, but not the ability to import the database from older versions. This will be supported in future releases. * For all clients except bearer-only applications, you must specify at least one redirect URI. Keycloak will not allow you to log in unless you have specified a valid redirect URI for that application. * Direct Grant API +`ON` * standalone/configuration/keycloak-server.json * JavaScript adapter * Session Timeout === Migrating from 1.0 Alpha 2 to Alpha 3 * SkeletonKeyToken, SkeletonKeyScope, SkeletonKeyPrincipal, and SkeletonKeySession have been renamed to: AccessToken, AccessScope, KeycloakPrincipal, and KeycloakAuthenticatedSession respectively. * ServletOAuthClient.getBearerToken() method signature has changed. It now returns an AccessTokenResponse so that you can obtain a refresh token too. * Adapters now check the access token expiration with every request. If the token is expired, they will attempt to invoke a refresh on the auth server using a saved refresh token. * Subject in AccessToken has been changed to the User ID. === Migrating from 1.0 Alpha 1 to Alpha 2 * DB Schema has changed. We don't have any data migration utilities yet as of Alpha 2. * JBoss and WildFly adapters are now installed via a {appserver_name} subsystem. Please review the adapter installation documentation. Edits to standalone.xml are now required. * There is a new credential type ""secret"". Unlike other credential types, it is stored in plain text in the database and can be viewed in the admin console. * There is no longer required Application or OAuth Client credentials. These client types are now hard coded to use the ""secret"" credential type. * Because of the ""secret"" credential change to Application and OAuth Client, you'll have to update your keycloak.json configuration files and regenerate a secret within the Application or OAuth Client credentials tab in the administration console. ",12187,False,1953.9470992690538,median "// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google Inc. 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS // ""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 THE COPYRIGHT // OWNER OR CONTRIBUTORS 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. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include #include #include #include #include #include #include #include #include namespace google { namespace protobuf { namespace internal { namespace { inline WireFormatLite::FieldType real_type(FieldType type) { GOOGLE_DCHECK(type > 0 && type <= WireFormatLite::MAX_FIELD_TYPE); return static_cast(type); } inline WireFormatLite::CppType cpp_type(FieldType type) { return WireFormatLite::FieldTypeToCppType(real_type(type)); } inline bool is_packable(WireFormatLite::WireType type) { switch (type) { case WireFormatLite::WIRETYPE_VARINT: case WireFormatLite::WIRETYPE_FIXED64: case WireFormatLite::WIRETYPE_FIXED32: return true; case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: case WireFormatLite::WIRETYPE_START_GROUP: case WireFormatLite::WIRETYPE_END_GROUP: return false; // Do not add a default statement. Let the compiler complain when someone // adds a new wire type. } GOOGLE_LOG(FATAL) << ""can't reach here.""; return false; } // Registry stuff. typedef hash_map, ExtensionInfo> ExtensionRegistry; ExtensionRegistry* registry_ = NULL; GOOGLE_PROTOBUF_DECLARE_ONCE(registry_init_); void DeleteRegistry() { delete registry_; registry_ = NULL; } void InitRegistry() { registry_ = new ExtensionRegistry; OnShutdown(&DeleteRegistry); } // This function is only called at startup, so there is no need for thread- // safety. void Register(const MessageLite* containing_type, int number, ExtensionInfo info) { ::google::protobuf::GoogleOnceInit(®istry_init_, &InitRegistry); if (!InsertIfNotPresent(registry_, std::make_pair(containing_type, number), info)) { GOOGLE_LOG(FATAL) << ""Multiple extension registrations for type \\"""" << containing_type->GetTypeName() << ""\\"", field number "" << number << "".""; } } const ExtensionInfo* FindRegisteredExtension( const MessageLite* containing_type, int number) { return (registry_ == NULL) ? NULL : FindOrNull(*registry_, std::make_pair(containing_type, number)); } } // namespace ExtensionFinder::~ExtensionFinder() {} bool GeneratedExtensionFinder::Find(int number, ExtensionInfo* output) { const ExtensionInfo* extension = FindRegisteredExtension(containing_type_, number); if (extension == NULL) { return false; } else { *output = *extension; return true; } } void ExtensionSet::RegisterExtension(const MessageLite* containing_type, int number, FieldType type, bool is_repeated, bool is_packed) { GOOGLE_CHECK_NE(type, WireFormatLite::TYPE_ENUM); GOOGLE_CHECK_NE(type, WireFormatLite::TYPE_MESSAGE); GOOGLE_CHECK_NE(type, WireFormatLite::TYPE_GROUP); ExtensionInfo info(type, is_repeated, is_packed); Register(containing_type, number, info); } static bool CallNoArgValidityFunc(const void* arg, int number) { // Note: Must use C-style cast here rather than reinterpret_cast because // the C++ standard at one point did not allow casts between function and // data pointers and some compilers enforce this for C++-style casts. No // compiler enforces it for C-style casts since lots of C-style code has // relied on these kinds of casts for a long time, despite being // technically undefined. See: // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#195 // Also note: Some compilers do not allow function pointers to be ""const"". // Which makes sense, I suppose, because it's meaningless. return ((EnumValidityFunc*)arg)(number); } void ExtensionSet::RegisterEnumExtension(const MessageLite* containing_type, int number, FieldType type, bool is_repeated, bool is_packed, EnumValidityFunc* is_valid) { GOOGLE_CHECK_EQ(type, WireFormatLite::TYPE_ENUM); ExtensionInfo info(type, is_repeated, is_packed); info.enum_validity_check.func = CallNoArgValidityFunc; // See comment in CallNoArgValidityFunc() about why we use a c-style cast. info.enum_validity_check.arg = (void*)is_valid; Register(containing_type, number, info); } void ExtensionSet::RegisterMessageExtension(const MessageLite* containing_type, int number, FieldType type, bool is_repeated, bool is_packed, const MessageLite* prototype) { GOOGLE_CHECK(type == WireFormatLite::TYPE_MESSAGE || type == WireFormatLite::TYPE_GROUP); ExtensionInfo info(type, is_repeated, is_packed); info.message_prototype = prototype; Register(containing_type, number, info); } // =================================================================== // Constructors and basic methods. ExtensionSet::ExtensionSet(::google::protobuf::Arena* arena) : arena_(arena) { if (arena_ != NULL) { arena_->OwnDestructor(&extensions_); } } ExtensionSet::ExtensionSet() : arena_(NULL) {} ExtensionSet::~ExtensionSet() { // Deletes all allocated extensions. if (arena_ == NULL) { for (map::iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { iter->second.Free(); } } } // Defined in extension_set_heavy.cc. // void ExtensionSet::AppendToList(const Descriptor* containing_type, // const DescriptorPool* pool, // vector* output) const bool ExtensionSet::Has(int number) const { map::const_iterator iter = extensions_.find(number); if (iter == extensions_.end()) return false; GOOGLE_DCHECK(!iter->second.is_repeated); return !iter->second.is_cleared; } int ExtensionSet::NumExtensions() const { int result = 0; for (map::const_iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { if (!iter->second.is_cleared) { ++result; } } return result; } int ExtensionSet::ExtensionSize(int number) const { map::const_iterator iter = extensions_.find(number); if (iter == extensions_.end()) return false; return iter->second.GetSize(); } FieldType ExtensionSet::ExtensionType(int number) const { map::const_iterator iter = extensions_.find(number); if (iter == extensions_.end()) { GOOGLE_LOG(DFATAL) << ""Don't lookup extension types if they aren't present (1). ""; return 0; } if (iter->second.is_cleared) { GOOGLE_LOG(DFATAL) << ""Don't lookup extension types if they aren't present (2). ""; } return iter->second.type; } void ExtensionSet::ClearExtension(int number) { map::iterator iter = extensions_.find(number); if (iter == extensions_.end()) return; iter->second.Clear(); } // =================================================================== // Field accessors namespace { enum Cardinality { REPEATED, OPTIONAL }; } // namespace #define GOOGLE_DCHECK_TYPE(EXTENSION, LABEL, CPPTYPE) \\ GOOGLE_DCHECK_EQ((EXTENSION).is_repeated ? REPEATED : OPTIONAL, LABEL); \\ GOOGLE_DCHECK_EQ(cpp_type((EXTENSION).type), WireFormatLite::CPPTYPE_##CPPTYPE) // ------------------------------------------------------------------- // Primitives #define PRIMITIVE_ACCESSORS(UPPERCASE, LOWERCASE, CAMELCASE) \\ \\ LOWERCASE ExtensionSet::Get##CAMELCASE(int number, \\ LOWERCASE default_value) const { \\ map::const_iterator iter = extensions_.find(number); \\ if (iter == extensions_.end() || iter->second.is_cleared) { \\ return default_value; \\ } else { \\ GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, UPPERCASE); \\ return iter->second.LOWERCASE##_value; \\ } \\ } \\ \\ void ExtensionSet::Set##CAMELCASE(int number, FieldType type, \\ LOWERCASE value, \\ const FieldDescriptor* descriptor) { \\ Extension* extension; \\ if (MaybeNewExtension(number, descriptor, &extension)) { \\ extension->type = type; \\ GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_##UPPERCASE); \\ extension->is_repeated = false; \\ } else { \\ GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, UPPERCASE); \\ } \\ extension->is_cleared = false; \\ extension->LOWERCASE##_value = value; \\ } \\ \\ LOWERCASE ExtensionSet::GetRepeated##CAMELCASE(int number, int index) const { \\ map::const_iterator iter = extensions_.find(number); \\ GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; \\ GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \\ return iter->second.repeated_##LOWERCASE##_value->Get(index); \\ } \\ \\ void ExtensionSet::SetRepeated##CAMELCASE( \\ int number, int index, LOWERCASE value) { \\ map::iterator iter = extensions_.find(number); \\ GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; \\ GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \\ iter->second.repeated_##LOWERCASE##_value->Set(index, value); \\ } \\ \\ void ExtensionSet::Add##CAMELCASE(int number, FieldType type, \\ bool packed, LOWERCASE value, \\ const FieldDescriptor* descriptor) { \\ Extension* extension; \\ if (MaybeNewExtension(number, descriptor, &extension)) { \\ extension->type = type; \\ GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_##UPPERCASE); \\ extension->is_repeated = true; \\ extension->is_packed = packed; \\ extension->repeated_##LOWERCASE##_value = \\ Arena::Create >(arena_, arena_); \\ } else { \\ GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \\ GOOGLE_DCHECK_EQ(extension->is_packed, packed); \\ } \\ extension->repeated_##LOWERCASE##_value->Add(value); \\ } PRIMITIVE_ACCESSORS( INT32, int32, Int32) PRIMITIVE_ACCESSORS( INT64, int64, Int64) PRIMITIVE_ACCESSORS(UINT32, uint32, UInt32) PRIMITIVE_ACCESSORS(UINT64, uint64, UInt64) PRIMITIVE_ACCESSORS( FLOAT, float, Float) PRIMITIVE_ACCESSORS(DOUBLE, double, Double) PRIMITIVE_ACCESSORS( BOOL, bool, Bool) #undef PRIMITIVE_ACCESSORS const void* ExtensionSet::GetRawRepeatedField(int number, const void* default_value) const { map::const_iterator iter = extensions_.find(number); if (iter == extensions_.end()) { return default_value; } // We assume that all the RepeatedField<>* pointers have the same // size and alignment within the anonymous union in Extension. return iter->second.repeated_int32_value; } void* ExtensionSet::MutableRawRepeatedField(int number, FieldType field_type, bool packed, const FieldDescriptor* desc) { Extension* extension; // We instantiate an empty Repeated{,Ptr}Field if one doesn't exist for this // extension. if (MaybeNewExtension(number, desc, &extension)) { extension->is_repeated = true; extension->type = field_type; extension->is_packed = packed; switch (WireFormatLite::FieldTypeToCppType( static_cast(field_type))) { case WireFormatLite::CPPTYPE_INT32: extension->repeated_int32_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_INT64: extension->repeated_int64_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_UINT32: extension->repeated_uint32_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_UINT64: extension->repeated_uint64_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_DOUBLE: extension->repeated_double_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_FLOAT: extension->repeated_float_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_BOOL: extension->repeated_bool_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_ENUM: extension->repeated_enum_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_STRING: extension->repeated_string_value = Arena::Create >(arena_, arena_); break; case WireFormatLite::CPPTYPE_MESSAGE: extension->repeated_message_value = Arena::Create >(arena_, arena_); break; } } // We assume that all the RepeatedField<>* pointers have the same // size and alignment within the anonymous union in Extension. return extension->repeated_int32_value; } // Compatible version using old call signature. Does not create extensions when // the don't already exist; instead, just GOOGLE_CHECK-fails. void* ExtensionSet::MutableRawRepeatedField(int number) { map::iterator iter = extensions_.find(number); GOOGLE_CHECK(iter == extensions_.end()) << ""Extension not found.""; // We assume that all the RepeatedField<>* pointers have the same // size and alignment within the anonymous union in Extension. return iter->second.repeated_int32_value; } // ------------------------------------------------------------------- // Enums int ExtensionSet::GetEnum(int number, int default_value) const { map::const_iterator iter = extensions_.find(number); if (iter == extensions_.end() || iter->second.is_cleared) { // Not present. Return the default value. return default_value; } else { GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, ENUM); return iter->second.enum_value; } } void ExtensionSet::SetEnum(int number, FieldType type, int value, const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_ENUM); extension->is_repeated = false; } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, ENUM); } extension->is_cleared = false; extension->enum_value = value; } int ExtensionSet::GetRepeatedEnum(int number, int index) const { map::const_iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM); return iter->second.repeated_enum_value->Get(index); } void ExtensionSet::SetRepeatedEnum(int number, int index, int value) { map::iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM); iter->second.repeated_enum_value->Set(index, value); } void ExtensionSet::AddEnum(int number, FieldType type, bool packed, int value, const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_ENUM); extension->is_repeated = true; extension->is_packed = packed; extension->repeated_enum_value = Arena::Create >(arena_, arena_); } else { GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); GOOGLE_DCHECK_EQ(extension->is_packed, packed); } extension->repeated_enum_value->Add(value); } // ------------------------------------------------------------------- // Strings const string& ExtensionSet::GetString(int number, const string& default_value) const { map::const_iterator iter = extensions_.find(number); if (iter == extensions_.end() || iter->second.is_cleared) { // Not present. Return the default value. return default_value; } else { GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, STRING); return *iter->second.string_value; } } string* ExtensionSet::MutableString(int number, FieldType type, const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_STRING); extension->is_repeated = false; extension->string_value = Arena::Create(arena_); } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, STRING); } extension->is_cleared = false; return extension->string_value; } const string& ExtensionSet::GetRepeatedString(int number, int index) const { map::const_iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING); return iter->second.repeated_string_value->Get(index); } string* ExtensionSet::MutableRepeatedString(int number, int index) { map::iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING); return iter->second.repeated_string_value->Mutable(index); } string* ExtensionSet::AddString(int number, FieldType type, const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_STRING); extension->is_repeated = true; extension->is_packed = false; extension->repeated_string_value = Arena::Create >(arena_, arena_); } else { GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); } return extension->repeated_string_value->Add(); } // ------------------------------------------------------------------- // Messages const MessageLite& ExtensionSet::GetMessage( int number, const MessageLite& default_value) const { map::const_iterator iter = extensions_.find(number); if (iter == extensions_.end()) { // Not present. Return the default value. return default_value; } else { GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); if (iter->second.is_lazy) { return iter->second.lazymessage_value->GetMessage(default_value); } else { return *iter->second.message_value; } } } // Defined in extension_set_heavy.cc. // const MessageLite& ExtensionSet::GetMessage(int number, // const Descriptor* message_type, // MessageFactory* factory) const MessageLite* ExtensionSet::MutableMessage(int number, FieldType type, const MessageLite& prototype, const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_MESSAGE); extension->is_repeated = false; extension->is_lazy = false; extension->message_value = prototype.New(arena_); extension->is_cleared = false; return extension->message_value; } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); extension->is_cleared = false; if (extension->is_lazy) { return extension->lazymessage_value->MutableMessage(prototype); } else { return extension->message_value; } } } // Defined in extension_set_heavy.cc. // MessageLite* ExtensionSet::MutableMessage(int number, FieldType type, // const Descriptor* message_type, // MessageFactory* factory) void ExtensionSet::SetAllocatedMessage(int number, FieldType type, const FieldDescriptor* descriptor, MessageLite* message) { if (message == NULL) { ClearExtension(number); return; } Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_MESSAGE); extension->is_repeated = false; extension->is_lazy = false; if (message->GetArena() == arena_) { extension->message_value = message; } else { extension->message_value = message->New(arena_); extension->message_value->CheckTypeAndMergeFrom(*message); if (message->GetArena() == NULL) { delete message; } } } else { GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); if (extension->is_lazy) { extension->lazymessage_value->SetAllocatedMessage(message); } else { if (arena_ == NULL) { delete extension->message_value; } if (message->GetArena() == arena_) { extension->message_value = message; } else { extension->message_value = message->New(arena_); extension->message_value->CheckTypeAndMergeFrom(*message); if (message->GetArena() == NULL) { delete message; } } } } extension->is_cleared = false; } MessageLite* ExtensionSet::ReleaseMessage(int number, const MessageLite& prototype) { map::iterator iter = extensions_.find(number); if (iter == extensions_.end()) { // Not present. Return NULL. return NULL; } else { GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); MessageLite* ret = NULL; if (iter->second.is_lazy) { ret = iter->second.lazymessage_value->ReleaseMessage(prototype); if (arena_ == NULL) { delete iter->second.lazymessage_value; } } else { if (arena_ == NULL) { ret = iter->second.message_value; } else { // ReleaseMessage() always returns a heap-allocated message, and we are // on an arena, so we need to make a copy of this message to return. ret = (iter->second.message_value)->New(); ret->CheckTypeAndMergeFrom(*iter->second.message_value); } } extensions_.erase(number); return ret; } } MessageLite* ExtensionSet::UnsafeArenaReleaseMessage( int number, const MessageLite& prototype) { map::iterator iter = extensions_.find(number); if (iter == extensions_.end()) { // Not present. Return NULL. return NULL; } else { GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); MessageLite* ret = NULL; if (iter->second.is_lazy) { ret = iter->second.lazymessage_value->UnsafeArenaReleaseMessage(prototype); if (arena_ == NULL) { delete iter->second.lazymessage_value; } } else { ret = iter->second.message_value; } extensions_.erase(number); return ret; } } // Defined in extension_set_heavy.cc. // MessageLite* ExtensionSet::ReleaseMessage(const FieldDescriptor* descriptor, // MessageFactory* factory); const MessageLite& ExtensionSet::GetRepeatedMessage( int number, int index) const { map::const_iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE); return iter->second.repeated_message_value->Get(index); } MessageLite* ExtensionSet::MutableRepeatedMessage(int number, int index) { map::iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE); return iter->second.repeated_message_value->Mutable(index); } MessageLite* ExtensionSet::AddMessage(int number, FieldType type, const MessageLite& prototype, const FieldDescriptor* descriptor) { Extension* extension; if (MaybeNewExtension(number, descriptor, &extension)) { extension->type = type; GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_MESSAGE); extension->is_repeated = true; extension->repeated_message_value = Arena::Create >(arena_, arena_); } else { GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); } // RepeatedPtrField does not know how to Add() since it cannot // allocate an abstract object, so we have to be tricky. MessageLite* result = extension->repeated_message_value ->AddFromCleared >(); if (result == NULL) { result = prototype.New(arena_); extension->repeated_message_value->AddAllocated(result); } return result; } // Defined in extension_set_heavy.cc. // MessageLite* ExtensionSet::AddMessage(int number, FieldType type, // const Descriptor* message_type, // MessageFactory* factory) #undef GOOGLE_DCHECK_TYPE void ExtensionSet::RemoveLast(int number) { map::iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; Extension* extension = &iter->second; GOOGLE_DCHECK(extension->is_repeated); switch(cpp_type(extension->type)) { case WireFormatLite::CPPTYPE_INT32: extension->repeated_int32_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_INT64: extension->repeated_int64_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_UINT32: extension->repeated_uint32_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_UINT64: extension->repeated_uint64_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_FLOAT: extension->repeated_float_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_DOUBLE: extension->repeated_double_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_BOOL: extension->repeated_bool_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_ENUM: extension->repeated_enum_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_STRING: extension->repeated_string_value->RemoveLast(); break; case WireFormatLite::CPPTYPE_MESSAGE: extension->repeated_message_value->RemoveLast(); break; } } MessageLite* ExtensionSet::ReleaseLast(int number) { map::iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; Extension* extension = &iter->second; GOOGLE_DCHECK(extension->is_repeated); GOOGLE_DCHECK(cpp_type(extension->type) == WireFormatLite::CPPTYPE_MESSAGE); return extension->repeated_message_value->ReleaseLast(); } void ExtensionSet::SwapElements(int number, int index1, int index2) { map::iterator iter = extensions_.find(number); GOOGLE_CHECK(iter != extensions_.end()) << ""Index out-of-bounds (field is empty).""; Extension* extension = &iter->second; GOOGLE_DCHECK(extension->is_repeated); switch(cpp_type(extension->type)) { case WireFormatLite::CPPTYPE_INT32: extension->repeated_int32_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_INT64: extension->repeated_int64_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_UINT32: extension->repeated_uint32_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_UINT64: extension->repeated_uint64_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_FLOAT: extension->repeated_float_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_DOUBLE: extension->repeated_double_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_BOOL: extension->repeated_bool_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_ENUM: extension->repeated_enum_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_STRING: extension->repeated_string_value->SwapElements(index1, index2); break; case WireFormatLite::CPPTYPE_MESSAGE: extension->repeated_message_value->SwapElements(index1, index2); break; } } // =================================================================== void ExtensionSet::Clear() { for (map::iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { iter->second.Clear(); } } void ExtensionSet::MergeFrom(const ExtensionSet& other) { for (map::const_iterator iter = other.extensions_.begin(); iter != other.extensions_.end(); ++iter) { const Extension& other_extension = iter->second; InternalExtensionMergeFrom(iter->first, other_extension); } } void ExtensionSet::InternalExtensionMergeFrom( int number, const Extension& other_extension) { if (other_extension.is_repeated) { Extension* extension; bool is_new = MaybeNewExtension(number, other_extension.descriptor, &extension); if (is_new) { // Extension did not already exist in set. extension->type = other_extension.type; extension->is_packed = other_extension.is_packed; extension->is_repeated = true; } else { GOOGLE_DCHECK_EQ(extension->type, other_extension.type); GOOGLE_DCHECK_EQ(extension->is_packed, other_extension.is_packed); GOOGLE_DCHECK(extension->is_repeated); } switch (cpp_type(other_extension.type)) { #define HANDLE_TYPE(UPPERCASE, LOWERCASE, REPEATED_TYPE) \\ case WireFormatLite::CPPTYPE_##UPPERCASE: \\ if (is_new) { \\ extension->repeated_##LOWERCASE##_value = \\ Arena::Create(arena_, arena_); \\ } \\ extension->repeated_##LOWERCASE##_value->MergeFrom( \\ *other_extension.repeated_##LOWERCASE##_value); \\ break; HANDLE_TYPE( INT32, int32, RepeatedField < int32>); HANDLE_TYPE( INT64, int64, RepeatedField < int64>); HANDLE_TYPE( UINT32, uint32, RepeatedField < uint32>); HANDLE_TYPE( UINT64, uint64, RepeatedField < uint64>); HANDLE_TYPE( FLOAT, float, RepeatedField < float>); HANDLE_TYPE( DOUBLE, double, RepeatedField < double>); HANDLE_TYPE( BOOL, bool, RepeatedField < bool>); HANDLE_TYPE( ENUM, enum, RepeatedField < int>); HANDLE_TYPE( STRING, string, RepeatedPtrField< string>); #undef HANDLE_TYPE case WireFormatLite::CPPTYPE_MESSAGE: if (is_new) { extension->repeated_message_value = Arena::Create >(arena_, arena_); } // We can't call RepeatedPtrField::MergeFrom() because // it would attempt to allocate new objects. RepeatedPtrField* other_repeated_message = other_extension.repeated_message_value; for (int i = 0; i < other_repeated_message->size(); i++) { const MessageLite& other_message = other_repeated_message->Get(i); MessageLite* target = extension->repeated_message_value ->AddFromCleared >(); if (target == NULL) { target = other_message.New(arena_); extension->repeated_message_value->AddAllocated(target); } target->CheckTypeAndMergeFrom(other_message); } break; } } else { if (!other_extension.is_cleared) { switch (cpp_type(other_extension.type)) { #define HANDLE_TYPE(UPPERCASE, LOWERCASE, CAMELCASE) \\ case WireFormatLite::CPPTYPE_##UPPERCASE: \\ Set##CAMELCASE(number, other_extension.type, \\ other_extension.LOWERCASE##_value, \\ other_extension.descriptor); \\ break; HANDLE_TYPE( INT32, int32, Int32); HANDLE_TYPE( INT64, int64, Int64); HANDLE_TYPE(UINT32, uint32, UInt32); HANDLE_TYPE(UINT64, uint64, UInt64); HANDLE_TYPE( FLOAT, float, Float); HANDLE_TYPE(DOUBLE, double, Double); HANDLE_TYPE( BOOL, bool, Bool); HANDLE_TYPE( ENUM, enum, Enum); #undef HANDLE_TYPE case WireFormatLite::CPPTYPE_STRING: SetString(number, other_extension.type, *other_extension.string_value, other_extension.descriptor); break; case WireFormatLite::CPPTYPE_MESSAGE: { Extension* extension; bool is_new = MaybeNewExtension(number, other_extension.descriptor, &extension); if (is_new) { extension->type = other_extension.type; extension->is_packed = other_extension.is_packed; extension->is_repeated = false; if (other_extension.is_lazy) { extension->is_lazy = true; extension->lazymessage_value = other_extension.lazymessage_value->New(arena_); extension->lazymessage_value->MergeFrom( *other_extension.lazymessage_value); } else { extension->is_lazy = false; extension->message_value = other_extension.message_value->New(arena_); extension->message_value->CheckTypeAndMergeFrom( *other_extension.message_value); } } else { GOOGLE_DCHECK_EQ(extension->type, other_extension.type); GOOGLE_DCHECK_EQ(extension->is_packed,other_extension.is_packed); GOOGLE_DCHECK(!extension->is_repeated); if (other_extension.is_lazy) { if (extension->is_lazy) { extension->lazymessage_value->MergeFrom( *other_extension.lazymessage_value); } else { extension->message_value->CheckTypeAndMergeFrom( other_extension.lazymessage_value->GetMessage( *extension->message_value)); } } else { if (extension->is_lazy) { extension->lazymessage_value->MutableMessage( *other_extension.message_value)->CheckTypeAndMergeFrom( *other_extension.message_value); } else { extension->message_value->CheckTypeAndMergeFrom( *other_extension.message_value); } } } extension->is_cleared = false; break; } } } } } void ExtensionSet::Swap(ExtensionSet* x) { if (GetArenaNoVirtual() == x->GetArenaNoVirtual()) { extensions_.swap(x->extensions_); } else { // TODO(cfallin, rohananil): We maybe able to optimize a case where we are // swapping from heap to arena-allocated extension set, by just Own()'ing // the extensions. ExtensionSet extension_set; extension_set.MergeFrom(*x); x->Clear(); x->MergeFrom(*this); Clear(); MergeFrom(extension_set); } } void ExtensionSet::SwapExtension(ExtensionSet* other, int number) { if (this == other) return; map::iterator this_iter = extensions_.find(number); map::iterator other_iter = other->extensions_.find(number); if (this_iter == extensions_.end() && other_iter == other->extensions_.end()) { return; } if (this_iter != extensions_.end() && other_iter != other->extensions_.end()) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { using std::swap; swap(this_iter->second, other_iter->second); } else { // TODO(cfallin, rohananil): We could further optimize these cases, // especially avoid creation of ExtensionSet, and move MergeFrom logic // into Extensions itself (which takes arena as an argument). // We do it this way to reuse the copy-across-arenas logic already // implemented in ExtensionSet's MergeFrom. ExtensionSet temp; temp.InternalExtensionMergeFrom(number, other_iter->second); map::iterator temp_iter = temp.extensions_.find(number); other_iter->second.Clear(); other->InternalExtensionMergeFrom(number, this_iter->second); this_iter->second.Clear(); InternalExtensionMergeFrom(number, temp_iter->second); } return; } if (this_iter == extensions_.end()) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { extensions_.insert(std::make_pair(number, other_iter->second)); } else { InternalExtensionMergeFrom(number, other_iter->second); } other->extensions_.erase(number); return; } if (other_iter == other->extensions_.end()) { if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { other->extensions_.insert(std::make_pair(number, this_iter->second)); } else { other->InternalExtensionMergeFrom(number, this_iter->second); } extensions_.erase(number); return; } } bool ExtensionSet::IsInitialized() const { // Extensions are never required. However, we need to check that all // embedded messages are initialized. for (map::const_iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { const Extension& extension = iter->second; if (cpp_type(extension.type) == WireFormatLite::CPPTYPE_MESSAGE) { if (extension.is_repeated) { for (int i = 0; i < extension.repeated_message_value->size(); i++) { if (!extension.repeated_message_value->Get(i).IsInitialized()) { return false; } } } else { if (!extension.is_cleared) { if (extension.is_lazy) { if (!extension.lazymessage_value->IsInitialized()) return false; } else { if (!extension.message_value->IsInitialized()) return false; } } } } } return true; } bool ExtensionSet::FindExtensionInfoFromTag( uint32 tag, ExtensionFinder* extension_finder, int* field_number, ExtensionInfo* extension, bool* was_packed_on_wire) { *field_number = WireFormatLite::GetTagFieldNumber(tag); WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag); return FindExtensionInfoFromFieldNumber(wire_type, *field_number, extension_finder, extension, was_packed_on_wire); } bool ExtensionSet::FindExtensionInfoFromFieldNumber( int wire_type, int field_number, ExtensionFinder* extension_finder, ExtensionInfo* extension, bool* was_packed_on_wire) { if (!extension_finder->Find(field_number, extension)) { return false; } WireFormatLite::WireType expected_wire_type = WireFormatLite::WireTypeForFieldType(real_type(extension->type)); // Check if this is a packed field. *was_packed_on_wire = false; if (extension->is_repeated && wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED && is_packable(expected_wire_type)) { *was_packed_on_wire = true; return true; } // Otherwise the wire type must match. return expected_wire_type == wire_type; } bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, ExtensionFinder* extension_finder, FieldSkipper* field_skipper) { int number; bool was_packed_on_wire; ExtensionInfo extension; if (!FindExtensionInfoFromTag( tag, extension_finder, &number, &extension, &was_packed_on_wire)) { return field_skipper->SkipField(input, tag); } else { return ParseFieldWithExtensionInfo( number, was_packed_on_wire, extension, input, field_skipper); } } bool ExtensionSet::ParseFieldWithExtensionInfo( int number, bool was_packed_on_wire, const ExtensionInfo& extension, io::CodedInputStream* input, FieldSkipper* field_skipper) { // Explicitly not read extension.is_packed, instead check whether the field // was encoded in packed form on the wire. if (was_packed_on_wire) { uint32 size; if (!input->ReadVarint32(&size)) return false; io::CodedInputStream::Limit limit = input->PushLimit(size); switch (extension.type) { #define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE, CPP_LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ while (input->BytesUntilLimit() > 0) { \\ CPP_LOWERCASE value; \\ if (!WireFormatLite::ReadPrimitive< \\ CPP_LOWERCASE, WireFormatLite::TYPE_##UPPERCASE>( \\ input, &value)) return false; \\ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \\ extension.is_packed, value, \\ extension.descriptor); \\ } \\ break HANDLE_TYPE( INT32, Int32, int32); HANDLE_TYPE( INT64, Int64, int64); HANDLE_TYPE( UINT32, UInt32, uint32); HANDLE_TYPE( UINT64, UInt64, uint64); HANDLE_TYPE( SINT32, Int32, int32); HANDLE_TYPE( SINT64, Int64, int64); HANDLE_TYPE( FIXED32, UInt32, uint32); HANDLE_TYPE( FIXED64, UInt64, uint64); HANDLE_TYPE(SFIXED32, Int32, int32); HANDLE_TYPE(SFIXED64, Int64, int64); HANDLE_TYPE( FLOAT, Float, float); HANDLE_TYPE( DOUBLE, Double, double); HANDLE_TYPE( BOOL, Bool, bool); #undef HANDLE_TYPE case WireFormatLite::TYPE_ENUM: while (input->BytesUntilLimit() > 0) { int value; if (!WireFormatLite::ReadPrimitive( input, &value)) return false; if (extension.enum_validity_check.func( extension.enum_validity_check.arg, value)) { AddEnum(number, WireFormatLite::TYPE_ENUM, extension.is_packed, value, extension.descriptor); } else { // Invalid value. Treat as unknown. field_skipper->SkipUnknownEnum(number, value); } } break; case WireFormatLite::TYPE_STRING: case WireFormatLite::TYPE_BYTES: case WireFormatLite::TYPE_GROUP: case WireFormatLite::TYPE_MESSAGE: GOOGLE_LOG(FATAL) << ""Non-primitive types can't be packed.""; break; } input->PopLimit(limit); } else { switch (extension.type) { #define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE, CPP_LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: { \\ CPP_LOWERCASE value; \\ if (!WireFormatLite::ReadPrimitive< \\ CPP_LOWERCASE, WireFormatLite::TYPE_##UPPERCASE>( \\ input, &value)) return false; \\ if (extension.is_repeated) { \\ Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \\ extension.is_packed, value, \\ extension.descriptor); \\ } else { \\ Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \\ extension.descriptor); \\ } \\ } break HANDLE_TYPE( INT32, Int32, int32); HANDLE_TYPE( INT64, Int64, int64); HANDLE_TYPE( UINT32, UInt32, uint32); HANDLE_TYPE( UINT64, UInt64, uint64); HANDLE_TYPE( SINT32, Int32, int32); HANDLE_TYPE( SINT64, Int64, int64); HANDLE_TYPE( FIXED32, UInt32, uint32); HANDLE_TYPE( FIXED64, UInt64, uint64); HANDLE_TYPE(SFIXED32, Int32, int32); HANDLE_TYPE(SFIXED64, Int64, int64); HANDLE_TYPE( FLOAT, Float, float); HANDLE_TYPE( DOUBLE, Double, double); HANDLE_TYPE( BOOL, Bool, bool); #undef HANDLE_TYPE case WireFormatLite::TYPE_ENUM: { int value; if (!WireFormatLite::ReadPrimitive( input, &value)) return false; if (!extension.enum_validity_check.func( extension.enum_validity_check.arg, value)) { // Invalid value. Treat as unknown. field_skipper->SkipUnknownEnum(number, value); } else if (extension.is_repeated) { AddEnum(number, WireFormatLite::TYPE_ENUM, extension.is_packed, value, extension.descriptor); } else { SetEnum(number, WireFormatLite::TYPE_ENUM, value, extension.descriptor); } break; } case WireFormatLite::TYPE_STRING: { string* value = extension.is_repeated ? AddString(number, WireFormatLite::TYPE_STRING, extension.descriptor) : MutableString(number, WireFormatLite::TYPE_STRING, extension.descriptor); if (!WireFormatLite::ReadString(input, value)) return false; break; } case WireFormatLite::TYPE_BYTES: { string* value = extension.is_repeated ? AddString(number, WireFormatLite::TYPE_BYTES, extension.descriptor) : MutableString(number, WireFormatLite::TYPE_BYTES, extension.descriptor); if (!WireFormatLite::ReadBytes(input, value)) return false; break; } case WireFormatLite::TYPE_GROUP: { MessageLite* value = extension.is_repeated ? AddMessage(number, WireFormatLite::TYPE_GROUP, *extension.message_prototype, extension.descriptor) : MutableMessage(number, WireFormatLite::TYPE_GROUP, *extension.message_prototype, extension.descriptor); if (!WireFormatLite::ReadGroup(number, input, value)) return false; break; } case WireFormatLite::TYPE_MESSAGE: { MessageLite* value = extension.is_repeated ? AddMessage(number, WireFormatLite::TYPE_MESSAGE, *extension.message_prototype, extension.descriptor) : MutableMessage(number, WireFormatLite::TYPE_MESSAGE, *extension.message_prototype, extension.descriptor); if (!WireFormatLite::ReadMessage(input, value)) return false; break; } } } return true; } bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, const MessageLite* containing_type) { FieldSkipper skipper; GeneratedExtensionFinder finder(containing_type); return ParseField(tag, input, &finder, &skipper); } bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, const MessageLite* containing_type, io::CodedOutputStream* unknown_fields) { CodedOutputStreamFieldSkipper skipper(unknown_fields); GeneratedExtensionFinder finder(containing_type); return ParseField(tag, input, &finder, &skipper); } // Defined in extension_set_heavy.cc. // bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, // const MessageLite* containing_type, // UnknownFieldSet* unknown_fields) // Defined in extension_set_heavy.cc. // bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, // const MessageLite* containing_type, // UnknownFieldSet* unknown_fields); void ExtensionSet::SerializeWithCachedSizes( int start_field_number, int end_field_number, io::CodedOutputStream* output) const { map::const_iterator iter; for (iter = extensions_.lower_bound(start_field_number); iter != extensions_.end() && iter->first < end_field_number; ++iter) { iter->second.SerializeFieldWithCachedSizes(iter->first, output); } } int ExtensionSet::ByteSize() const { int total_size = 0; for (map::const_iterator iter = extensions_.begin(); iter != extensions_.end(); ++iter) { total_size += iter->second.ByteSize(iter->first); } return total_size; } // Defined in extension_set_heavy.cc. // int ExtensionSet::SpaceUsedExcludingSelf() const bool ExtensionSet::MaybeNewExtension(int number, const FieldDescriptor* descriptor, Extension** result) { pair::iterator, bool> insert_result = extensions_.insert(std::make_pair(number, Extension())); *result = &insert_result.first->second; (*result)->descriptor = descriptor; return insert_result.second; } // =================================================================== // Methods of ExtensionSet::Extension void ExtensionSet::Extension::Clear() { if (is_repeated) { switch (cpp_type(type)) { #define HANDLE_TYPE(UPPERCASE, LOWERCASE) \\ case WireFormatLite::CPPTYPE_##UPPERCASE: \\ repeated_##LOWERCASE##_value->Clear(); \\ break HANDLE_TYPE( INT32, int32); HANDLE_TYPE( INT64, int64); HANDLE_TYPE( UINT32, uint32); HANDLE_TYPE( UINT64, uint64); HANDLE_TYPE( FLOAT, float); HANDLE_TYPE( DOUBLE, double); HANDLE_TYPE( BOOL, bool); HANDLE_TYPE( ENUM, enum); HANDLE_TYPE( STRING, string); HANDLE_TYPE(MESSAGE, message); #undef HANDLE_TYPE } } else { if (!is_cleared) { switch (cpp_type(type)) { case WireFormatLite::CPPTYPE_STRING: string_value->clear(); break; case WireFormatLite::CPPTYPE_MESSAGE: if (is_lazy) { lazymessage_value->Clear(); } else { message_value->Clear(); } break; default: // No need to do anything. Get*() will return the default value // as long as is_cleared is true and Set*() will overwrite the // previous value. break; } is_cleared = true; } } } void ExtensionSet::Extension::SerializeFieldWithCachedSizes( int number, io::CodedOutputStream* output) const { if (is_repeated) { if (is_packed) { if (cached_size == 0) return; WireFormatLite::WriteTag(number, WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(cached_size); switch (real_type(type)) { #define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \\ WireFormatLite::Write##CAMELCASE##NoTag( \\ repeated_##LOWERCASE##_value->Get(i), output); \\ } \\ break HANDLE_TYPE( INT32, Int32, int32); HANDLE_TYPE( INT64, Int64, int64); HANDLE_TYPE( UINT32, UInt32, uint32); HANDLE_TYPE( UINT64, UInt64, uint64); HANDLE_TYPE( SINT32, SInt32, int32); HANDLE_TYPE( SINT64, SInt64, int64); HANDLE_TYPE( FIXED32, Fixed32, uint32); HANDLE_TYPE( FIXED64, Fixed64, uint64); HANDLE_TYPE(SFIXED32, SFixed32, int32); HANDLE_TYPE(SFIXED64, SFixed64, int64); HANDLE_TYPE( FLOAT, Float, float); HANDLE_TYPE( DOUBLE, Double, double); HANDLE_TYPE( BOOL, Bool, bool); HANDLE_TYPE( ENUM, Enum, enum); #undef HANDLE_TYPE case WireFormatLite::TYPE_STRING: case WireFormatLite::TYPE_BYTES: case WireFormatLite::TYPE_GROUP: case WireFormatLite::TYPE_MESSAGE: GOOGLE_LOG(FATAL) << ""Non-primitive types can't be packed.""; break; } } else { switch (real_type(type)) { #define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \\ WireFormatLite::Write##CAMELCASE(number, \\ repeated_##LOWERCASE##_value->Get(i), output); \\ } \\ break HANDLE_TYPE( INT32, Int32, int32); HANDLE_TYPE( INT64, Int64, int64); HANDLE_TYPE( UINT32, UInt32, uint32); HANDLE_TYPE( UINT64, UInt64, uint64); HANDLE_TYPE( SINT32, SInt32, int32); HANDLE_TYPE( SINT64, SInt64, int64); HANDLE_TYPE( FIXED32, Fixed32, uint32); HANDLE_TYPE( FIXED64, Fixed64, uint64); HANDLE_TYPE(SFIXED32, SFixed32, int32); HANDLE_TYPE(SFIXED64, SFixed64, int64); HANDLE_TYPE( FLOAT, Float, float); HANDLE_TYPE( DOUBLE, Double, double); HANDLE_TYPE( BOOL, Bool, bool); HANDLE_TYPE( STRING, String, string); HANDLE_TYPE( BYTES, Bytes, string); HANDLE_TYPE( ENUM, Enum, enum); HANDLE_TYPE( GROUP, Group, message); HANDLE_TYPE( MESSAGE, Message, message); #undef HANDLE_TYPE } } } else if (!is_cleared) { switch (real_type(type)) { #define HANDLE_TYPE(UPPERCASE, CAMELCASE, VALUE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ WireFormatLite::Write##CAMELCASE(number, VALUE, output); \\ break HANDLE_TYPE( INT32, Int32, int32_value); HANDLE_TYPE( INT64, Int64, int64_value); HANDLE_TYPE( UINT32, UInt32, uint32_value); HANDLE_TYPE( UINT64, UInt64, uint64_value); HANDLE_TYPE( SINT32, SInt32, int32_value); HANDLE_TYPE( SINT64, SInt64, int64_value); HANDLE_TYPE( FIXED32, Fixed32, uint32_value); HANDLE_TYPE( FIXED64, Fixed64, uint64_value); HANDLE_TYPE(SFIXED32, SFixed32, int32_value); HANDLE_TYPE(SFIXED64, SFixed64, int64_value); HANDLE_TYPE( FLOAT, Float, float_value); HANDLE_TYPE( DOUBLE, Double, double_value); HANDLE_TYPE( BOOL, Bool, bool_value); HANDLE_TYPE( STRING, String, *string_value); HANDLE_TYPE( BYTES, Bytes, *string_value); HANDLE_TYPE( ENUM, Enum, enum_value); HANDLE_TYPE( GROUP, Group, *message_value); #undef HANDLE_TYPE case WireFormatLite::TYPE_MESSAGE: if (is_lazy) { lazymessage_value->WriteMessage(number, output); } else { WireFormatLite::WriteMessage(number, *message_value, output); } break; } } } int ExtensionSet::Extension::ByteSize(int number) const { int result = 0; if (is_repeated) { if (is_packed) { switch (real_type(type)) { #define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \\ result += WireFormatLite::CAMELCASE##Size( \\ repeated_##LOWERCASE##_value->Get(i)); \\ } \\ break HANDLE_TYPE( INT32, Int32, int32); HANDLE_TYPE( INT64, Int64, int64); HANDLE_TYPE( UINT32, UInt32, uint32); HANDLE_TYPE( UINT64, UInt64, uint64); HANDLE_TYPE( SINT32, SInt32, int32); HANDLE_TYPE( SINT64, SInt64, int64); HANDLE_TYPE( ENUM, Enum, enum); #undef HANDLE_TYPE // Stuff with fixed size. #define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ result += WireFormatLite::k##CAMELCASE##Size * \\ repeated_##LOWERCASE##_value->size(); \\ break HANDLE_TYPE( FIXED32, Fixed32, uint32); HANDLE_TYPE( FIXED64, Fixed64, uint64); HANDLE_TYPE(SFIXED32, SFixed32, int32); HANDLE_TYPE(SFIXED64, SFixed64, int64); HANDLE_TYPE( FLOAT, Float, float); HANDLE_TYPE( DOUBLE, Double, double); HANDLE_TYPE( BOOL, Bool, bool); #undef HANDLE_TYPE case WireFormatLite::TYPE_STRING: case WireFormatLite::TYPE_BYTES: case WireFormatLite::TYPE_GROUP: case WireFormatLite::TYPE_MESSAGE: GOOGLE_LOG(FATAL) << ""Non-primitive types can't be packed.""; break; } cached_size = result; if (result > 0) { result += io::CodedOutputStream::VarintSize32(result); result += io::CodedOutputStream::VarintSize32( WireFormatLite::MakeTag(number, WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); } } else { int tag_size = WireFormatLite::TagSize(number, real_type(type)); switch (real_type(type)) { #define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ result += tag_size * repeated_##LOWERCASE##_value->size(); \\ for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \\ result += WireFormatLite::CAMELCASE##Size( \\ repeated_##LOWERCASE##_value->Get(i)); \\ } \\ break HANDLE_TYPE( INT32, Int32, int32); HANDLE_TYPE( INT64, Int64, int64); HANDLE_TYPE( UINT32, UInt32, uint32); HANDLE_TYPE( UINT64, UInt64, uint64); HANDLE_TYPE( SINT32, SInt32, int32); HANDLE_TYPE( SINT64, SInt64, int64); HANDLE_TYPE( STRING, String, string); HANDLE_TYPE( BYTES, Bytes, string); HANDLE_TYPE( ENUM, Enum, enum); HANDLE_TYPE( GROUP, Group, message); HANDLE_TYPE( MESSAGE, Message, message); #undef HANDLE_TYPE // Stuff with fixed size. #define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ result += (tag_size + WireFormatLite::k##CAMELCASE##Size) * \\ repeated_##LOWERCASE##_value->size(); \\ break HANDLE_TYPE( FIXED32, Fixed32, uint32); HANDLE_TYPE( FIXED64, Fixed64, uint64); HANDLE_TYPE(SFIXED32, SFixed32, int32); HANDLE_TYPE(SFIXED64, SFixed64, int64); HANDLE_TYPE( FLOAT, Float, float); HANDLE_TYPE( DOUBLE, Double, double); HANDLE_TYPE( BOOL, Bool, bool); #undef HANDLE_TYPE } } } else if (!is_cleared) { result += WireFormatLite::TagSize(number, real_type(type)); switch (real_type(type)) { #define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ result += WireFormatLite::CAMELCASE##Size(LOWERCASE); \\ break HANDLE_TYPE( INT32, Int32, int32_value); HANDLE_TYPE( INT64, Int64, int64_value); HANDLE_TYPE( UINT32, UInt32, uint32_value); HANDLE_TYPE( UINT64, UInt64, uint64_value); HANDLE_TYPE( SINT32, SInt32, int32_value); HANDLE_TYPE( SINT64, SInt64, int64_value); HANDLE_TYPE( STRING, String, *string_value); HANDLE_TYPE( BYTES, Bytes, *string_value); HANDLE_TYPE( ENUM, Enum, enum_value); HANDLE_TYPE( GROUP, Group, *message_value); #undef HANDLE_TYPE case WireFormatLite::TYPE_MESSAGE: { if (is_lazy) { int size = lazymessage_value->ByteSize(); result += io::CodedOutputStream::VarintSize32(size) + size; } else { result += WireFormatLite::MessageSize(*message_value); } break; } // Stuff with fixed size. #define HANDLE_TYPE(UPPERCASE, CAMELCASE) \\ case WireFormatLite::TYPE_##UPPERCASE: \\ result += WireFormatLite::k##CAMELCASE##Size; \\ break HANDLE_TYPE( FIXED32, Fixed32); HANDLE_TYPE( FIXED64, Fixed64); HANDLE_TYPE(SFIXED32, SFixed32); HANDLE_TYPE(SFIXED64, SFixed64); HANDLE_TYPE( FLOAT, Float); HANDLE_TYPE( DOUBLE, Double); HANDLE_TYPE( BOOL, Bool); #undef HANDLE_TYPE } } return result; } int ExtensionSet::Extension::GetSize() const { GOOGLE_DCHECK(is_repeated); switch (cpp_type(type)) { #define HANDLE_TYPE(UPPERCASE, LOWERCASE) \\ case WireFormatLite::CPPTYPE_##UPPERCASE: \\ return repeated_##LOWERCASE##_value->size() HANDLE_TYPE( INT32, int32); HANDLE_TYPE( INT64, int64); HANDLE_TYPE( UINT32, uint32); HANDLE_TYPE( UINT64, uint64); HANDLE_TYPE( FLOAT, float); HANDLE_TYPE( DOUBLE, double); HANDLE_TYPE( BOOL, bool); HANDLE_TYPE( ENUM, enum); HANDLE_TYPE( STRING, string); HANDLE_TYPE(MESSAGE, message); #undef HANDLE_TYPE } GOOGLE_LOG(FATAL) << ""Can't get here.""; return 0; } // This function deletes all allocated objects. This function should be only // called if the Extension was created with an arena. void ExtensionSet::Extension::Free() { if (is_repeated) { switch (cpp_type(type)) { #define HANDLE_TYPE(UPPERCASE, LOWERCASE) \\ case WireFormatLite::CPPTYPE_##UPPERCASE: \\ delete repeated_##LOWERCASE##_value; \\ break HANDLE_TYPE( INT32, int32); HANDLE_TYPE( INT64, int64); HANDLE_TYPE( UINT32, uint32); HANDLE_TYPE( UINT64, uint64); HANDLE_TYPE( FLOAT, float); HANDLE_TYPE( DOUBLE, double); HANDLE_TYPE( BOOL, bool); HANDLE_TYPE( ENUM, enum); HANDLE_TYPE( STRING, string); HANDLE_TYPE(MESSAGE, message); #undef HANDLE_TYPE } } else { switch (cpp_type(type)) { case WireFormatLite::CPPTYPE_STRING: delete string_value; break; case WireFormatLite::CPPTYPE_MESSAGE: if (is_lazy) { delete lazymessage_value; } else { delete message_value; } break; default: break; } } } // Defined in extension_set_heavy.cc. // int ExtensionSet::Extension::SpaceUsedExcludingSelf() const // ================================================================== // Default repeated field instances for iterator-compatible accessors const RepeatedStringTypeTraits::RepeatedFieldType* RepeatedStringTypeTraits::default_repeated_field_ = NULL; const RepeatedMessageGenericTypeTraits::RepeatedFieldType* RepeatedMessageGenericTypeTraits::default_repeated_field_ = NULL; #define PROTOBUF_DEFINE_DEFAULT_REPEATED(TYPE) \\ const RepeatedField* \\ RepeatedPrimitiveGenericTypeTraits::default_repeated_field_##TYPE##_ = NULL; PROTOBUF_DEFINE_DEFAULT_REPEATED(int32) PROTOBUF_DEFINE_DEFAULT_REPEATED(int64) PROTOBUF_DEFINE_DEFAULT_REPEATED(uint32) PROTOBUF_DEFINE_DEFAULT_REPEATED(uint64) PROTOBUF_DEFINE_DEFAULT_REPEATED(double) PROTOBUF_DEFINE_DEFAULT_REPEATED(float) PROTOBUF_DEFINE_DEFAULT_REPEATED(bool) #undef PROTOBUF_DEFINE_DEFAULT_REPEATED struct StaticDefaultRepeatedFieldsInitializer { StaticDefaultRepeatedFieldsInitializer() { InitializeDefaultRepeatedFields(); OnShutdown(&DestroyDefaultRepeatedFields); } } static_repeated_fields_initializer; void InitializeDefaultRepeatedFields() { RepeatedStringTypeTraits::default_repeated_field_ = new RepeatedStringTypeTraits::RepeatedFieldType; RepeatedMessageGenericTypeTraits::default_repeated_field_ = new RepeatedMessageGenericTypeTraits::RepeatedFieldType; RepeatedPrimitiveGenericTypeTraits::default_repeated_field_int32_ = new RepeatedField; RepeatedPrimitiveGenericTypeTraits::default_repeated_field_int64_ = new RepeatedField; RepeatedPrimitiveGenericTypeTraits::default_repeated_field_uint32_ = new RepeatedField; RepeatedPrimitiveGenericTypeTraits::default_repeated_field_uint64_ = new RepeatedField; RepeatedPrimitiveGenericTypeTraits::default_repeated_field_double_ = new RepeatedField; RepeatedPrimitiveGenericTypeTraits::default_repeated_field_float_ = new RepeatedField; RepeatedPrimitiveGenericTypeTraits::default_repeated_field_bool_ = new RepeatedField; } void DestroyDefaultRepeatedFields() { delete RepeatedStringTypeTraits::default_repeated_field_; delete RepeatedMessageGenericTypeTraits::default_repeated_field_; delete RepeatedPrimitiveGenericTypeTraits::default_repeated_field_int32_; delete RepeatedPrimitiveGenericTypeTraits::default_repeated_field_int64_; delete RepeatedPrimitiveGenericTypeTraits::default_repeated_field_uint32_; delete RepeatedPrimitiveGenericTypeTraits::default_repeated_field_uint64_; delete RepeatedPrimitiveGenericTypeTraits::default_repeated_field_double_; delete RepeatedPrimitiveGenericTypeTraits::default_repeated_field_float_; delete RepeatedPrimitiveGenericTypeTraits::default_repeated_field_bool_; } } // namespace internal } // namespace protobuf } // namespace google ",16350,True,3357.8628674959928,median "= EDGE2AI Workshop == Introduction The Cloudera Self Driving Vehicle (CSDV) is a miniature autonomous car which is trained to follow markers along a race track, the team achieved this by rapidly sampling photographs and using them to run inference to adjust the steering angle of the vehicle. ===== Labs summary: * *Lab 1* - On the Gateway host, run a simulator to send IoT sensors data to the MQTT broker. * *Lab 2* - On the Gateway host, configure and start **MiNiFi**, which will read from the MQTT broker, filter and forward to the **NiFi** cluster. * *Lab 3* - Create the MiNiFi flow on the Edge Flow Manager and publish it for the MiNiFi agent to start sending data to the NiFi cluster. * *Lab 4* - On Schema Registry, register the schema describing the data generated by the IoT sensors. * *Lab 5* - On the NiFi cluster, prepare the data and send it to the **Kafka** cluster. * *Lab 6* - On the *Streams Messaging Manager (SMM)* Web UI, monitor the Kafka cluster and confirm data is being ingested correctly. * *Lab 7* - Use the Edge Flow Manager to update existing edge flows and perform additional processing on the edge * *Lab 8* - Use NiFi to process each record, calling the **Model endpoint** and save results to **Kudu**. * *Lab 9* - On the CDH cluster, process each record using **Spark Streaming**, calling the **Model endpoint** and save results to **Kudu**. * *Lab 10* - On the CDH cluster, pull reports on upcoming predicted machine failures using **Impala** and **Hue**. * *Lab 11* - On the **CDSW** cluster, train your model with the **Experiment** feature. * *Lab 12* - On the **CDSW** cluster, deploy the model into production with the **Model** feature. ===== Pre-requisites * Laptop with a supported OS (Windows 7 not supported). * Ability to SSH into remote hosts from Windows or Mac. For Windows machines, install Putty or even better link:https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse[install OpenSSH for PowerShell]. * A modern browser like Google Chrome (IE not supported). ===== Connecting to your cluster You should have 2 addresses for you one-node cluster: the public DNS name and the public IP address. With those addresses you can test the following connectivity to your cluster: . It is convenient to export the DNS, IP, and path to the PEM of your cluster for future use: + [source, shell] ---- export WDNS= export WIP= export WPEM= ---- . Ensure you can SSH into the cluster (using either the DNS name or IP address) + [source,shell] ---- ssh -i $WPEM centos@$WDNS ---- . Ensure you can connect to the following service using your browser: + [%autowidth,options=""header""] |=== |Service|URL|Credentials |Cloudera Manager|http://:7180/|`admin/admin` |Edge Flow Manager|http://:10080/efm/ui/| |NiFi|http://:8080/nifi/| |NiFi Registry|http://:18080/nifi-registry/| |Schema Registry|http://:7788/| |SMM|http://:9991/| |Hue|http://:8888/| |CDSW|http://cdsw..nip.io/|`admin/supersecret1` |=== . Login into *Cloudera Manager* and familiarize yourself with the services installed . Login into *Hue*. As you are the first user to login into Hue, you are granted admin privileges. At this point, you won't need to do anything on Hue, but by logging in, CDH has created your HDFS user and folder. Below a screenshot of Chrome open with 8 tabs, one for each service. image::images/browser.png[width=800] [[lab_1, Lab 1]] == Lab 1 - Configure and run MiNiFi MiNiFi is installed on the host. In this lab you will configure and run MiNiFi to read from the MQTT broker and forward to the NiFi cluster, but it's only in the next lab that you will provide the flow to execute. . Sudo to the root user + [source,shell] ---- sudo su - ---- . Start the MiNiFi agent: + [source,shell] ---- systemctl start minifi ---- . Exit the root session + [source,shell] ---- exit ---- [[lab_2, Lab2]] == Lab 2 - Configuring the NiFi Flow In order to connect MiNiFi to NiFi we need to know where we are going so let's create a path for our data to slowly build a flow. Open NiFi UI on your CDF cluster and create a new input source named `AWS_MiNiFi_CSV` leave it alone for now, we will need the input id to set our connection from MiNiFi processor to NiFi Remote Process Group (RPG) [[lab_3, Lab3]] == Lab 3 - Configuring Edge Flow Management Cloudera Edge Flow Management gives you a visual overview of all MiNiFi agents in your environment, and allows you to update the flow configuration for each one, with versioning control thanks to the **NiFi Registry** integration. In this lab, you will create the MiNiFi flow and publish it for the MiNiFi agent to pick it up. . Open the EFM Web UI at http://:10080/efm/ui/. Ensure you see your minifi agent's heartbeat messages in the **Events Monitor**. + image::images/cem_heartbeats.png[width=800] . You can then select the **Flow Designer** tab (image:images/flow_designer_icon.png[width=30]). To build a dataflow, select the desired class (`iot-1`) from the table and click OPEN. Alternatively, you can double-click on the desired class. . Add a _GetFile_ processor onto canvas to get csv data: + Update processor name to **GetCSVFile**. . Add a _Remote Process Group_ (RPG) to the canvas and configure it as follows: + [source] ---- URL: http://edge2ai-1.dim.local:8080/nifi ---- + image::images/add_rpg.png[width=800] . At this point you need to connect the ConsumerMQTT processor to the RPG. For this, you first need to add an Input Port to the remote NiFi server. Open the NiFi Web UI at `\\http://:8080/nifi/` and drag the _Input Port_ to the canvas. Call it something like ""from Gateway"". + image::images/add_input_port.png[width=800] . To terminate the NiFI _Input Port_ let's, for now, add a _Funnel_ to the canvas... + image::images/add_funnel.png[width=600] . ... and setup a connection from the Input Port to it. To setup a connection, hover the mouse over the Input Port until an arrow symbol is shown in the center. Click on the arrow, drag it and drop it on the Funnel to connect the two elements. + image::images/connecting.png[width=800] . Right-click on the Input Port and start it. Alternatively, click on the Input Port to select it and then press the start (""play"") button on the Operate panel: + image::images/operate_panel.png[width=300] . You will need the ID of the _Input Port_ to complete the connection of the _ConsumeMQTT_ processor to the RPG (NiFi). Double-click on the _Input Port_ and copy its ID. + image::images/input_port_id.png[width=800] . Back to the Flow Designer, connect the ConsumeMQTT processor to the RPG. The connection requires an ID and you can paste here the ID you copied from the Input Port. + image::images/connect_to_rpg.png[width=800] . The Flow is now complete, but before publishing it, create the Bucket in the _NiFi Registry_ so that all versions of your flows are stored for review and audit. Open the NiFi Registry at `\\http://:18080/nifi-registry`, click on the wrench/spanner icon (image:images/spanner_icon.png[width=20]) on the top-right corner on and create a bucket called `IoT`. + image::images/create_bucket.png[width=800] . You can now publish the flow for the MiNiFi agent to automatically pick up. Click *Publish*, add a descriptive comment for your changes and click *Apply*. + image::images/publish_flow.png[width=800] + image::images/cem_first_version.png[width=800] . Go back to the *NiFi Registry* Web UI and click on the *NiFi Registry* name, next to the Cloudera logo. If the flow publishing was successful, you should see the flow's version details in the NiFi Registry. + image::images/flow_in_nifi_registry.png[width=800] . At this point, you can test the edge flow up until NiFi. Start the simulator again and confirm you can see the messages queued in NiFi. + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- + image::images/running_simulator.png[width=800] + image::images/queued_events.png[width=300] . You can stop the simulator once you confirm that the flow is working correctly. [[lab_4, Lab 4]] == Lab 4 - Registering our schema in Schema Registry The data produced by the temperature sensors is described by the schema in file `link:https://raw.githubusercontent.com/cloudera-labs/edge2ai-workshop/master/sensor.avsc[sensor.avsc]`. In this lab we will register this schema in Schema Registry so that our flows in NiFi can refer to schema using an unified service. This will also allow us to evolve the schema in the future, if needed, keeping older versions under version control, so that existing flows and flowfiles will continue to work. . Go the following URL, which contains the schema definition we'll use for this lab. Select all contents of the page and copy it. + `link:https://raw.githubusercontent.com/cloudera-labs/edge2ai-workshop/master/sensor.avsc[https://raw.githubusercontent.com/cloudera-labs/edge2ai-workshop/master/sensor.avsc, window=""_blank""]` . In the Schema Registry Web UI, click the `+` sign to register a new schema. . Click on a blank area in the *Schema Text* field and paste the contents you copied. . Complete the schema creation by filling the following properties: + [source] ---- Name: SensorReading Description: Schema for the data generated by the IoT sensors Type: Avro schema provider Schema Group: Kafka Compatibility: Backward Evolve: checked ---- image::images/register_schema.png[width=800] . Save the schema [[lab_5, Lab 5]] == Lab 5 - Configuring the NiFi flow and pushing data to Kafka In this lab, you will create a NiFi flow to receive the data from all gateways and push it to **Kafka**. === Creating a Process Group Before we start building our flow, let's create a Process Group to help organizing the flows in the NiFi canvas and also to enable flow version control. . Open the NiFi Web UI, create a new Process Group and name it something like *Process Sensor Data*. + image::images/create_pgroup.png[width=800] . We want to be able to version control the flows we will add to the Process Group. In order to do that, we first need to connect NiFi to the *NiFi Registry*. On the NiFi global menu, click on ""Controller Services"", navigate to the ""Registry Clients"" tab and add a Registry client with the following URL: + ---- Name: NiFi Registry URL: http://edge2ai-1.dim.local:18080 ---- + image::images/global_controller_settings.png[width=800] + image::images/add_registry_client.png[width=800] . On the *NiFi Registry* Web UI, add another bucket for storing the Sensor flow we're about to build'. Call it `SensorFlows`: + image::images/sensor_flows_bucket.png[width=800] . Back on the *NiFi* Web UI, to enable version control for the Process Group, right-click on it and select *Version > Start version control* and enter the details below. Once you complete, a image:images/version_control_tick.png[width=20] will appear on the Process Group, indicating that version control is now enabled for it. + [source] ---- Registry: NiFi Registry Bucket: SensorFlows Flow Name: SensorProcessGroup ---- . Let's also enable processors in this Process Group to use schemas stored in Schema Registry. Right-click on the Process Group, select *Configure* and navigate to the *Controller Services* tab. Click the *`+`* icon and add a *HortonworksSchemaRegistry* service. After the service is added, click on the service's _cog_ icon (image:images/cog_icon.png[width=20]), go to the *Properties* tab and configure it with the following *Schema Registry URL* and click *Apply*. + [source] ---- URL: http://edge2ai-1.dim.local:7788/api/v1 ---- + image::images/added_hwx_sr_service.png[width=800] . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *HortonworksSchemaRegistry* Controller Service. . Still on the *Controller Services* screen, let's add two additional services to handle the reading and writing of JSON records. Click on the image:images/plus_button.png[width=25] button and add the following two services: ** *`JsonTreeReader`*, with the following properties: + [source] ---- Schema Access Strategy: Use 'Schema Name' Property Schema Registry: HortonworksSchemaRegistry Schema Name: ${schema.name} -> already set by default! ---- ** *`JsonRecordSetWriter`*, with the following properties: + [source] ---- Schema Write Strategy: HWX Schema Reference Attributes Schema Access Strategy: Inherit Record Schema Schema Registry: HortonworksSchemaRegistry ---- . Enable the *JsonTreeReader* and the *JsonRecordSetWriter* Controller Services you just created, by clicking on their respective _lightning bolt_ icons (image:images/enable_icon.png[width=20]). + image::images/controller_services.png[width=800] === Creating the flow . Double-click on the newly created process group to expand it. . Inside the process group, add a new _Input Port_ and name it ""Sensor Data"" . We need to tell NiFi which schema should be used to read and write the Sensor data. For this we'll use an _UpdateAttribute_ processor to add an attribute to the FlowFile indicating the schema name. + Add an _UpdateAttribute_ processor by dragging the processor icon to the canvas: + image::images/add_updateattribute.png[width=800] . Double-click the _UpdateAttribute_ processor and configure it as follows: .. In the _SETTINGS_ tab: + [source] ---- Name: Set Schema Name ---- .. In the _PROPERTIES_ tab: ** Click on the image:images/plus_button.png[width=25] button and add the following property: + [source] ---- Property Name: schema.name Property Value: SensorReading ---- .. Click *Apply* . Connect the *Sensor Data* input port to the *Set Schema Name* processor. . Add a _PublishKafkaRecord_2.0_ processor and configure it as follows: + *SETTINGS* tab: + [source] ---- Name: Publish to Kafka topic: iot ---- + *PROPERTIES* tab: + [source] ---- Kafka Brokers: edge2ai-1.dim.local:9092 Topic Name: iot Record Reader: JsonTreeReader Record Writer: JsonRecordSetWriter Use Transactions: false Attributes to Send as Headers (Regex): schema.* ---- + NOTE: Make sure you use the PublishKafkaRecord_2.0 processor and *not* the PublishKafka_2.0 one . While still in the _PROPERTIES_ tab of the _PublishKafkaRecord_2.0_ processor, click on the image:images/plus_button.png[width=25] button and add the following property: + [source] ---- Property Name: client.id Property Value: nifi-sensor-data ---- + Later, this will help us clearly identify who is producing data into the Kafka topic. . Connect the *Set Schema Name* processor to the *Publish to Kafka topic: iot* processor. . Add a new _Funnel_ to the canvas and connect the PublishKafkaRecord processor to it. When the ""Create connection"" dialog appears, select ""*failure*"" and click *Add*. + image::images/add_kafka_failure_connection.png[width=600] . Double-click on the *Publish to Kafka topic: iot* processor, go to the *SETTINGS* tab, check the ""*success*"" relationship in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section. Click *Apply*. + image::images/terminate_publishkafka_relationship.png[width=600] . Start the input port and the two processors. Your canvas should now look like the one below: + image::images/publishKafka_flow.png[width=800] . The only thing that remains to be configured now is to finally connect the ""*from Gateway*"" Input Port to the flow in the ""*Processor Sensor Data*"" group. To do that, first go back to the root canvas by clicking on the *NiFi Flow* link on the status bar. + image::images/breadcrumbs.png[width=400] . Connect the Input Port to the *Process Sensor Data* Process Group by dragging the destination of the current connection from the funnel to the Process Group. When prompted, ensure the ""To input"" fields is set to the *Sensor data* Input Port. + image::images/connect_input.png[width=800] + image::images/to_input.png[width=800] . Refresh the screen (`Ctrl+R` on Linux/Windows; `Cmd+R` on Mac) and you should see that the records that were queued on the ""*from Gateway*"" Input Port disappeared. They flowed into the *Process Sensor Data* flow. If you expand the Process Group you should see that those records were processed by the _PublishKafkaRecord_ processor and there should be no records queued on the ""failure"" output queue. + image::images/kafka_success.png[width=800] + At this point, the messages are already in the Kafka topic. You can add more processors as needed to process, split, duplicate or re-route your FlowFiles to all other destinations and processors. . To complete this Lab, let's commit and version the work we've just done. Go back to the NiFi root canvas, clicking on the ""Nifi Flow"" breadcrumb. Right-click on the *Process Sensor Data* Process Group and select *Version > Commit local changes*. Enter a descriptive comment and save. [[lab_6, Lab 6]] == Lab 6 - Use SMM to confirm that the data is flowing correctly Now that our NiFi flow is pushing data to Kafka, it would be good to have a confirmation that everything is running as expected. In this lab you will use Streams Messaging Manager (SMM) to check and monitor Kafka. . Start the simulator again and confirm you can see the messages queued in NiFi. Leave it running. + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- . Go to the Stream Messaging Manager (SMM) Web UI and familiarize yourself with the options there. Notice the filters (blue boxes) at the top of the screen. + image::images/smm.png[width=800] . Click on the *Producers* filter and select only the *`nifi-sensor-data`* producer. This will hide all the irrelevant topics and show only the ones that producer is writing to. . If you filter by *Topic* instead and select the `iot` topic, you'll be able to see all the *producers* and *consumers* that are writing to and reading from it, respectively. Since we haven't implemented any consumers yet, the consumer list should be empty. . Click on the topic to explore its details. You can see more details, metrics and the break down per partition. Click on one of the partitions and you'll see additional information and which producers and consumers interact with that partition. + image::images/producers.png[width=800] . Click on the *EXPLORE* link to visualize the data in a particular partition. Confirm that there's data in the Kafka topic and it looks like the JSON produced by the sensor simulator. + image::images/explore_partition.png[width=800] . Check the data from the partition. You'll notice something odd. These are readings from temperature sensors and we don't expect any of the sensors to measure temperatures greater than 150 degrees in the conditions they are used. It seems, though, that `sensor_0` and `sensor_1` are intermittently producing noise and some of the measurements have very high values for these measurements. + image::images/troubled_sensors.png[width=800] . Stop the simulator with CTRL-C. . In the next Lab we'll eliminate with these problematic measurements to avoid problems later in our data flow. [[lab_7, Lab 7]] == Lab 7 - Update the edge flows to perform additional processing on the data In the previous lab we noticed that some of the sensors were sending erroneous measurements intermittently. If we let these measurements to be processed by our data flow we might have problems with the quality of our flow output and we want to avoid that. We could use our *Process Sensor Data* flow in NiFi to filter out those problematic measurements. However, if their volume is large we could be wasting network bandwidth and causing additional overhead in NiFi to process the bogus data. What we'd like to do instead is to push additional logic to the edge to identify and filter those problems in place and avoiding sending them to NiFi in the first place. We've noticed that the problem always happen with the temperatures in measurements `sensor_0` and `sensor_1`, only. If any of these two temperatures are *greater than 500* we *must discard* the entire sensor reading. If both of these temperatures are in the normal range (< 500) we can guarantee that all temperatures reported are correct and can be sent to NiFi. . Go to the CEM Web UI and add a new processor to the canvas. In the Filter box of the dialog that appears, type ""JsonPath"". Select the _EvaluateJSONPath_ processor and click *Add*. . Double-click on the new processor and configure it with the following properties: + [source,python] ---- Processor Name: Extract sensor_0 and sensor1 values Destination: flowfile-attribute ---- + image::images/EvaluateJsonPath.png[width=800] . Click on the *Add Property* button and enter the following properties: + [%autowidth,cols=""1a,1a"",options=""header""] |=== |Property Name|Property Value |`sensor_0`|`$.sensor_0` |`sensor_1`|`$.sensor_1` |=== + image::images/extract_attributes.png[width=800] . Click *Apply* to save the processor configuration. . Drag one more new processor to the canvas. In the Filter box of the dialog that appears, type ""Route"". Select the _RouteOnAttribute_ processor and click *Add*. + image::images/route_on_attribute.png[width=800] . Double-click on the new processor and configure it with the following properties: + [source,python] ---- Processor Name: Filter Errors Route Strategy: Route to Property name ---- . Click on the *Add Property* button and enter the following properties: + [%autowidth,cols=""1a,1a"",options=""header""] |=== |Property Name|Property Value |`error`|`${sensor_0:ge(500):or(${sensor_1:ge(500)})}` |=== + image::images/route_on_attribute_config.png[width=800] . Click *Apply* to save the processor configuration. . Reconnect the _ConsumeMQTT_ processor to the _Extract sensor_0 and sensor1 values_ processor: .. Click on the existing connection between _ConsumeMQTT_ and the _RPG_ to select it. .. Drag the destination end of the connection to the _Extract sensor_0 and sensor1 values_ processor. + image::images/reconnect_consume_mqtt.png[width=800] . Connect the _Extract sensor_0 and sensor1 values_ to the _Filter errors_ processor. When the *Create Connection* dialog appear, select ""*matched*"" and click *Create*. + image::images/connect_extract_to_route.png[width-800] + image::images/create_connection.png[width=800] . Double-click the _Extract sensor_0 and sensor1 values_ and check the following values in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section and click *Apply*: ** failure ** unmatched ** sensor_0 ** sensor_1 + image::images/terminations.png[width=800] . Before creating the last connection, you will need (again) the ID of the NiFi _Input Port_. Go to the NiFi Web UI , double-click on the ""*from Gateway*"" _Input Port_ and copy its ID. + image::images/input_port_id.png[width=800] . Back on the CEM Web UI, connect the _Filter errors_ processor to the RPG: + image::images/connect_filter_ro_rpg.png[width=800] . In the *Create Connection* dialog, check the ""*unmatched*"" checkbox and enter the copied input port ID, and click on *Create*: + image::images/create_last_connection.png[width=800] . To ignore the errors, double-click on the _Filter errors_ processor, check the *error* checkbox under the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section and click *Apply*: + image::images/terminate_errors.png[width=800] . Finally, click on *ACTIONS > Publish...* on the CEM canvas, enter a descriptive comment like ""Added filtering of erroneous readings"" and click *Publish*. . Start the simulator again. . Go to the NiFi Web UI and confirm that the data is flowing without errors within the *Process Sensor Data* process group. Refresh a few times and check that the numbers are changing. . Use the *EXPLORE* feature on the SMM Web UI to confirm that the bogus readings have been filtered out. . Stop the simulator once you have verified the data. [[lab_8, Lab 8]] == Lab 8 - Use NiFi to call the CDSW model endpoint and save to Kudu In this lab, you will use NiFi to consume the Kafka messages containing the IoT data we ingested in the previous lab, call a CDSW model API endpoint to predict whether the machine where the readings came from is likely to break or not. In preparation for the workshop we trained and deployed a Machine Learning model on the Cloudera Data Science Workbench (CDSW) running on your cluster. The model API can take a feature vector with the reading for the 12 temperature readings provided by the sensor and predict, based on that vector, if the machine is likely to break or not. === Add new Controller Services When the sensor data was sent to Kafka using the _PublishKafkaRecord_ processor, we chose to attach the schema information in the header of Kafka messages. Now, instead of hard-coding which schema we should use to read the message, we can leverage that metadata to dynamically load the correct schema for each message. To do this, though, we need to configure a different _JsonTreeReader_ that will use the schema properties in the header, instead of the `${schema.name}` attribute, as we did before. We'll also add a new _RestLookupService_ controller service to perform the calls to the CDSW model API endpoint. . If you're not in the *Process Sensor Data* process group, double-click on it to expand it. On the *Operate* panel (left-hand side), click on the _cog_ icon (image:images/cog_icon.png[width=25]) to access the *Process Sensor Data* process group's configuration page. + image::images/operate_panel_cog.png[width=300] . Click on the _plus_ button (image:images/plus_button.png[width=25]), add a new *JsonTreeReader*, configure it as shown below and click *Apply* when you're done: + On the *SETTINGS* tab: + [source] ---- Name: JsonTreeReader - With schema identifier ---- + On the *PROPERTIES* tab: + [source] ---- Schema Access Strategy: HWX Schema Reference Attributes Schema Registry: HortonworksSchemaRegistry ---- . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *JsonTreeReader - With schema identifier* controller service. . Click again on the _plus_ button (image:images/plus_button.png[width=25]), add a *RestLookupService* controller service, configure it as shown below and click *Apply* when you're done: + On the *PROPERTIES* tab: + [source] ---- URL: http://cdsw..nip.io/api/altus-ds-1/models/call-model Record Reader: JsonTreeReader Record Path: /response ---- + NOTE: `` above must be replaced with your cluster's public IP, *not* DNS name. The final URL should look something like this: `\\http://cdsw.12.34.56.78.nip.io/api/altus-ds-1/models/call-model` . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *RestLookupService* controller service. + image::images/additional_controller_services.png[width=800] . Close the *Process Sensor Data Configuration* page. === Create the flow We'll now create the flow to read the sensor data from Kafka, execute a model prediction for each of them and write the results to Kudu. At the end of this section you flow should look like the one below: image::images/from_kafka_to_kudu_flow.png[width=800] ==== ConsumeKafkaRecord_2_0 processor . We'll add a new flow to the same canvas we were using before (inside the *Process Sensor Data* Process Group). Click on an empty area of the canvas and drag it to the side to give you more space to add new processors. . Add a *ConsumeKafkaRecord_2_0* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Consume Kafka iot messages ---- + *PROPERTIES* tab: + [source] ---- Kafka Brokers: edge2ai-1.dim.local:9092 Topic Name(s): iot Topic Name Format: names Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Honor Transactions: false Group ID: iot-sensor-consumer Offset Reset: latest Headers to Add as Attributes (Regex): schema.* ---- . Add a new _Funnel_ to the canvas and connect the *Consume Kafka iot messages* to it. When prompted, check the *parse.failure* relationship for this connection: + image:images/parse_failure_relationship.png[width=500] ==== LookupRecord processor . Add a *LookupRecord* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Predict machine health ---- + *PROPERTIES* tab: + [source] ---- Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Lookup Service: RestLookupService Result RecordPath: /response Routing Strategy: Route to 'success' Record Result Contents: Insert Entire Record ---- . Add 3 more user-defined properties by clicking on the _plus_ button (image:images/plus_button.png[width=25]) for each of them: + [source] ---- mime.type: toString('application/json', 'UTF-8') request.body: concat('{""accessKey"":""', '${cdsw.access.key}', '"",""request"":{""feature"":""', /sensor_0, ', ', /sensor_1, ', ', /sensor_2, ', ', /sensor_3, ', ', /sensor_4, ', ', /sensor_5, ', ', /sensor_6, ', ', /sensor_7, ', ', /sensor_8, ', ', /sensor_9, ', ', /sensor_10, ', ', /sensor_11, '""}}') request.method: toString('post', 'UTF-8') ---- . Click *Apply* to save the changes to the *Predict machine health* processor. . Connect the *Consume Kafka iot messages* processor to the *Predict machine health* one. When prompted, check the *success* relationship for this connection. . Connect the *Predict machine health* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. ==== UpdateRecord processor . Add a *UpdateRecord* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Update health flag ---- + *PROPERTIES* tab: + [source] ---- Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Replacement Value Strategy: Record Path Value ---- . Add one more user-defined propertie by clicking on the _plus_ button (image:images/plus_button.png[width=25]): + [source] ---- /is_healthy: /response/result ---- . Connect the *Predict machine health* processor to the *Update health flag* one. When prompted, check the *success* relationship for this connection. . Connect the *Update health flag* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. ==== PutKudu processor . Add a *PutKudu* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Write to Kudu ---- + *PROPERTIES* tab: + [source] ---- Kudu Masters: edge2ai-1.dim.local:7051 Table Name: impala::default.sensors Record Reader: JsonTreeReader - With schema identifier ---- . Connect the *Update health flag* processor to the *Write to Kudu* one. When prompted, check the *success* relationship for this connection. . Connect the *Write to Kudu* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. . Double-click on the *Write to Kudu* processor, go to the *SETTINGS* tab, check the ""*success*"" relationship in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section. Click *Apply*. ==== CDSW Access Key When we added the *Predict machine health* above, you may have noticed that one of the properties (`request.body`) makes a reference to a variable called `cdsw.access.key`. This is an application key required to authenticate with the CDSW Model API when requesting predictions. So, we need to provide the key to the _LookupRecord_ processor by setting a variable with its value. . To get the Access Key, go to the CDSW Web UI and click on *Models > Iot Prediction Model > Settings*. Copy the Access Key. + image::images/model_access_key.png[width=800] . Go back to the NiFi Web UI, right-click on an empty area of the *Process Sensor Data* canvas, and click on *Variables*. . Click on the _plus_ button (image:images/plus_button.png[width=25]) and add the following variable: + [source] ---- Variable Name: cdsw.access.key Variable Value: ---- + image::images/access_key_variable.png[width=800] . Click *Apply* ==== Create the Kudu table . Go to the Hue Web UI and login. The first user to login to a Hue installation is automatically created and granted admin privileges in Hue. . The Hue UI should open with the Impala Query Editor by default. If it doesn't, you can always find it by clicking on *Query button > Editor -> Impala*: + image::images/impala_editor.png[width=800] . First, create the Kudu table. Login into Hue, and in the Impala Query, run this statement: + [source,sql] ---- CREATE TABLE sensors ( sensor_id INT, sensor_ts TIMESTAMP, sensor_0 DOUBLE, sensor_1 DOUBLE, sensor_2 DOUBLE, sensor_3 DOUBLE, sensor_4 DOUBLE, sensor_5 DOUBLE, sensor_6 DOUBLE, sensor_7 DOUBLE, sensor_8 DOUBLE, sensor_9 DOUBLE, sensor_10 DOUBLE, sensor_11 DOUBLE, is_healthy INT, PRIMARY KEY (sensor_ID, sensor_ts) ) PARTITION BY HASH PARTITIONS 16 STORED AS KUDU TBLPROPERTIES ('kudu.num_tablet_replicas' = '1'); ---- + image::images/create_table.png[width=800] ==== Running the flow We're ready not to run and test our flow. Follow the steps below: . Start all the processors in your flow. . If the simulator is not already running, start it again on your SSH window: + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- . Refresh your NiFi page and you should see messages passing through your flow. The failure queues should have no records queued up. + image::images/kudu_success.png[width=800] . On Lab 10, you will learn how to query and verify the records inserted into Kudu. [[lab_9, Lab 9]] == Lab 9 - Use Spark to call the CDSW model endpoint and save to Kudu NOTE: This lab is optional, since it does the same processing we performed in Lab 8 but using Spark instead of NiFi. If you want to run this lab, stop the flow created in Lab 8 first, to avoid duplicated data being sent into Kudu. Otherwise, just skip to *Lab 10* Spark Streaming is a processing framework for (near) real-time data. In this lab, you will use Spark to consume Kafka messages which contains the IoT data from the machine, and call the model API endpoint to predict whether, with those IoT values the machine sent, the machine is likely to break. Then save the results to Kudu for fast analytics. ==== Create the Kudu table NOTE: If you already executed this step in the previous lab, please skip the table creation here. . Go to the Hue Web UI and login. The first user to login to a Hue installation is automatically created and granted admin privileges in Hue. . The Hue UI should open with the Impala Query Editor by default. If it doesn't, you can always find it by clicking on *Query button > Editor -> Impala*: + image::images/impala_editor.png[width=800] . First, create the Kudu table. Login into Hue, and in the Impala Query, run this statement: + [source,sql] ---- CREATE TABLE sensors ( sensor_id INT, sensor_ts TIMESTAMP, sensor_0 DOUBLE, sensor_1 DOUBLE, sensor_2 DOUBLE, sensor_3 DOUBLE, sensor_4 DOUBLE, sensor_5 DOUBLE, sensor_6 DOUBLE, sensor_7 DOUBLE, sensor_8 DOUBLE, sensor_9 DOUBLE, sensor_10 DOUBLE, sensor_11 DOUBLE, is_healthy INT, PRIMARY KEY (sensor_ID, sensor_ts) ) PARTITION BY HASH PARTITIONS 16 STORED AS KUDU TBLPROPERTIES ('kudu.num_tablet_replicas' = '1'); ---- + image::images/create_table.png[width=800] ==== CDSW Access Key . To configure and run the Spark Streaming job, you will need a CDSW Access Key to connect to the model endpoint that has been deployed there. To get the Access Key, go to the CDSW Web UI and click on *Models > Iot Prediction Model > Settings*. Copy the Access Key. + image::images/model_access_key.png[width=800] ==== Running the Spark job . Open a second Terminal and SSH into the VM. The first is running the sensor data simulator, so you can't use it. + [source,shell] ---- ACCESS_KEY= PUBLIC_IP=$(curl https://api.ipify.org/) mv ~/edge2ai-workshop/spark.iot.py ~ sed -i ""s/YourHostname/$(hostname -f)/"" spark.iot.py sed -i ""s/YourCDSWDomain/cdsw.$PUBLIC_IP.nip.io/"" spark.iot.py sed -i ""s/YourAccessKey/$ACCESS_KEY/"" spark.iot.py wget http://central.maven.org/maven2/org/apache/kudu/kudu-spark2_2.11/1.9.0/kudu-spark2_2.11-1.9.0.jar wget https://raw.githubusercontent.com/swordsmanliu/SparkStreamingHbase/master/lib/spark-core_2.11-1.5.2.logging.jar rm -rf ~/.m2 ~/.ivy2/ spark-submit \\ --master local[2] \\ --jars kudu-spark2_2.11-1.9.0.jar,spark-core_2.11-1.5.2.logging.jar \\ --packages org.apache.spark:spark-streaming-kafka_2.11:1.6.3 \\ spark.iot.py ---- + . Spark Streaming will flood your screen with log messages, however, at a 5 seconds interval, you should be able to spot a table: these are the messages that were consumed from Kafka and processed by Spark. You can configure Spark for a smaller time window, however, for this exercise 5 seconds is sufficient. + image::images/spark_job_output.png[width=800] [[lab_10, Lab 10]] == Lab 10 - Fast analytics on fast data with Kudu and Impala In this lab, you will run some SQL queries using the Impala engine. You can run a report to inform you which machines are likely to break in the near future. . Login into Hue and run the following queries in the Impala Query Editor: + [source,sql] ---- SELECT sensor_id, sensor_ts FROM sensors WHERE is_healthy = 0; ---- + [source,sql] ---- SELECT is_healthy, count(*) as occurrences FROM sensors GROUP BY is_healthy; ---- . Run a few times the SQL statements and verify that the number of occurrences are increasing as the data is ingested by either NiFi or the Spark job. This allows you to build real-time reports for fast action. + image::images/table_select.png[width=800] [[lab_11, Lab 11]] == Lab 11 - CDSW: Train the model In this and the following lab, you will wear the hat of a Data Scientist. You will write the model code, train it several times and finally deploy the model to Production. All within 30 minutes! === STEP 1: Configure CDSW . Open CDSW Web UI and log in as `admin`, if you haven't yet done so. . Navigate to the CDSW **Admin** page to fine tune the environment: .. In the **Engines** tab, add in _Engines Profiles_ a new engine (docker image) with 2 vCPUs and 4 GB RAM, while deleting the default engine. .. Check if the following variable already exists under _Environmental Variables_. If not, add it: + [source] ---- HADOOP_CONF_DIR=/etc/hadoop/conf/ ---- + image::images/engines.png[width=800] === STEP 2: Create the project . Return to the main page and click on *New Project*, using this GitHub project as the source: `https://github.com/cloudera-labs/edge2ai-workshop` + image::images/create_project.png[width=800] . Now that your project has been created, click on *Open Workbench* and start a Python3 session: + image::images/open_workbench.png[width=800] . Once the Engine is ready, run the following command to install some required libraries: + [source] ---- !pip3 install --upgrade pip scikit-learn ---- . The project comes with a historical dataset. Copy this dataset into HDFS: + [source] ---- !hdfs dfs -put -f data/historical_iot.txt /user/$HADOOP_USER_NAME ---- + image::images/session_prep.png[width=800] . You're now ready to run the Experiment to train the model on your historical data. . You can stop the Engine at this point. === STEP 3: Examine `cdsw.iot_exp.py` Open the file `cdsw.iot_exp.py`. This is a python program that builds a model to predict machine failure (the likelihood that this machine is going to fail). There is a dataset available on hdfs with customer data, including a failure indicator field. The program is going to build a failure prediction model using the Random Forest algorithm. Random forests are ensembles of decision trees. Random forests are one of the most successful machine learning models for classification and regression. They combine many decision trees in order to reduce the risk of overfitting. Like decision trees, random forests handle categorical features, extend to the multiclass classification setting, do not require feature scaling, and are able to capture non-linearities and feature interactions. `spark.mllib` supports random forests for binary and multiclass classification and for regression, using both continuous and categorical features. `spark.mllib` implements random forests using the existing decision tree implementation. Please see the decision tree guide for more information on trees. The Random Forest algorithm expects a couple of parameters: * *numTrees*: Number of trees in the forest. + Increasing the number of trees will decrease the variance in predictions, improving the model’s test-time accuracy. Training time increases roughly linearly in the number of trees. * *maxDepth*: Maximum depth of each tree in the forest. + Increasing the depth makes the model more expressive and powerful. However, deep trees take longer to train and are also more prone to overfitting. In general, it is acceptable to train deeper trees when using random forests than when using a single decision tree. One tree is more likely to overfit than a random forest (because of the variance reduction from averaging multiple trees in the forest). In the `cdsw.iot_exp.py` program, these parameters can be passed to the program at runtime, to these python variables: [source,python] ---- param_numTrees = int(sys.argv[1]) param_maxDepth = int(sys.argv[2]) ---- Also note the quality indicator for the Random Forest model, are written back to the Data Science Workbench repository: [source,python] ---- cdsw.track_metric(""auroc"", auroc) cdsw.track_metric(""ap"", ap) ---- These indicators will show up later in the **Experiments** dashboard. === STEP 4: Run the experiment for the first time . Now, run the experiment using the following parameters: + [source,python] ---- numTrees = 20 numDepth = 20 ---- . From the menu, select `Run -> Run Experiments...`. Now, in the background, the Data Science Workbench environment will spin up a new docker container, where this program will run. + image::images/run_experiment.png[width=800] . Go back to the **Projects** page in CDSW, and hit the **Experiments** button. . If the Status indicates `Running`, you have to wait till the run is completed. In case the status is `Build Failed` or `Failed` , check the log information. This is accessible by clicking on the run number of your experiments. There you can find the session log, as well as the build information. + image::images/experiment_details.png[width=800] . In case your status indicates `Success`, you should be able to see the *auroc* (Area Under the Curve) model quality indicator. It might be that this value is hidden by the CDSW user interface. In that case, click on the ‘3 metrics’ links, and select the auroc field. It might be needed to de-select some other fields, since the interface can only show 3 metrics at the same time. + image::images/exp_metrics.png[width=800] . In this example, `~0.8383`. Not bad, but maybe there are better hyper parameter values available. === STEP 5: Re-run the experiment several times . Go back to the Workbench and run the experiment 2 more times and try different values for NumTrees and NumDepth. Try the following values: + [source,python] ---- NumTrees NumDepth 15 25 25 20 ---- . When all runs have completed successfully, check which parameters had the best quality (best predictive value). This is represented by the highest _area under the curve_: `auroc` metric. + image::images/best_model.png[width=800] === STEP 6: Save the best model to your environment . Select the run number with the best predictive value (in the example above, experiment *4*). . In the *Overview* screen of the experiment, you can see that the model, in Pickle format (`.pkl`), is captured in the file `iot_model.pkl`. Select this file and hit the **Add to Project** button. This will copy the model to your project directory. + image::images/save_model.png[width=800] + image::images/model_saved.png[width=800] [[lab_12, Lab 12]] == Lab 12 - CDSW: Deploy the model === STEP 1: Examine the program `cdsw.iot_model.py` . Open the project you created in the previous lab and examine the file in the Workbench. This PySpark program uses the `pickle.load` mechanism to deploy models. The model is loaded from the `iot_modelf.pkl` file, which was saved in the previous lab from the experiment with the best predictive model. + There program also contains the `predict` definition, which is the function that calls the model, passing the features as parameters, and will return a result variable. . Before deploying the model, try it out in the Workbench: launch a Python3 engine and run the code in file `cdsw.iot_model.py`. Then call the `predict()` method from the prompt: + [source,python] ---- predict({""feature"": ""0, 65, 0, 137, 21.95, 83, 19.42, 111, 9.4, 6, 3.43, 4""}) ---- + image::images/predict.png[width=800] . The functions returns successfully, so we know we can now deploy the model. You can now stop the engine. === STEP 2: Deploy the model . From the main page of your project, select the *Models* button. Select *New Model* and specify the following configuration: + [source, python] ---- Name: IoT Prediction Model Description: IoT Prediction Model File: cdsw.iot_model.py Function: predict Example Input: {""feature"": ""0, 65, 0, 137, 21.95, 83, 19.42, 111, 9.4, 6, 3.43, 4""} Kernel: Python 3 Engine: 2 vCPU / 4 GB Memory Replicas: 1 ---- + image:images/create_model.png[width=800] . After all parameters are set, click on the *Deploy Model* button. Wait till the model is deployed. This can take several minutes. === STEP 3: Test the deployed model . When your model status change to `Deployed`, click on the model name link to go to the Model's *Overview* page. From the that page, click on the *Test* button to check if the model is working. . The green circle with the `success` status indicates that our REST call to the model is working. The `1` in the response `{""result"": 1}`, means that the machine from where these temperature readings were collected is _unlikely_ to experience a failure. + image::images/test_model.png[width=800] . Now, lets change the input parameters and call the predict function again. Put the following values in the Input field: + [source,python] ---- { ""feature"": ""0, 95, 0, 88, 26.62, 75, 21.05, 115, 8.65, 5, 3.32, 3"" } ---- . With these input parameters, the model returns `0`, which means that the machine is likely to break. == Resources * link:https://medium.freecodecamp.org/building-an-iiot-system-using-apache-nifi-mqtt-and-raspberry-pi-ce1d6ed565bc[Original blog by Abdelkrim Hadjidj] * This workshop was based on the following work by Fabio Ghirardello: ** https://github.com/fabiog1901/IoT-predictive-maintenance ** https://github.com/fabiog1901/OneNodeCDHCluster * link:https://www.cloudera.com/documentation.html[Cloudera Documentation] == Troubleshooting ==== *CEM doesn't pick up new NARs* . Delete the agent manifest manually using the EFM API: . Verify each class has the same agent manifest ID: + [source] ---- http://hostname:10080/efm/api/agent-classes [{""name"":""iot1"",""agentManifests"":[""agent-manifest-id""]},{""name"":""iot4"",""agentManifests"":[""agent-manifest-id""]}] ---- . Confirm the manifest doesn't have the NAR you installed + [source] ---- http://hostname:10080/efm/api/agent-manifests?class=iot4 [{""identifier"":""agent-manifest-id"",""agentType"":""minifi-java"",""version"":""1"",""buildInfo"":{""timestamp"":1556628651811,""compiler"":""JDK 8""},""bundles"":[{""group"":""default"",""artifact"":""system"",""version"":""unversioned"",""componentManifest"":{""controllerServices"":[],""processors"": ---- . Call the API endpoint: + [source] ---- http://hostname:10080/efm/swagger/ ---- . Hit the `DELETE - Delete the agent manifest specified by id` button, and in the id field, enter `agent-manifest-id` ",12196,False,2079.4286577205166,median "[[box-component]] = Box Component :docTitle: Box :artifactId: camel-box :description: Upload, download and manage files, folders, groups, collaborations, etc. on box.com. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/box.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Box component provides access to all of the Box.com APIs accessible using https://github.com/box/box-java-sdk/[https://github.com/box/box-java-sdk]. It allows producing messages to upload and download files, create, edit, and manage folders, etc. It also supports APIs that allow polling for updates to user accounts and even changes to enterprise accounts, etc. Box.com requires the use of OAuth2.0 for all client application authentication. In order to use camel-box with your account, you'll need to create a new application within Box.com at https://developer.box.com/[https://developer.box.com]. The Box application's client id and secret will allow access to Box APIs which require a current user. A user access token is generated and managed by the API for an end user. Maven users will need to add the following dependency to their pom.xml for this component: [source,xml] ---- org.apache.camel camel-box ${camel-version} ---- == Connection Authentication Types The Box component supports three different types of authenticated connections. === Standard Authentication *Standard Authentication* uses the *OAuth 2.0 three-legged authentication process* to authenticate its connections with Box.com. This type of authentication enables Box *managed users* and *external users* to access, edit, and save their Box content through the Box component. === App Enterprise Authentication *App Enterprise Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as a *Service Account* for a *Box Application*. This type of authentication enables a service account to access, edit, and save the Box content of its *Box Application* through the Box component. === App User Authentication *App User Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as an *App User* for a *Box Application*. This type of authentication enables app users to access, edit, and save their Box content in its *Box Application* through the Box component. == Box Options // component options: START The Box component supports 19 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *configuration* (common) | To use the shared configuration | | BoxConfiguration | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *userId* (common) | The user ID to use for an App User. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *basicPropertyBinding* (advanced) | *Deprecated* Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== // component options: END // endpoint options: START The Box endpoint is configured using URI syntax: ---- box:apiName/methodName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *apiName* | *Required* What kind of operation to perform. There are 10 enums and the value can be one of: COLLABORATIONS, COMMENTS, EVENT_LOGS, FILES, FOLDERS, GROUPS, EVENTS, SEARCH, TASKS, USERS | | BoxApiName | *methodName* | *Required* What sub operation to use for the selected operation | | String |=== === Query Parameters (21 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *inBody* (common) | Sets the name of a parameter to be passed in the exchange In Body | | String | *userId* (common) | The user ID to use for an App User. | | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== === API Parameters (10 APIs): The Box endpoint is an API based component and has additional parameters based on which API name and API method is used. The API name and API method is located in the endpoint URI as the apiName/methodName path parameters: ---- box:apiName/methodName ---- There are 10 API names as listed in the table below: [width=""100%"",cols=""2,2,6"",options=""header""] |=== | API Name | Type | Description | *collaborations* | Producer | Provides operations to manage Box collaborations | *comments* | Producer | Provides operations to manage Box comments | *event-logs* | Producer | Provides operations to read Box enterprise (admin) event logs | *events* | Consumer | Provides operations to manage Box events | *files* | Producer | Provides operations to manage Box files | *folders* | Producer | Provides operations to manage Box folders | *groups* | Producer | Provides operations to manage Box groups | *search* | Producer | Provides operations to manage Box searches | *tasks* | Producer | Provides operations to manage Box tasks | *users* | Producer | Provides operations to manage Box users |=== Each API is documented in the following sections to come. ==== API: collaborations *Only producer is supported* The collaborations API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxCollaboration addFolderCollaboration(String folderId, com.box.sdk.BoxCollaborator collaborator, com.box.sdk.BoxCollaboration.Role role); com.box.sdk.BoxCollaboration addFolderCollaborationByEmail(String folderId, String email, com.box.sdk.BoxCollaboration.Role role); void deleteCollaboration(String collaborationId); com.box.sdk.BoxCollaboration.Info getCollaborationInfo(String collaborationId); java.util.Collection getFolderCollaborations(String folderId); com.box.sdk.BoxCollaboration updateCollaborationInfo(String collaborationId, com.box.sdk.BoxCollaboration.Info info); ---- The collaborations API is defined in the syntax as follows: ---- box:collaborations/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFolderCollaboration* | add | Add a collaboration to this folder | *addFolderCollaborationByEmail* | addByEmail | Add a collaboration to this folder | *deleteCollaboration* | delete | Delete collaboration | *getCollaborationInfo* | info | Get collaboration information | *getFolderCollaborations* | collaborations | Get information about all of the collaborations for folder | *updateCollaborationInfo* | updateInfo | Update collaboration information |=== The collaborations API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFolderCollaboration | *collaborator* | The collaborator to add | BoxCollaborator | addFolderCollaboration | *folderId* | The id of folder to add collaboration to | String | addFolderCollaboration | *role* | The role of the collaborator | Role | addFolderCollaborationByEmail | *email* | The email address of the collaborator to add | String | addFolderCollaborationByEmail | *folderId* | The id of folder to add collaboration to | String | addFolderCollaborationByEmail | *role* | The role of the collaborator | Role | deleteCollaboration | *collaborationId* | The id of comment to change | String | getCollaborationInfo | *collaborationId* | The id of collaboration | String | getFolderCollaborations | *folderId* | The id of folder to get collaborations information on | String | updateCollaborationInfo | *collaborationId* | The id of collaboration | String | updateCollaborationInfo | *info* | Collaboration information to update | Info |=== In addition to the parameters above, the collaborations API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: comments *Only producer is supported* The comments API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFile addFileComment(String fileId, String message); com.box.sdk.BoxComment changeCommentMessage(String commentId, String message); void deleteComment(String commentId); com.box.sdk.BoxComment.Info getCommentInfo(String commentId); java.util.List getFileComments(String fileId); com.box.sdk.BoxComment replyToComment(String commentId, String message); ---- The comments API is defined in the syntax as follows: ---- box:comments/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFileComment* | add | Add comment to file | *changeCommentMessage* | updateMessage | Change comment message | *deleteComment* | delete | Delete comment | *getCommentInfo* | info | Get comment information | *getFileComments* | comments | Get a list of any comments on this file | *replyToComment* | reply | Reply to a comment |=== The comments API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFileComment | *fileId* | The id of file | String | addFileComment | *message* | The comment's message | String | changeCommentMessage | *commentId* | The id of comment to change | String | changeCommentMessage | *message* | The new message for the comment | String | deleteComment | *commentId* | The id of comment to delete | String | getCommentInfo | *commentId* | The id of comment | String | getFileComments | *fileId* | The id of file | String | replyToComment | *commentId* | The id of comment to reply to | String | replyToComment | *message* | The message for the reply | String |=== In addition to the parameters above, the comments API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: event-logs *Only producer is supported* The event-logs API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.List getEnterpriseEvents(String position, java.util.Date after, java.util.Date before, com.box.sdk.BoxEvent.Type[] types); ---- The event-logs API is defined in the syntax as follows: ---- box:event-logs/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *getEnterpriseEvents* | events | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The event-logs API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | getEnterpriseEvents | *after* | The lower bound on the timestamp of the events returned | Date | getEnterpriseEvents | *before* | The upper bound on the timestamp of the events returned | Date | getEnterpriseEvents | *position* | *Optional* The starting position of the event stream. May be null in which case all events within bounds returned. | String | getEnterpriseEvents | *types* | *Optional* An optional list of event types to filter by | Type[] |=== In addition to the parameters above, the event-logs API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: events *Only consumer is supported* The events API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void listen(com.box.sdk.EventListener listener, Long startingPosition); ---- The events API is defined in the syntax as follows: ---- box:events/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *listen* | | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The events API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | listen | *startingPosition* | *Optional* The starting position of the event stream | Long |=== In addition to the parameters above, the events API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: files *Only producer is supported* The files API has 22 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void checkUpload(String fileName, String parentFolderId, Long size); com.box.sdk.BoxFile copyFile(String fileId, String destinationFolderId, String newName); com.box.sdk.Metadata createFileMetadata(String fileId, com.box.sdk.Metadata metadata, String typeName); com.box.sdk.BoxSharedLink createFileSharedLink(String fileId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFile(String fileId); void deleteFileMetadata(String fileId); void deleteFileVersion(String fileId, Integer version); java.io.OutputStream downloadFile(String fileId, java.io.OutputStream output, Long rangeStart, Long rangeEnd, com.box.sdk.ProgressListener listener); java.io.OutputStream downloadPreviousFileVersion(String fileId, Integer version, java.io.OutputStream output, com.box.sdk.ProgressListener listener); java.net.URL getDownloadURL(String fileId); com.box.sdk.BoxFile.Info getFileInfo(String fileId, String[] fields); com.box.sdk.Metadata getFileMetadata(String fileId, String typeName); java.net.URL getFilePreviewLink(String fileId); byte[] getFileThumbnail(String fileId, com.box.sdk.BoxFile.ThumbnailFileType fileType, Integer minWidth, Integer minHeight, Integer maxWidth, Integer maxHeight); java.util.Collection getFileVersions(String fileId); com.box.sdk.BoxFile moveFile(String fileId, String destinationFolderId, String newName); com.box.sdk.BoxFileVersion promoteFileVersion(String fileId, Integer version); com.box.sdk.BoxFile renameFile(String fileId, String newFileName); com.box.sdk.BoxFile updateFileInfo(String fileId, com.box.sdk.BoxFile.Info info); com.box.sdk.Metadata updateFileMetadata(String fileId, com.box.sdk.Metadata metadata); com.box.sdk.BoxFile uploadFile(String parentFolderId, java.io.InputStream content, String fileName, java.util.Date created, java.util.Date modified, Long size, Boolean check, com.box.sdk.ProgressListener listener); com.box.sdk.BoxFile uploadNewFileVersion(String fileId, java.io.InputStream fileContent, java.util.Date modified, Long fileSize, com.box.sdk.ProgressListener listener); ---- The files API is defined in the syntax as follows: ---- box:files/methodName?[parameters] ---- The 22 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *checkUpload* | canUpload | Does a pre-verification before upload, to check if the filename already exists or if there is permission to upload | *copyFile* | copy | Copy file to destination folder while optionally giving it a new name | *createFileMetadata* | createMetadata | Create metadata for file in either the global properties template or the specified template type | *createFileSharedLink* | link | Create a shared link to file | *deleteFile* | delete | Delete the file | *deleteFileMetadata* | deleteMetadata | Delete the file properties metadata | *deleteFileVersion* | deleteVersion | Delete a file version | *downloadFile* | download | Download a file | *downloadPreviousFileVersion* | downloadVersion | Download a previous version of file | *getDownloadURL* | url | Get an expiring URL for downloading a file directly from Box | *getFileInfo* | info | Get file information | *getFileMetadata* | metadata | Gets the file properties metadata | *getFilePreviewLink* | | Get an expiring URL for creating an embedded preview session | *getFileThumbnail* | thumbnail | Retrieves a thumbnail, or smaller image representation, of this file | *getFileVersions* | versions | Get any previous versions of file | *moveFile* | move | Move file to destination folder while optionally giving it a new name | *promoteFileVersion* | promoteVersion | Promote a previous version of file | *renameFile* | rename | Rename file giving it the name newName | *updateFileInfo* | updateInfo | Update file information | *updateFileMetadata* | updateMetadata | Update the file properties metadata | *uploadFile* | upload | Upload a new file to parent folder | *uploadNewFileVersion* | uploadVersion | Upload a new version of file |=== The files API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | checkUpload | *fileName* | The name to give the uploaded file | String | checkUpload | *parentFolderId* | The id of parent folder | String | checkUpload | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | copyFile | *destinationFolderId* | The id of the destination folder | String | copyFile | *fileId* | The id of file to copy | String | copyFile | *newName* | *Optional* The new name for copied file; if newName is null, the copied file has same name as the original. | String | createFileMetadata | *fileId* | The id of the file to create metadata for | String | createFileMetadata | *metadata* | The new metadata values | Metadata | createFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | createFileSharedLink | *access* | The access level of the shared link | Access | createFileSharedLink | *fileId* | The id of the file to create shared link on | String | createFileSharedLink | *permissions* | *Optional* The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFileSharedLink | *unshareDate* | *Optional* The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFile | *fileId* | The id of file to delete | String | deleteFileMetadata | *fileId* | The id of file to delete | String | deleteFileVersion | *fileId* | The id of file with version to delete | String | deleteFileVersion | *version* | The version of file to delete; initial version of file has value of 0, second version of file is 1 and so on. | Integer | downloadFile | *fileId* | The id of file | String | downloadFile | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadFile | *output* | The stream to which the file contents will be written | OutputStream | downloadFile | *rangeEnd* | *Optional* The byte offset in file at which to stop the download; if null the entire contents of file will be downloaded. | Long | downloadFile | *rangeStart* | *Optional* The byte offset in file at which to start the download; if null the entire contents of file will be downloaded. | Long | downloadPreviousFileVersion | *fileId* | The id of file | String | downloadPreviousFileVersion | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadPreviousFileVersion | *output* | The stream to which the version contents will be written | OutputStream | downloadPreviousFileVersion | *version* | The version of file to download; initial version of file has value of 0, second version of file is 1 and so on. | Integer | getDownloadURL | *fileId* | The id of file | String | getFileInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFileInfo | *fileId* | The id of file | String | getFileMetadata | *fileId* | The id of the file to retrieve metadata for | String | getFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | getFilePreviewLink | *fileId* | The id of the file to get preview link on | String | getFileThumbnail | *fileId* | The id of the file to get thumbnail | String | getFileThumbnail | *fileType* | Either PNG of JPG | ThumbnailFileType | getFileThumbnail | *maxHeight* | Maximum height | Integer | getFileThumbnail | *maxWidth* | Maximum width | Integer | getFileThumbnail | *minHeight* | Minimum height | Integer | getFileThumbnail | *minWidth* | Minimum width | Integer | getFileVersions | *fileId* | The id of file | String | moveFile | *destinationFolderId* | The id of the destination folder | String | moveFile | *fileId* | The id of file to move | String | moveFile | *newName* | *Optional* The new name of moved file; if newName is null, the moved file has same name as the original. | String | promoteFileVersion | *fileId* | The id of file | String | promoteFileVersion | *version* | The version of file to promote; initial version of file has value of 0, second version of file is 1 and so on. | Integer | renameFile | *fileId* | The id of file to rename | String | renameFile | *newFileName* | The new name of file | String | updateFileInfo | *fileId* | The id of file to update | String | updateFileInfo | *info* | The updated information | Info | updateFileMetadata | *fileId* | The id of file to delete | String | updateFileMetadata | *metadata* | The new metadata values | Metadata | uploadFile | *check* | *Optional* If the file name is already used, call the uploadNewVersion instead. | Boolean | uploadFile | *content* | A stream containing contents of the file to upload | InputStream | uploadFile | *created* | *Optional* The content created date that will be given to the uploaded file | Date | uploadFile | *fileName* | The name to give the uploaded file | String | uploadFile | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadFile | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date | uploadFile | *parentFolderId* | The id of parent folder | String | uploadFile | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *fileContent* | A stream containing contents of the file to upload | InputStream | uploadNewFileVersion | *fileId* | The id of file | String | uploadNewFileVersion | *fileSize* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadNewFileVersion | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date |=== In addition to the parameters above, the files API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: folders *Only producer is supported* The folders API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFolder copyFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String folderName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String[] path); com.box.sdk.BoxSharedLink createFolderSharedLink(String folderId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFolder(String folderId); com.box.sdk.BoxFolder getFolder(String[] path); com.box.sdk.BoxFolder.Info getFolderInfo(String folderId, String[] fields); java.util.Collection getFolderItems(String folderId, Long offset, Long limit, String[] fields); com.box.sdk.BoxFolder moveFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder renameFolder(String folderId, String newFolderName); com.box.sdk.BoxFolder updateFolderInfo(String folderId, com.box.sdk.BoxFolder.Info info); ---- The folders API is defined in the syntax as follows: ---- box:folders/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *copyFolder* | copy | Copy folder to destination folder while optionally giving it a new name | *createFolder* | create | Create a folder specified by path from parent folder with given parentFolderId, creating intermediate directories as required | *createFolderSharedLink* | link | Create a shared link to folder | *deleteFolder* | delete | Delete folder | *getFolder* | folder | Return the Box folder referenced by path | *getFolderInfo* | info | Get folder information | *getFolderItems* | items | Returns a specific range of child items in folder and specifies which fields of each item to retrieve | *moveFolder* | move | Move folder to destination folder while optionally giving it a new name | *renameFolder* | rename | Rename folder giving it the name newName | *updateFolderInfo* | updateInfo | Update folder information |=== The folders API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | copyFolder | *destinationFolderId* | The id of the destination folder | String | copyFolder | *folderId* | The id of folder to copy | String | copyFolder | *newName* | *Optional* The new name for copied folder; if newName is null, the copied folder has same name as the original. | String | createFolder | *folderName* | The name of created folder | String | createFolder | *parentFolderId* | The id of parent folder | String | createFolder | *path* | Sequence of Box folder names from parent folder to returned folder | String[] | createFolderSharedLink | *access* | The access level of the shared link | Access | createFolderSharedLink | *folderId* | The id of folder to create shared link on | String | createFolderSharedLink | *permissions* | The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFolderSharedLink | *unshareDate* | The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFolder | *folderId* | The id of folder to delete | String | getFolder | *path* | Sequence of Box folder names from root folder to returned folder | String[] | getFolderInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFolderInfo | *folderId* | The id of folder | String | getFolderItems | *fields* | *Optional* The item fields to retrieve for each child item; if null all item fields are retrieved. | String[] | getFolderItems | *folderId* | The id of folder | String | getFolderItems | *limit* | *Optional* The maximum number of children to retrieve after the offset; if null all child items are retrieved. | Long | getFolderItems | *offset* | *Optional* The index of first child item to retrieve; if null all child items are retrieved. | Long | moveFolder | *destinationFolderId* | The id of the destination folder | String | moveFolder | *folderId* | The id of folder to move | String | moveFolder | *newName* | *Optional* The new name of moved folder; if newName is null, the moved folder has same name as the original. | String | renameFolder | *folderId* | The id of folder to rename | String | renameFolder | *newFolderName* | The new name of folder | String | updateFolderInfo | *folderId* | The id of folder to update | String | updateFolderInfo | *info* | The updated information | Info |=== In addition to the parameters above, the folders API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: groups *Only producer is supported* The groups API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxGroupMembership addGroupMembership(String groupId, String userId, com.box.sdk.BoxGroupMembership.Role role); com.box.sdk.BoxGroup createGroup(String name, String provenance, String externalSyncIdentifier, String description, String invitabilityLevel, String memberViewabilityLevel); void deleteGroup(String groupId); void deleteGroupMembership(String groupMembershipId); com.box.sdk.BoxGroup.Info getGroupInfo(String groupId); com.box.sdk.BoxGroupMembership.Info getGroupMembershipInfo(String groupMembershipId); java.util.Collection getGroupMemberships(String groupId); com.box.sdk.BoxGroup updateGroupInfo(String groupId, com.box.sdk.BoxGroup.Info groupInfo); com.box.sdk.BoxGroupMembership updateGroupMembershipInfo(String groupMembershipId, com.box.sdk.BoxGroupMembership.Info info); ---- The groups API is defined in the syntax as follows: ---- box:groups/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addGroupMembership* | addMembership | Add a member to group with the specified role | *createGroup* | create | Create a new group with a specified name and optional additional parameters | *deleteGroup* | delete | Delete group | *deleteGroupMembership* | deleteMembership | Delete group membership | *getGroupInfo* | info | Get group information | *getGroupMembershipInfo* | membershipInfo | Get group membership information | *getGroupMemberships* | memberships | Get information about all of the group memberships for this group | *updateGroupInfo* | | Update group information | *updateGroupMembershipInfo* | updateMembershipInfo | Update group membership information |=== The groups API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addGroupMembership | *groupId* | The id of group | String | addGroupMembership | *role* | *Optional* The role of the user in this group. Can be null to assign the default role. | Role | addGroupMembership | *userId* | The id of user to be added to group | String | createGroup | *description* | *Optional* The description of the new group | String | createGroup | *externalSyncIdentifier* | *Optional* The external_sync_identifier of the new group | String | createGroup | *invitabilityLevel* | *Optional* The invitibility_level of the new group | String | createGroup | *memberViewabilityLevel* | *Optional* The member_viewability_level of the new group | String | createGroup | *name* | The name of the new group | String | createGroup | *provenance* | *Optional* The provenance of the new group | String | deleteGroup | *groupId* | The id of group to delete | String | deleteGroupMembership | *groupMembershipId* | The id of group membership to delete | String | getGroupInfo | *groupId* | The id of group | String | getGroupMembershipInfo | *groupMembershipId* | The id of group membership | String | getGroupMemberships | *groupId* | The id of group | String | updateGroupInfo | *groupId* | The id of group to update | String | updateGroupInfo | *groupInfo* | The updated information | Info | updateGroupMembershipInfo | *groupMembershipId* | The id of group membership to update | String | updateGroupMembershipInfo | *info* | The updated information | Info |=== In addition to the parameters above, the groups API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: search *Only producer is supported* The search API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.Collection searchFolder(String folderId, String query); ---- The search API is defined in the syntax as follows: ---- box:search/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *searchFolder* | search | Search folder and all descendant folders using the given query |=== The search API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | searchFolder | *folderId* | The id of folder searched | String | searchFolder | *query* | The search query | String |=== In addition to the parameters above, the search API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: tasks *Only producer is supported* The tasks API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxTask addAssignmentToTask(String taskId, com.box.sdk.BoxUser assignTo); com.box.sdk.BoxTask addFileTask(String fileId, com.box.sdk.BoxTask.Action action, java.util.Date dueAt, String message); void deleteTask(String taskId); void deleteTaskAssignment(String taskAssignmentId); java.util.List getFileTasks(String fileId); com.box.sdk.BoxTaskAssignment.Info getTaskAssignmentInfo(String taskAssignmentId); java.util.List getTaskAssignments(String taskId); com.box.sdk.BoxTask.Info getTaskInfo(String taskId); com.box.sdk.BoxTask updateTaskInfo(String taskId, com.box.sdk.BoxTask.Info info); ---- The tasks API is defined in the syntax as follows: ---- box:tasks/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addAssignmentToTask* | addAssignment | Add assignment for task | *addFileTask* | add | Add task to file | *deleteTask* | delete | Delete task | *deleteTaskAssignment* | deleteAssignment | Delete task assignment | *getFileTasks* | tasks | Get a list of any tasks on file | *getTaskAssignmentInfo* | assignmentInfo | Get task assignment information | *getTaskAssignments* | assignments | Get a list of any assignments for task | *getTaskInfo* | info | Get task information | *updateTaskInfo* | updateInfo | Update task information |=== The tasks API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addAssignmentToTask | *assignTo* | The user to assign to task | BoxUser | addAssignmentToTask | *taskId* | The id of task to add assignment for | String | addFileTask | *action* | The action the task assignee will be prompted to do | Action | addFileTask | *dueAt* | The day at which this task is due | Date | addFileTask | *fileId* | The id of file to add task to | String | addFileTask | *message* | *Optional* An optional message to include with the task | String | deleteTask | *taskId* | The id of task to delete | String | deleteTaskAssignment | *taskAssignmentId* | The id of task assignment to delete | String | getFileTasks | *fileId* | The id of file | String | getTaskAssignmentInfo | *taskAssignmentId* | The id of task assignment | String | getTaskAssignments | *taskId* | The id of task | String | getTaskInfo | *taskId* | The id of task | String | updateTaskInfo | *info* | The updated information | Info | updateTaskInfo | *taskId* | The id of task | String |=== In addition to the parameters above, the tasks API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: users *Only producer is supported* The users API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.EmailAlias addUserEmailAlias(String userId, String email); com.box.sdk.BoxUser createAppUser(String name, com.box.sdk.CreateUserParams params); com.box.sdk.BoxUser createEnterpriseUser(String login, String name, com.box.sdk.CreateUserParams params); void deleteUser(String userId, boolean notifyUser, boolean force); void deleteUserEmailAlias(String userId, String emailAliasId); java.util.List getAllEnterpriseOrExternalUsers(String filterTerm, String[] fields); java.util.Collection getUserEmailAlias(String userId); com.box.sdk.BoxUser.Info getUserInfo(String userId); com.box.sdk.BoxFolder.Info moveFolderToUser(String userId, String sourceUserId); com.box.sdk.BoxUser updateUserInfo(String userId, com.box.sdk.BoxUser.Info info); ---- The users API is defined in the syntax as follows: ---- box:users/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addUserEmailAlias* | addEmailAlias | Add a new email alias to user's account | *createAppUser* | create | Provision a new app user in an enterprise with additional user information using Box Developer Edition | *createEnterpriseUser* | create | Provision a new user in an enterprise with additional user information | *deleteUser* | delete | Delete user from an enterprise account | *deleteUserEmailAlias* | deleteEmailAlias | Delete an email alias from user's account | *getAllEnterpriseOrExternalUsers* | users | Get any managed users that match the filter term as well as any external users that match the filter term | *getUserEmailAlias* | emailAlias | Get a collection of all the email aliases for user | *getUserInfo* | info | Get user information | *moveFolderToUser* | | Move root folder for specified user to current user | *updateUserInfo* | updateInfo | Update user information |=== The users API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addUserEmailAlias | *email* | The email address to add as an alias | String | addUserEmailAlias | *userId* | The id of user | String | createAppUser | *name* | The name of the user | String | createAppUser | *params* | *Optional* Additional user information | CreateUserParams | createEnterpriseUser | *login* | The email address the user will use to login | String | createEnterpriseUser | *name* | The name of the user | String | createEnterpriseUser | *params* | *Optional* Additional user information | CreateUserParams | deleteUser | *force* | Whether or not this user should be deleted even if they still own files | Boolean | deleteUser | *notifyUser* | Whether or not to send an email notification to the user that their account has been deleted | Boolean | deleteUser | *userId* | The id of user to delete | String | deleteUserEmailAlias | *emailAliasId* | The id of the email alias to delete | String | deleteUserEmailAlias | *userId* | The id of user | String | getAllEnterpriseOrExternalUsers | *fields* | *Optional* The fields to retrieve. Leave this out for the standard fields. | String[] | getAllEnterpriseOrExternalUsers | *filterTerm* | *Optional* The filter term to lookup users by (login for external, login or name for managed); if null all managed users are returned. | String | getUserEmailAlias | *userId* | The id of user | String | getUserInfo | *userId* | The id of user | String | moveFolderToUser | *sourceUserId* | The user id of the user whose files will be the source for this operation | String | moveFolderToUser | *userId* | The id of user | String | updateUserInfo | *info* | The updated information | Info | updateUserInfo | *userId* | The id of user to update | String |=== In addition to the parameters above, the users API can also use from the 21 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. // endpoint options: END == Samples The following route uploads new files to the user's root folder: [source,java] ---- from(""file:..."") .to(""box://files/upload/inBody=fileUploadRequest""); ---- The following route polls user's account for updates: [source,java] ---- from(""box://events/listen?startingPosition=-1"") .to(""bean:blah""); ---- The following route uses a producer with dynamic header options. The *fileId* property has the Box file id and the *output* property has the output stream of the file contents, so they are assigned to the *CamelBox.fileId* header and *CamelBox.output* header respectively as follows: [source,java] ---- from(""direct:foo"") .setHeader(""CamelBox.fileId"", header(""fileId"")) .setHeader(""CamelBox.output"", header(""output"")) .to(""box://files/download"") .to(""file://...""); ---- === More information See more details at the Box API reference: https://developer.box.com/reference include::camel-spring-boot::page$box-starter.adoc[] ",12316,True,2581.539257626845,median "#include ""envoy/extensions/filters/http/grpc_json_transcoder/v3/transcoder.pb.h"" #include ""common/grpc/codec.h"" #include ""common/grpc/common.h"" #include ""common/http/message_impl.h"" #include ""common/protobuf/protobuf.h"" #include ""extensions/filters/http/well_known_names.h"" #include ""test/integration/http_integration.h"" #include ""test/mocks/http/mocks.h"" #include ""test/proto/bookstore.pb.h"" #include ""test/test_common/utility.h"" #include ""absl/strings/match.h"" #include ""gtest/gtest.h"" using Envoy::Protobuf::TextFormat; using Envoy::ProtobufUtil::Status; using Envoy::ProtobufUtil::error::Code; using Envoy::ProtobufWkt::Empty; namespace Envoy { namespace { // A magic header value which marks header as not expected. constexpr char UnexpectedHeaderValue[] = ""Unexpected header value""; class GrpcJsonTranscoderIntegrationTest : public testing::TestWithParam, public HttpIntegrationTest { public: GrpcJsonTranscoderIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()) {} void SetUp() override { setUpstreamProtocol(FakeHttpConnection::Type::HTTP2); const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor : ""{}"" services : ""bookstore.Bookstore"" )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); } protected: template void testTranscoding(Http::RequestHeaderMap&& request_headers, const std::string& request_body, const std::vector& expected_grpc_request_messages, const std::vector& grpc_response_messages, const Status& grpc_status, Http::HeaderMap&& expected_response_headers, const std::string& expected_response_body, bool full_response = true, bool always_send_trailers = false, const std::string expected_upstream_request_body = """", bool expect_connection_to_upstream = true, bool expect_response_complete = true) { codec_client_ = makeHttpConnection(lookupPort(""http"")); IntegrationStreamDecoderPtr response; if (!request_body.empty()) { auto encoder_decoder = codec_client_->startRequest(request_headers); request_encoder_ = &encoder_decoder.first; response = std::move(encoder_decoder.second); Buffer::OwnedImpl body(request_body); codec_client_->sendData(*request_encoder_, body, true); } else { response = codec_client_->makeHeaderOnlyRequest(request_headers); } if (expect_connection_to_upstream) { ASSERT_TRUE( fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); } if (!expected_grpc_request_messages.empty() || !expected_upstream_request_body.empty()) { ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_TRUE(upstream_request_->waitForEndStream(*dispatcher_)); std::string dump; for (char ch : upstream_request_->body().toString()) { dump += std::to_string(int(ch)); dump += "" ""; } if (!expected_grpc_request_messages.empty()) { Grpc::Decoder grpc_decoder; std::vector frames; ASSERT_TRUE(grpc_decoder.decode(upstream_request_->body(), frames)) << dump; EXPECT_EQ(expected_grpc_request_messages.size(), frames.size()); for (size_t i = 0; i < expected_grpc_request_messages.size(); ++i) { RequestType actual_message; if (frames[i].length_ > 0) { ASSERT_TRUE(actual_message.ParseFromString(frames[i].data_->toString())); } RequestType expected_message; ASSERT_TRUE( TextFormat::ParseFromString(expected_grpc_request_messages[i], &expected_message)); EXPECT_THAT(actual_message, ProtoEq(expected_message)); } } if (!expected_upstream_request_body.empty()) { EXPECT_EQ(expected_upstream_request_body, upstream_request_->body().toString()); } Http::TestResponseHeaderMapImpl response_headers; response_headers.setStatus(200); response_headers.setContentType(""application/grpc""); if (grpc_response_messages.empty() && !always_send_trailers) { response_headers.setGrpcStatus(static_cast(grpc_status.error_code())); response_headers.setGrpcMessage(absl::string_view(grpc_status.error_message().data(), grpc_status.error_message().size())); upstream_request_->encodeHeaders(response_headers, true); } else { response_headers.addCopy(Http::LowerCaseString(""trailer""), ""Grpc-Status""); response_headers.addCopy(Http::LowerCaseString(""trailer""), ""Grpc-Message""); upstream_request_->encodeHeaders(response_headers, false); for (const auto& response_message_str : grpc_response_messages) { ResponseType response_message; EXPECT_TRUE(TextFormat::ParseFromString(response_message_str, &response_message)); auto buffer = Grpc::Common::serializeToGrpcFrame(response_message); upstream_request_->encodeData(*buffer, false); } Http::TestResponseTrailerMapImpl response_trailers; response_trailers.setGrpcStatus(static_cast(grpc_status.error_code())); response_trailers.setGrpcMessage(absl::string_view(grpc_status.error_message().data(), grpc_status.error_message().size())); upstream_request_->encodeTrailers(response_trailers); } EXPECT_TRUE(upstream_request_->complete()); } ASSERT_TRUE(response->waitForEndStream()); EXPECT_EQ(response->complete(), expect_response_complete); if (response->headers().get(Http::LowerCaseString(""transfer-encoding"")).empty() || !absl::StartsWith(response->headers() .get(Http::LowerCaseString(""transfer-encoding""))[0] ->value() .getStringView(), ""chunked"")) { EXPECT_TRUE(response->headers().get(Http::LowerCaseString(""trailer"")).empty()); } expected_response_headers.iterate( [response = response.get()](const Http::HeaderEntry& entry) -> Http::HeaderMap::Iterate { Http::LowerCaseString lower_key{std::string(entry.key().getStringView())}; if (entry.value() == UnexpectedHeaderValue) { EXPECT_TRUE(response->headers().get(lower_key).empty()); } else { if (response->headers().get(lower_key).empty()) { ADD_FAILURE() << ""Header "" << lower_key.get() << "" not found.""; } else { EXPECT_EQ(entry.value().getStringView(), response->headers().get(lower_key)[0]->value().getStringView()); } } return Http::HeaderMap::Iterate::Continue; }); if (!expected_response_body.empty()) { if (full_response) { EXPECT_EQ(expected_response_body, response->body()); } else { EXPECT_TRUE(absl::StartsWith(response->body(), expected_response_body)); } } codec_client_->close(); ASSERT_TRUE(fake_upstream_connection_->close()); ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect()); } // override configuration on per-route basis void overrideConfig(const std::string& json_config) { envoy::extensions::filters::http::grpc_json_transcoder::v3::GrpcJsonTranscoder per_route_config; TestUtility::loadFromJson(json_config, per_route_config); ConfigHelper::HttpModifierFunction modifier = [per_route_config]( envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& cfg) { auto* config = cfg.mutable_route_config() ->mutable_virtual_hosts() ->Mutable(0) ->mutable_typed_per_filter_config(); (*config)[Extensions::HttpFilters::HttpFilterNames::get().GrpcJsonTranscoder].PackFrom( per_route_config); }; config_helper_.addConfigModifier(modifier); } }; INSTANTIATE_TEST_SUITE_P(IpVersions, GrpcJsonTranscoderIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryPost) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({""theme"": ""Children""})"", {R""(shelf { theme: ""Children"" })""}, {R""(id: 20 theme: ""Children"" )""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""30""}, {""grpc-status"", ""0""}}, R""({""id"":""20"",""theme"":""Children""})""); } TEST_P(GrpcJsonTranscoderIntegrationTest, QueryParams) { HttpIntegrationTest::initialize(); // 1. Binding theme='Children' in CreateShelfRequest // Using the following HTTP template: // POST /shelves // body: shelf testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf?shelf.theme=Children""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, """", {R""(shelf { theme: ""Children"" })""}, {R""(id: 20 theme: ""Children"" )""}, Status(), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""content-type"", ""application/json""}, }, R""({""id"":""20"",""theme"":""Children""})""); // 2. Binding theme='Children' and id='999' in CreateShelfRequest testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf?shelf.id=999&shelf.theme=Children""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, """", {R""(shelf { id: 999 theme: ""Children"" })""}, {R""(id: 999 theme: ""Children"" )""}, Status(), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""content-type"", ""application/json""}, }, R""({""id"":""999"",""theme"":""Children""})""); // 3. Binding shelf=1, book= and book.title='War and Peace' in CreateBookRequest // Using the following HTTP template: // POST /shelves/{shelf}/books // body: book testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""PUT""}, {"":path"", ""/shelves/1/books?book.title=War%20and%20Peace""}, {"":authority"", ""host""}}, R""({""author"" : ""Leo Tolstoy""})"", {R""(shelf: 1 book { author: ""Leo Tolstoy"" title: ""War and Peace"" })""}, {R""(id: 3 author: ""Leo Tolstoy"" title: ""War and Peace"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, R""({""id"":""3"",""author"":""Leo Tolstoy"",""title"":""War and Peace""})""); // 4. Binding shelf=1, book.author='Leo Tolstoy' and book.title='War and Peace' in // CreateBookRequest // Using the following HTTP template: // POST /shelves/{shelf}/books // body: book testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""PUT""}, {"":path"", ""/shelves/1/books?book.author=Leo%20Tolstoy&book.title=War%20and%20Peace""}, {"":authority"", ""host""}}, """", {R""(shelf: 1 book { author: ""Leo Tolstoy"" title: ""War and Peace"" })""}, {R""(id: 3 author: ""Leo Tolstoy"" title: ""War and Peace"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, R""({""id"":""3"",""author"":""Leo Tolstoy"",""title"":""War and Peace""})""); // 5. Test URL decoding. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""PUT""}, {"":path"", ""/shelves/1/books?book.title=War%20%26%20Peace""}, {"":authority"", ""host""}}, R""({""author"" : ""Leo Tolstoy""})"", {R""(shelf: 1 book { author: ""Leo Tolstoy"" title: ""War & Peace"" })""}, {R""(id: 3 author: ""Leo Tolstoy"" title: ""War & Peace"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, R""({""id"":""3"",""author"":""Leo Tolstoy"",""title"":""War & Peace""})""); // 6. Binding all book fields through query params. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""PUT""}, {"":path"", ""/shelves/1/books?book.id=999&book.author=Leo%20Tolstoy&book.title=War%20and%20Peace""}, {"":authority"", ""host""}}, """", {R""(shelf: 1 book { id : 999 author: ""Leo Tolstoy"" title: ""War and Peace"" })""}, {R""(id: 999 author: ""Leo Tolstoy"" title: ""War and Peace"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, R""({""id"":""999"",""author"":""Leo Tolstoy"",""title"":""War and Peace""})""); // 7. Binding shelf=3, book= and the repeated field book.quote with // two values (""Winter is coming"" and ""Hold the door"") in CreateBookRequest. // These values should be added to the repeated field in addition to what is // translated in the body. // Using the following HTTP template: // POST /shelves/{shelf}/books // body: book std::string reqBody = R""({""id"":""999"",""author"":""George R.R. Martin"",""title"":""A Game of Thrones"",)"" R""(""quotes"":[""A girl has no name"",""A very small man can cast a very large shadow""]})""; std::string grpcResp = R""(id : 999 author: ""George R.R. Martin"" title: ""A Game of Thrones"" quotes: ""A girl has no name"" quotes : ""A very small man can cast a very large shadow"" quotes: ""Winter is coming"" quotes : ""Hold the door"")""; std::string expectGrpcRequest = absl::StrCat(""shelf: 1 book {"", grpcResp, ""}""); std::string respBody = R""({""id"":""999"",""author"":""George R.R. Martin"",""title"":""A Game of Thrones"",""quotes"":[""A girl has no name"")"" R""(,""A very small man can cast a very large shadow"",""Winter is coming"",""Hold the door""]})""; testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""PUT""}, {"":path"", ""/shelves/1/books?book.quotes=Winter%20is%20coming&book.quotes=Hold%20the%20door""}, {"":authority"", ""host""}}, reqBody, {expectGrpcRequest}, {grpcResp}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, respBody); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryGet) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves""}, {"":authority"", ""host""}}, """", {""""}, {R""(shelves { id: 20 theme: ""Children"" } shelves { id: 1 theme: ""Foo"" } )""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""69""}, {""grpc-status"", ""0""}}, R""({""shelves"":[{""id"":""20"",""theme"":""Children""},{""id"":""1"",""theme"":""Foo""}]})""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryGetHttpBody) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/index""}, {"":authority"", ""host""}}, """", {""""}, {R""(content_type: ""text/html"" data: ""

Hello!

"" )""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""text/html""}, {""content-length"", ""15""}, {""grpc-status"", ""0""}}, R""(

Hello!

)""); } TEST_P(GrpcJsonTranscoderIntegrationTest, StreamGetHttpBody) { HttpIntegrationTest::initialize(); // 1. Normal streaming get testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/indexStream""}, {"":authority"", ""host""}}, """", {""""}, {R""(content_type: ""text/html"" data: ""

Hello!

"")"", R""(content_type: ""text/plain"" data: ""Hello!"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""text/html""}}, R""(

Hello!

)"" R""(Hello!)""); // 2. Empty response (trailers only) from streaming backend, with a gRPC error. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/indexStream""}, {"":authority"", ""host""}}, """", {""""}, {}, Status(Code::NOT_FOUND, ""Not Found""), Http::TestResponseHeaderMapImpl{{"":status"", ""404""}, {""content-type"", ""application/json""}}, """"); } TEST_P(GrpcJsonTranscoderIntegrationTest, StreamGetHttpBodyMultipleFramesInData) { HttpIntegrationTest::initialize(); // testTranscoding() does not provide grpc multiframe support. // Since this is one-off it does not make sense to even more // complicate this function. // // Make request to gRPC upstream codec_client_ = makeHttpConnection(lookupPort(""http"")); auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/indexStream""}, {"":authority"", ""host""}, }); waitForNextUpstreamRequest(); // Send multi-framed gRPC response // Headers Http::TestResponseHeaderMapImpl response_headers; response_headers.setStatus(200); response_headers.setContentType(""application/grpc""); upstream_request_->encodeHeaders(response_headers, false); // Payload google::api::HttpBody grpcMsg; EXPECT_TRUE(TextFormat::ParseFromString(R""(content_type: ""text/plain"" data: ""Hello"")"", &grpcMsg)); Buffer::OwnedImpl response_buffer; for (size_t i = 0; i < 3; i++) { auto frame = Grpc::Common::serializeToGrpcFrame(grpcMsg); response_buffer.add(*frame); } upstream_request_->encodeData(response_buffer, false); // Trailers Http::TestResponseTrailerMapImpl response_trailers; auto grpc_status = Status(); response_trailers.setGrpcStatus(static_cast(grpc_status.error_code())); response_trailers.setGrpcMessage( absl::string_view(grpc_status.error_message().data(), grpc_status.error_message().size())); upstream_request_->encodeTrailers(response_trailers); EXPECT_TRUE(upstream_request_->complete()); // Wait for complete / check body to have 3 frames joined ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(response->complete()); EXPECT_EQ(response->body(), ""HelloHelloHello""); } TEST_P(GrpcJsonTranscoderIntegrationTest, StreamGetHttpBodyFragmented) { HttpIntegrationTest::initialize(); // Make request to gRPC upstream codec_client_ = makeHttpConnection(lookupPort(""http"")); auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/indexStream""}, {"":authority"", ""host""}, }); waitForNextUpstreamRequest(); // Send fragmented gRPC response // Headers Http::TestResponseHeaderMapImpl response_headers; response_headers.setStatus(200); response_headers.setContentType(""application/grpc""); upstream_request_->encodeHeaders(response_headers, false); // Fragmented payload google::api::HttpBody http_body; http_body.set_content_type(""text/plain""); http_body.set_data(std::string(1024, 'a')); // Fragment gRPC frame into 2 buffers equally divided Buffer::OwnedImpl fragment1; auto fragment2 = Grpc::Common::serializeToGrpcFrame(http_body); fragment1.move(*fragment2, fragment2->length() / 2); upstream_request_->encodeData(fragment1, false); upstream_request_->encodeData(*fragment2, false); // Trailers Http::TestResponseTrailerMapImpl response_trailers; auto grpc_status = Status(); response_trailers.setGrpcStatus(static_cast(grpc_status.error_code())); response_trailers.setGrpcMessage( absl::string_view(grpc_status.error_message().data(), grpc_status.error_message().size())); upstream_request_->encodeTrailers(response_trailers); EXPECT_TRUE(upstream_request_->complete()); // Wait for complete ASSERT_TRUE(response->waitForEndStream()); EXPECT_TRUE(response->complete()); // Ensure that body was actually replaced EXPECT_EQ(response->body(), http_body.data()); // As well as content-type header auto content_type = response->headers().get(Http::LowerCaseString(""content-type"")); EXPECT_EQ(""text/plain"", content_type[0]->value().getStringView()); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryEchoHttpBody) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/echoBody?arg=oops""}, {"":authority"", ""host""}, {""content-type"", ""text/plain""}}, ""Hello!"", {R""(arg: ""oops"" nested { content { content_type: ""text/plain"" data: ""Hello!"" } })""}, {R""(content_type: ""text/html"" data: ""

Hello!

"" )""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""text/html""}, {""content-length"", ""15""}, {""grpc-status"", ""0""}}, R""(

Hello!

)""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryGetError) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/100?""}, {"":authority"", ""host""}}, """", {""shelf: 100""}, {}, Status(Code::NOT_FOUND, ""Shelf 100 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""404""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 100 Not Found""}}, """"); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryGetError1) { const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor : ""{}"" services : ""bookstore.Bookstore"" ignore_unknown_query_parameters : true )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/shelves/100?unknown=1&shelf=9999""}, {"":authority"", ""host""}}, """", {""shelf: 9999""}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""404""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """"); } // Test an upstream that returns an error in a trailer-only response. TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryErrorConvertedToJson) { const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor: ""{}"" services: ""bookstore.Bookstore"" convert_grpc_status: true )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/100""}, {"":authority"", ""host""}}, """", {""shelf: 100""}, {}, Status(Code::NOT_FOUND, ""Shelf 100 Not Found""), Http::TestResponseHeaderMapImpl{{"":status"", ""404""}, {""content-type"", ""application/json""}, {""grpc-status"", UnexpectedHeaderValue}, {""grpc-message"", UnexpectedHeaderValue}}, R""({""code"":5,""message"":""Shelf 100 Not Found""})""); } // Upstream sends headers (e.g. sends metadata), and then sends trailer with an error. TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryErrorInTrailerConvertedToJson) { const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor: ""{}"" services: ""bookstore.Bookstore"" convert_grpc_status: true )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/100""}, {"":authority"", ""host""}}, """", {""shelf: 100""}, {}, Status(Code::NOT_FOUND, ""Shelf 100 Not Found""), Http::TestResponseHeaderMapImpl{{"":status"", ""404""}, {""content-type"", ""application/json""}, {""grpc-status"", UnexpectedHeaderValue}, {""grpc-message"", UnexpectedHeaderValue}}, R""({""code"":5,""message"":""Shelf 100 Not Found""})"", true, true); } // Streaming backend returns an error in a trailer-only response. TEST_P(GrpcJsonTranscoderIntegrationTest, StreamingErrorConvertedToJson) { const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor: ""{}"" services: ""bookstore.Bookstore"" convert_grpc_status: true )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/37/books""}, {"":authority"", ""host""}}, """", {""shelf: 37""}, {}, Status(Code::NOT_FOUND, ""Shelf 37 Not Found""), Http::TestResponseHeaderMapImpl{{"":status"", ""404""}, {""content-type"", ""application/json""}, {""grpc-status"", UnexpectedHeaderValue}, {""grpc-message"", UnexpectedHeaderValue}}, R""({""code"":5,""message"":""Shelf 37 Not Found""})""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryDelete) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""DELETE""}, {"":path"", ""/shelves/456/books/123""}, {"":authority"", ""host""}}, """", {""shelf: 456 book: 123""}, {""""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""2""}, {""grpc-status"", ""0""}}, ""{}""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryPatch) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""PATCH""}, {"":path"", ""/shelves/456/books/123""}, {"":authority"", ""host""}}, R""({""author"" : ""Leo Tolstoy"", ""title"" : ""War and Peace""})"", {R""(shelf: 456 book { id: 123 author: ""Leo Tolstoy"" title: ""War and Peace"" })""}, {R""(id: 123 author: ""Leo Tolstoy"" title: ""War and Peace"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""59""}, {""grpc-status"", ""0""}}, R""({""id"":""123"",""author"":""Leo Tolstoy"",""title"":""War and Peace""})""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryCustom) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""OPTIONS""}, {"":path"", ""/shelves/456""}, {"":authority"", ""host""}}, """", {""shelf: 456""}, {""""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""2""}, {""grpc-status"", ""0""}}, ""{}""); } TEST_P(GrpcJsonTranscoderIntegrationTest, BindingAndBody) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""PUT""}, {"":path"", ""/shelves/1/books""}, {"":authority"", ""host""}}, R""({""author"" : ""Leo Tolstoy"", ""title"" : ""War and Peace""})"", {R""(shelf: 1 book { author: ""Leo Tolstoy"" title: ""War and Peace"" })""}, {R""(id: 3 author: ""Leo Tolstoy"" title: ""War and Peace"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, R""({""id"":""3"",""author"":""Leo Tolstoy"",""title"":""War and Peace""})""); } TEST_P(GrpcJsonTranscoderIntegrationTest, ServerStreamingGet) { HttpIntegrationTest::initialize(); // 1: Normal streaming get testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/1/books""}, {"":authority"", ""host""}}, """", {""shelf: 1""}, {R""(id: 1 author: ""Neal Stephenson"" title: ""Readme"")"", R""(id: 2 author: ""George R.R. Martin"" title: ""A Game of Thrones"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, R""([{""id"":""1"",""author"":""Neal Stephenson"",""title"":""Readme""})"" R""(,{""id"":""2"",""author"":""George R.R. Martin"",""title"":""A Game of Thrones""}])""); // 2: Empty response (trailers only) from streaming backend. // Response type is a valid JSON, so content type should be application/json. // Regression test for github.com/envoyproxy/envoy#5011 testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/2/books""}, {"":authority"", ""host""}}, """", {""shelf: 2""}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, ""[]""); // 3: Empty response (trailers only) from streaming backend, with a gRPC error. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/37/books""}, {"":authority"", ""host""}}, """", {""shelf: 37""}, {}, Status(Code::NOT_FOUND, ""Shelf 37 not found""), Http::TestResponseHeaderMapImpl{{"":status"", ""404""}, {""content-type"", ""application/json""}}, ""[]""); } TEST_P(GrpcJsonTranscoderIntegrationTest, StreamingPost) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/bulk/shelves""}, {"":authority"", ""host""}}, R""([ { ""theme"" : ""Classics"" }, { ""theme"" : ""Satire"" }, { ""theme"" : ""Russian"" }, { ""theme"" : ""Children"" }, { ""theme"" : ""Documentary"" }, { ""theme"" : ""Mystery"" }, ])"", {R""(shelf { theme: ""Classics"" })"", R""(shelf { theme: ""Satire"" })"", R""(shelf { theme: ""Russian"" })"", R""(shelf { theme: ""Children"" })"", R""(shelf { theme: ""Documentary"" })"", R""(shelf { theme: ""Mystery"" })""}, {R""(id: 3 theme: ""Classics"")"", R""(id: 4 theme: ""Satire"")"", R""(id: 5 theme: ""Russian"")"", R""(id: 6 theme: ""Children"")"", R""(id: 7 theme: ""Documentary"")"", R""(id: 8 theme: ""Mystery"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""transfer-encoding"", ""chunked""}}, R""([{""id"":""3"",""theme"":""Classics""})"" R""(,{""id"":""4"",""theme"":""Satire""})"" R""(,{""id"":""5"",""theme"":""Russian""})"" R""(,{""id"":""6"",""theme"":""Children""})"" R""(,{""id"":""7"",""theme"":""Documentary""})"" R""(,{""id"":""8"",""theme"":""Mystery""}])""); } TEST_P(GrpcJsonTranscoderIntegrationTest, InvalidJson) { HttpIntegrationTest::initialize(); // Usually the response would be // ""Unexpected token.\\n"" // ""INVALID_JSON\\n"" // ""^"" // If Envoy does a short read of the upstream connection, it may only read part of the // string ""INVALID_JSON"". Envoy will note ""Unexpected token [whatever substring is read] testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}}, R""(INVALID_JSON)"", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""400""}, {""content-type"", ""text/plain""}}, ""Unexpected token.\\nI"", false); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}}, R""({ ""theme"" : ""Children"")"", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""400""}, {""content-type"", ""text/plain""}}, ""Unexpected end of string. Expected , or } after key:value pair.\\n"" ""\\n"" ""^""); // Usually the response would be // ""Expected : between key:value pair.\\n"" // ""{ \\""theme\\"" \\""Children\\"" }\\n"" // "" ^""); // But as with INVALID_JSON Envoy may not read the full string from the upstream connection so may // generate its error based on a partial upstream response. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}}, R""({ ""theme"" ""Children"" })"", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""400""}, {""content-type"", ""text/plain""}}, ""Expected : between key:value pair.\\n"", false); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}}, R""({ ""theme"" : ""Children"" }EXTRA)"", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""400""}, {""content-type"", ""text/plain""}}, ""Parsing terminated before end of input.\\n"", false); } std::string createDeepJson(int level, bool valid) { std::string begin = R""({""k"":)""; std::string deep_val = R""(""v"")""; std::string end = R""(})""; std::string json; for (int i = 0; i < level; ++i) { absl::StrAppend(&json, begin); } if (valid) { absl::StrAppend(&json, deep_val); } for (int i = 0; i < level; ++i) { absl::StrAppend(&json, end); } return json; } std::string jsonStrToPbStrucStr(std::string json) { Envoy::ProtobufWkt::Struct message; std::string structStr; TestUtility::loadFromJson(json, message); TextFormat::PrintToString(message, &structStr); return structStr; } TEST_P(GrpcJsonTranscoderIntegrationTest, DeepStruct) { // Lower the timeout for the 408 response. config_helper_.addConfigModifier( [&](envoy::extensions::filters::network::http_connection_manager::v3::HttpConnectionManager& hcm) -> void { auto* virtual_host = hcm.mutable_route_config()->mutable_virtual_hosts(0); virtual_host->mutable_routes(0)->mutable_route()->mutable_idle_timeout()->set_seconds(5); }); HttpIntegrationTest::initialize(); // Due to the limit of protobuf util, we can only compare to level 32. std::string deepJson = createDeepJson(32, true); std::string deepProto = ""content {"" + jsonStrToPbStrucStr(deepJson) + ""}""; testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/echoStruct""}, {"":authority"", ""host""}}, deepJson, {deepProto}, {deepProto}, Status(), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""content-type"", ""application/json""}, {""grpc-status"", ""0""}}, R""({""content"":)"" + deepJson + R""(})""); // The valid deep struct is parsed successfully. // Since we didn't set a response, it will time out. // Response body is empty (not a valid JSON), so the error response is plaintext. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/echoStruct""}, {"":authority"", ""host""}}, createDeepJson(100, true), {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""408""}, {""content-type"", ""text/plain""}}, """"); // The invalid deep struct is detected. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/echoStruct""}, {"":authority"", ""host""}}, createDeepJson(100, false), {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""400""}, {""content-type"", ""text/plain""}}, ""Unexpected token.\\n"", false); } std::string createLargeJson(int level) { std::shared_ptr cur = std::make_shared(); for (int i = 0; i < level - 1; ++i) { std::shared_ptr next = std::make_shared(); ProtobufWkt::Value val = ProtobufWkt::Value(); ProtobufWkt::Value left = ProtobufWkt::Value(*cur); ProtobufWkt::Value right = ProtobufWkt::Value(*cur); val.mutable_list_value()->add_values()->Swap(&left); val.mutable_list_value()->add_values()->Swap(&right); (*next->mutable_struct_value()->mutable_fields())[""k""] = val; cur = next; } return MessageUtil::getJsonStringFromMessageOrDie(*cur, false, false); } TEST_P(GrpcJsonTranscoderIntegrationTest, LargeStruct) { HttpIntegrationTest::initialize(); // Create a 40kB json payload. std::string largeJson = createLargeJson(12); std::string largeProto = ""content {"" + jsonStrToPbStrucStr(largeJson) + ""}""; testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""POST""}, {"":path"", ""/echoStruct""}, {"":authority"", ""host""}}, largeJson, {largeProto}, {largeProto}, Status(), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""content-type"", ""application/json""}, {""grpc-status"", ""0""}}, R""({""content"":)"" + largeJson + R""(})""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnknownFieldInRequest) { // Request JSON has many fields that are unknown to the request proto message. // They are discarded. HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({""theme"": ""Children"", ""unknown1"": ""a"", ""unknown2"" : {""a"" : ""b""}, ""unknown3"" : [""a"", ""b"", ""c""]})"", {R""(shelf { theme: ""Children"" })""}, {R""(id: 20 theme: ""Children"" )""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""30""}, {""grpc-status"", ""0""}}, R""({""id"":""20"",""theme"":""Children""})""); } // Test proto to json transcoding with an unknown field in the response message. // gRPC server may use a updated proto with a new field, but Envoy transcoding // filter could use an old proto descriptor without that field. That fields is unknown // to the Envoy transcoder filter. Expected result: the unknown field is discarded, // other fields should be transcoded properly. TEST_P(GrpcJsonTranscoderIntegrationTest, UnknownResponse) { // The mocked upstream proto response message is bookstore::BigBook which has // all 3 fields. But the proto descriptor used by the Envoy transcoder filter is using // bookstore::OldBigBook which is missing the `field1` field. HttpIntegrationTest::initialize(); // The bug is ZeroCopyInputStreamImpl::Skip() which is not implemented. // In order to trigger a call to that function, the response message has to be big enough // so it is stored in multiple slices. const std::string field1_value = std::string(32 * 1024, 'O'); const std::string response_body = fmt::format(R""(field1: ""{}"" field2: ""field2_value"" field3: ""field3_value"" )"", field1_value); testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/bigbook""}, {"":authority"", ""host""}}, """", {""""}, {response_body}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""49""}, {""grpc-status"", ""0""}}, R""({""field2"":""field2_value"",""field3"":""field3_value""})""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UTF8) { HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, ""{\\""id\\"":\\""20\\"",\\""theme\\"":\\""\\xC2\\xAE\\""}"", {""shelf {id : 20 theme: \\""®\\"" }""}, {""id: 20 theme: \\""\\xC2\\xAE\\""""}, Status(), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""content-type"", ""application/json""}, {""grpc-status"", ""0""}}, R""({""id"":""20"",""theme"":""®""})""); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, ""{\\""id\\"":\\""20\\"",\\""theme\\"":\\""\\xC3\\x28\\""}"", {}, {""""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""400""}}, R""(Encountered non UTF-8 code points)"", false); } TEST_P(GrpcJsonTranscoderIntegrationTest, DisableRequestValidation) { HttpIntegrationTest::initialize(); // Transcoding does not occur from a request with the gRPC content type. // We verify the request is not transcoded because the upstream receives the same JSON body. // We verify the response is not transcoded because the HTTP status code does not match the gRPC // status. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/shelves/100""}, {"":authority"", ""host""}, {""content-type"", ""application/grpc""}}, R""({ ""theme"" : ""Children"")"", {}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """", true, false, R""({ ""theme"" : ""Children"")""); // Transcoding does not occur when unknown path is called. // HTTP Request to is passed directly to gRPC backend. // gRPC response is passed directly to HTTP client. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/unknown/path""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({ ""theme"" : ""Children"")"", {}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """", true, false, R""({ ""theme"" : ""Children"")""); // Transcoding does not occur when unknown query param is included. // HTTP Request to is passed directly to gRPC backend. // gRPC response is passed directly to HTTP client. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/shelves/100?unknown=1""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({ ""theme"" : ""Children"")"", {}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """", true, false, R""({ ""theme"" : ""Children"")""); } TEST_P(GrpcJsonTranscoderIntegrationTest, RejectUnknownMethod) { const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor : ""{}"" services : ""bookstore.Bookstore"" request_validation_options: reject_unknown_method: true )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); HttpIntegrationTest::initialize(); // Transcoding does not occur from a request with the gRPC content type, even with an unknown // path. We verify the request is not transcoded because the upstream receives the same JSON body. // We verify the response is not transcoded because the HTTP status code does not match the gRPC // status. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/unknown/path""}, {"":authority"", ""host""}, {""content-type"", ""application/grpc""}}, R""({ ""theme"" : ""Children"")"", {}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """", true, false, R""({ ""theme"" : ""Children"")""); // Transcoding does not occur when unknown path is called. // The request is rejected. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/unknown/path""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, """", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""404""}}, ""Could not resolve /unknown/path to a method."", true, false, """", false); // Transcoding does not occur when unknown query param is included. // HTTP Request to is passed directly to gRPC backend. // gRPC response is passed directly to HTTP client. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/shelves/100?unknown=1""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({ ""theme"" : ""Children"")"", {}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """", true, false, R""({ ""theme"" : ""Children"")""); } TEST_P(GrpcJsonTranscoderIntegrationTest, RejectUnknownQueryParam) { const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor : ""{}"" services : ""bookstore.Bookstore"" request_validation_options: reject_unknown_query_parameters: true )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); HttpIntegrationTest::initialize(); // Transcoding does not occur from a request with the gRPC content type, even with unknown query // params. We verify the request is not transcoded because the upstream receives the same JSON // body. We verify the response is not transcoded because the HTTP status code does not match the // gRPC status. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/shelves/100?unknown=1""}, {"":authority"", ""host""}, {""content-type"", ""application/grpc""}}, R""({ ""theme"" : ""Children"")"", {}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """", true, false, R""({ ""theme"" : ""Children"")""); // Transcoding does not occur when unknown path is called. // HTTP Request to is passed directly to gRPC backend. // gRPC response is passed directly to HTTP client. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/unknown/path""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({ ""theme"" : ""Children"")"", {}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""200""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """", true, false, R""({ ""theme"" : ""Children"")""); // Transcoding does not occur when unknown query param is included. // The request is rejected. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/shelves/100?unknown=1""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, """", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""400""}}, ""Could not find field \\""unknown\\"" in the type \\""bookstore.GetShelfRequest\\""."", true, false, """", false); } TEST_P(GrpcJsonTranscoderIntegrationTest, EnableRequestValidationIgnoreQueryParam) { const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor : ""{}"" services : ""bookstore.Bookstore"" ignore_unknown_query_parameters : true request_validation_options: reject_unknown_method: true reject_unknown_query_parameters: true )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); HttpIntegrationTest::initialize(); // When strict mode is enabled with ignore unknown query params, // the request is not rejected and transcoding occurs. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/9999?unknown=1""}, {"":authority"", ""host""}}, """", {""shelf: 9999""}, {}, Status(Code::NOT_FOUND, ""Shelf 9999 Not Found""), Http::TestResponseHeaderMapImpl{ {"":status"", ""404""}, {""grpc-status"", ""5""}, {""grpc-message"", ""Shelf 9999 Not Found""}}, """"); // Transcoding does not occur when unknown path is called. // The request is rejected, even though it has unknown query params. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""GET""}, {"":path"", ""/unknown/path?unknown=1""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, """", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""404""}}, ""Could not resolve /unknown/path to a method."", true, false, """", false); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryPostRequestExceedsBufferLimit) { // Request body is more than 8 bytes. config_helper_.setBufferLimits(2 << 20, 8); HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({""theme"" : ""Children""})"", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""413""}}, ""Request rejected because the transcoder's internal buffer size exceeds the configured "" ""limit."", true, false, """", true); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryPostResponseExceedsBufferLimit) { // Request body is less than 35 bytes. // Response body is more than 35 bytes. config_helper_.setBufferLimits(2 << 20, 35); HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({""theme"": ""Children""})"", {R""(shelf { theme: ""Children"" })""}, {R""(id: 20 theme: ""Children 0123456789 0123456789 0123456789 0123456789"" )""}, Status(), Http::TestResponseHeaderMapImpl{ {"":status"", ""500""}, {""content-type"", ""text/plain""}, {""content-length"", ""99""}}, ""Response not transcoded because the transcoder's internal buffer size exceeds the "" ""configured limit.""); } TEST_P(GrpcJsonTranscoderIntegrationTest, UnaryPostHttpBodyRequestExceedsBufferLimit) { // Request body is more than 8 bytes. config_helper_.setBufferLimits(2 << 20, 8); HttpIntegrationTest::initialize(); testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/echoRawBody""}, {"":authority"", ""host""}, {""content-type"", ""text/plain""}}, R""(hello world!)"", {}, {}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""413""}}, ""Request rejected because the transcoder's internal buffer size exceeds the configured "" ""limit."", true, false, """", true); } TEST_P(GrpcJsonTranscoderIntegrationTest, ServerStreamingGetExceedsBufferLimit) { config_helper_.setBufferLimits(2 << 20, 60); HttpIntegrationTest::initialize(); // Under limit: A single response message is less than 60 bytes. // Messages transcoded successfully. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/1/books""}, {"":authority"", ""host""}}, """", {""shelf: 1""}, {R""(id: 1 author: ""Neal Stephenson"" title: ""Readme"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, R""([{""id"":""1"",""author"":""Neal Stephenson"",""title"":""Readme""}])""); // Over limit: The server streams two response messages. Even through the transcoder // handles them independently, portions of the first message are still in the // internal buffers while the second one is processed. // // Because the headers and body is already sent, the stream is closed with // an incomplete response. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/1/books""}, {"":authority"", ""host""}}, """", {""shelf: 1""}, {R""(id: 1 author: ""Neal Stephenson"" title: ""Readme"")"", R""(id: 2 author: ""George R.R. Martin"" title: ""A Game of Thrones"")""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, // Incomplete response, not valid JSON. R""([{""id"":""1"",""author"":""Neal Stephenson"",""title"":""Readme""})"", true, false, """", true, /*expect_response_complete=*/false); } TEST_P(GrpcJsonTranscoderIntegrationTest, ServerStreamingGetUnderBufferLimit) { const int num_messages = 20; config_helper_.setBufferLimits(2 << 20, 80); HttpIntegrationTest::initialize(); // Craft multiple response messages. IF combined together, they exceed the buffer limit. std::vector grpc_response_messages; grpc_response_messages.reserve(num_messages); for (int i = 0; i < num_messages; i++) { grpc_response_messages.push_back(R""(id: 1 author: ""Neal Stephenson"" title: ""Readme"")""); } // Craft expected response. std::vector expected_json_messages; expected_json_messages.reserve(num_messages); for (int i = 0; i < num_messages; i++) { expected_json_messages.push_back(R""({""id"":""1"",""author"":""Neal Stephenson"",""title"":""Readme""})""); } std::string expected_json_response = absl::StrCat(""["", absl::StrJoin(expected_json_messages, "",""), ""]""); // Under limit: Even though multiple messages are sent from the upstream, they are transcoded // while streaming. The buffer limit is never hit. At most two messages are ever in the internal // buffers. Transcoding succeeds. testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves/1/books""}, {"":authority"", ""host""}}, """", {""shelf: 1""}, grpc_response_messages, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}}, expected_json_response); } // TODO(nareddyt): Refactor testTranscoding and add a test case for client streaming under/over // buffer limit. Will do in a separate PR to minimize diff. TEST_P(GrpcJsonTranscoderIntegrationTest, RouteDisabled) { overrideConfig(R""EOF({""services"": [], ""proto_descriptor_bin"": """"})EOF""); HttpIntegrationTest::initialize(); codec_client_ = makeHttpConnection(lookupPort(""http"")); auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves""}, {"":authority"", ""host""}}); waitForNextUpstreamRequest(); upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{"":status"", ""200""}}, true); ASSERT_TRUE(response->waitForEndStream()); ASSERT_TRUE(response->complete()); EXPECT_EQ(""200"", response->headers().Status()->value().getStringView()); }; class OverrideConfigGrpcJsonTranscoderIntegrationTest : public GrpcJsonTranscoderIntegrationTest { public: /** * Global initializer for all integration tests. */ void SetUp() override { setUpstreamProtocol(FakeHttpConnection::Type::HTTP2); // creates filter but doesn't apply it to bookstore services const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder ""proto_descriptor"": """" )EOF""; config_helper_.addFilter(filter); } }; INSTANTIATE_TEST_SUITE_P(IpVersions, OverrideConfigGrpcJsonTranscoderIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(OverrideConfigGrpcJsonTranscoderIntegrationTest, RouteOverride) { // add bookstore per-route override const std::string filter = R""EOF({{ ""services"": [""bookstore.Bookstore""], ""proto_descriptor"": ""{}"" }})EOF""; overrideConfig( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); HttpIntegrationTest::initialize(); // testing the path that's defined in bookstore.descriptor file (should work the same way // as it does when grpc filter is applied to base config) testTranscoding( Http::TestRequestHeaderMapImpl{ {"":method"", ""GET""}, {"":path"", ""/shelves""}, {"":authority"", ""host""}}, """", {""""}, {R""(shelves { id: 20 theme: ""Children"" } shelves { id: 1 theme: ""Foo"" } )""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""69""}, {""grpc-status"", ""0""}}, R""({""shelves"":[{""id"":""20"",""theme"":""Children""},{""id"":""1"",""theme"":""Foo""}]})""); }; // Tests to ensure transcoding buffer limits do not apply when the runtime feature is disabled. class BufferLimitsDisabledGrpcJsonTranscoderIntegrationTest : public GrpcJsonTranscoderIntegrationTest { public: void SetUp() override { setUpstreamProtocol(FakeHttpConnection::Type::HTTP2); const std::string filter = R""EOF( name: grpc_json_transcoder typed_config: ""@type"": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder proto_descriptor : ""{}"" services : ""bookstore.Bookstore"" )EOF""; config_helper_.addFilter( fmt::format(filter, TestEnvironment::runfilesPath(""test/proto/bookstore.descriptor""))); // Disable runtime feature. config_helper_.addRuntimeOverride( ""envoy.reloadable_features.grpc_json_transcoder_adhere_to_buffer_limits"", ""false""); } }; INSTANTIATE_TEST_SUITE_P(IpVersions, BufferLimitsDisabledGrpcJsonTranscoderIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); TEST_P(BufferLimitsDisabledGrpcJsonTranscoderIntegrationTest, UnaryPostRequestExceedsBufferLimit) { // Request body is more than 20 bytes. config_helper_.setBufferLimits(2 << 20, 20); HttpIntegrationTest::initialize(); // Transcoding succeeds. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({""theme"": ""Children 0123456789 0123456789 0123456789 0123456789""})"", {R""(shelf { theme: ""Children 0123456789 0123456789 0123456789 0123456789"" })""}, {R""(id: 1)""}, Status(), Http::TestResponseHeaderMapImpl{{"":status"", ""200""}, {""content-type"", ""application/json""}, {""content-length"", ""10""}, {""grpc-status"", ""0""}}, R""({""id"":""1""})""); } TEST_P(BufferLimitsDisabledGrpcJsonTranscoderIntegrationTest, UnaryPostResponseExceedsBufferLimit) { // Request body is less than 35 bytes. // Response body is more than 35 bytes. config_helper_.setBufferLimits(2 << 20, 35); HttpIntegrationTest::initialize(); // Transcoding succeeds. However, the downstream client is unable to buffer the full response. // We can tell these errors are NOT from the transcoder because the response body is too generic. testTranscoding( Http::TestRequestHeaderMapImpl{{"":method"", ""POST""}, {"":path"", ""/shelf""}, {"":authority"", ""host""}, {""content-type"", ""application/json""}}, R""({""theme"": ""Children""})"", {R""(shelf { theme: ""Children"" })""}, {R""(id: 20 theme: ""Children 0123456789 0123456789 0123456789 0123456789"" )""}, Status(), Http::TestResponseHeaderMapImpl{ {"":status"", ""500""}, {""content-type"", ""text/plain""}, {""content-length"", ""21""}}, R""(Internal Server Error)""); } } // namespace } // namespace Envoy ",16249,True,3770.307369416946,median "/* * Copyright (C) 2010 Apple Inc. All rights reserved. * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS 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. */ #include ""config.h"" #if ENABLE(WEBGL) #include ""GraphicsContext3D.h"" #include ""ArrayBufferView.h"" #include ""CheckedInt.h"" #include ""DrawingBuffer.h"" #include ""Extensions3D.h"" #include ""Image.h"" #include ""ImageData.h"" #include #include namespace WebCore { namespace { uint8_t convertColor16LittleTo8(uint16_t value) { return value >> 8; } uint8_t convertColor16BigTo8(uint16_t value) { return static_cast(value & 0x00FF); } } // anonymous namespace PassRefPtr GraphicsContext3D::createDrawingBuffer(const IntSize& size) { #if ENABLE(ACCELERATED_2D_CANVAS) return DrawingBuffer::create(this, size); #else return 0; #endif } bool GraphicsContext3D::texImage2DResourceSafe(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint unpackAlignment) { ASSERT(unpackAlignment == 1 || unpackAlignment == 2 || unpackAlignment == 4 || unpackAlignment == 8); OwnArrayPtr zero; if (width > 0 && height > 0) { unsigned int size; GC3Denum error = computeImageSizeInBytes(format, type, width, height, unpackAlignment, &size, 0); if (error != GraphicsContext3D::NO_ERROR) { synthesizeGLError(error); return false; } zero = adoptArrayPtr(new unsigned char[size]); if (!zero) { synthesizeGLError(GraphicsContext3D::INVALID_VALUE); return false; } memset(zero.get(), 0, size); } return texImage2D(target, level, internalformat, width, height, border, format, type, zero.get()); } bool GraphicsContext3D::computeFormatAndTypeParameters(GC3Denum format, GC3Denum type, unsigned int* componentsPerPixel, unsigned int* bytesPerComponent) { switch (format) { case GraphicsContext3D::ALPHA: *componentsPerPixel = 1; break; case GraphicsContext3D::LUMINANCE: *componentsPerPixel = 1; break; case GraphicsContext3D::LUMINANCE_ALPHA: *componentsPerPixel = 2; break; case GraphicsContext3D::RGB: *componentsPerPixel = 3; break; case GraphicsContext3D::RGBA: case Extensions3D::BGRA_EXT: // GL_EXT_texture_format_BGRA8888 *componentsPerPixel = 4; break; default: return false; } switch (type) { case GraphicsContext3D::UNSIGNED_BYTE: *bytesPerComponent = sizeof(GC3Dubyte); break; case GraphicsContext3D::UNSIGNED_SHORT_5_6_5: case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4: case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1: *componentsPerPixel = 1; *bytesPerComponent = sizeof(GC3Dushort); break; case GraphicsContext3D::FLOAT: // OES_texture_float *bytesPerComponent = sizeof(GC3Dfloat); break; default: return false; } return true; } GC3Denum GraphicsContext3D::computeImageSizeInBytes(GC3Denum format, GC3Denum type, GC3Dsizei width, GC3Dsizei height, GC3Dint alignment, unsigned int* imageSizeInBytes, unsigned int* paddingInBytes) { ASSERT(imageSizeInBytes); ASSERT(alignment == 1 || alignment == 2 || alignment == 4 || alignment == 8); if (width < 0 || height < 0) return GraphicsContext3D::INVALID_VALUE; unsigned int bytesPerComponent, componentsPerPixel; if (!computeFormatAndTypeParameters(format, type, &bytesPerComponent, &componentsPerPixel)) return GraphicsContext3D::INVALID_ENUM; if (!width || !height) { *imageSizeInBytes = 0; if (paddingInBytes) *paddingInBytes = 0; return GraphicsContext3D::NO_ERROR; } CheckedInt checkedValue(bytesPerComponent * componentsPerPixel); checkedValue *= width; if (!checkedValue.valid()) return GraphicsContext3D::INVALID_VALUE; unsigned int validRowSize = checkedValue.value(); unsigned int padding = 0; unsigned int residual = validRowSize % alignment; if (residual) { padding = alignment - residual; checkedValue += padding; } // Last row needs no padding. checkedValue *= (height - 1); checkedValue += validRowSize; if (!checkedValue.valid()) return GraphicsContext3D::INVALID_VALUE; *imageSizeInBytes = checkedValue.value(); if (paddingInBytes) *paddingInBytes = padding; return GraphicsContext3D::NO_ERROR; } bool GraphicsContext3D::extractImageData(Image* image, GC3Denum format, GC3Denum type, bool flipY, bool premultiplyAlpha, bool ignoreGammaAndColorProfile, Vector& data) { if (!image) return false; if (!getImageData(image, format, type, premultiplyAlpha, ignoreGammaAndColorProfile, data)) return false; if (flipY) { unsigned int componentsPerPixel, bytesPerComponent; if (!computeFormatAndTypeParameters(format, type, &componentsPerPixel, &bytesPerComponent)) return false; // The image data is tightly packed, and we upload it as such. unsigned int unpackAlignment = 1; flipVertically(data.data(), image->width(), image->height(), componentsPerPixel * bytesPerComponent, unpackAlignment); } return true; } bool GraphicsContext3D::extractImageData(ImageData* imageData, GC3Denum format, GC3Denum type, bool flipY, bool premultiplyAlpha, Vector& data) { if (!imageData) return false; int width = imageData->width(); int height = imageData->height(); int dataBytes = width * height * 4; data.resize(dataBytes); if (!packPixels(imageData->data()->data()->data(), SourceFormatRGBA8, width, height, 0, format, type, premultiplyAlpha ? AlphaDoPremultiply : AlphaDoNothing, data.data())) return false; if (flipY) { unsigned int componentsPerPixel, bytesPerComponent; if (!computeFormatAndTypeParameters(format, type, &componentsPerPixel, &bytesPerComponent)) return false; // The image data is tightly packed, and we upload it as such. unsigned int unpackAlignment = 1; flipVertically(data.data(), width, height, componentsPerPixel * bytesPerComponent, unpackAlignment); } return true; } bool GraphicsContext3D::extractTextureData(unsigned int width, unsigned int height, GC3Denum format, GC3Denum type, unsigned int unpackAlignment, bool flipY, bool premultiplyAlpha, const void* pixels, Vector& data) { // Assumes format, type, etc. have already been validated. SourceDataFormat sourceDataFormat = SourceFormatRGBA8; switch (type) { case UNSIGNED_BYTE: switch (format) { case RGBA: sourceDataFormat = SourceFormatRGBA8; break; case RGB: sourceDataFormat = SourceFormatRGB8; break; case ALPHA: sourceDataFormat = SourceFormatA8; break; case LUMINANCE: sourceDataFormat = SourceFormatR8; break; case LUMINANCE_ALPHA: sourceDataFormat = SourceFormatRA8; break; default: ASSERT_NOT_REACHED(); } break; case FLOAT: // OES_texture_float switch (format) { case RGBA: sourceDataFormat = SourceFormatRGBA32F; break; case RGB: sourceDataFormat = SourceFormatRGB32F; break; case ALPHA: sourceDataFormat = SourceFormatA32F; break; case LUMINANCE: sourceDataFormat = SourceFormatR32F; break; case LUMINANCE_ALPHA: sourceDataFormat = SourceFormatRA32F; break; default: ASSERT_NOT_REACHED(); } break; case UNSIGNED_SHORT_5_5_5_1: sourceDataFormat = SourceFormatRGBA5551; break; case UNSIGNED_SHORT_4_4_4_4: sourceDataFormat = SourceFormatRGBA4444; break; case UNSIGNED_SHORT_5_6_5: sourceDataFormat = SourceFormatRGB565; break; default: ASSERT_NOT_REACHED(); } // Resize the output buffer. unsigned int componentsPerPixel, bytesPerComponent; if (!computeFormatAndTypeParameters(format, type, &componentsPerPixel, &bytesPerComponent)) return false; unsigned int bytesPerPixel = componentsPerPixel * bytesPerComponent; data.resize(width * height * bytesPerPixel); if (!packPixels(static_cast(pixels), sourceDataFormat, width, height, unpackAlignment, format, type, (premultiplyAlpha ? AlphaDoPremultiply : AlphaDoNothing), data.data())) return false; // The pixel data is now tightly packed. if (flipY) flipVertically(data.data(), width, height, bytesPerPixel, 1); return true; } void GraphicsContext3D::flipVertically(void* imageData, unsigned int width, unsigned int height, unsigned int bytesPerPixel, unsigned int unpackAlignment) { if (!width || !height) return; unsigned int validRowBytes = width * bytesPerPixel; unsigned int totalRowBytes = validRowBytes; unsigned int remainder = validRowBytes % unpackAlignment; if (remainder) totalRowBytes += (unpackAlignment - remainder); uint8_t* tempRow = new uint8_t[validRowBytes]; uint8_t* data = static_cast(imageData); for (unsigned i = 0; i < height / 2; i++) { uint8_t* lowRow = data + (totalRowBytes * i); uint8_t* highRow = data + (totalRowBytes * (height - i - 1)); memcpy(tempRow, lowRow, validRowBytes); memcpy(lowRow, highRow, validRowBytes); memcpy(highRow, tempRow, validRowBytes); } delete[] tempRow; } // These functions can not be static, or gcc will not allow them to be // used as template parameters. Use an anonymous namespace to prevent // the need to declare prototypes for them. namespace { //---------------------------------------------------------------------- // Pixel unpacking routines. void unpackRGBA8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[0]; destination[1] = source[1]; destination[2] = source[2]; destination[3] = source[3]; } void unpackRGBA16LittleToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16LittleTo8(source[0]); destination[1] = convertColor16LittleTo8(source[1]); destination[2] = convertColor16LittleTo8(source[2]); destination[3] = convertColor16LittleTo8(source[3]); } void unpackRGBA16BigToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16BigTo8(source[0]); destination[1] = convertColor16BigTo8(source[1]); destination[2] = convertColor16BigTo8(source[2]); destination[3] = convertColor16BigTo8(source[3]); } void unpackRGB8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[0]; destination[1] = source[1]; destination[2] = source[2]; destination[3] = 0xFF; } void unpackRGB16LittleToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16LittleTo8(source[0]); destination[1] = convertColor16LittleTo8(source[1]); destination[2] = convertColor16LittleTo8(source[2]); destination[3] = 0xFF; } void unpackRGB16BigToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16BigTo8(source[0]); destination[1] = convertColor16BigTo8(source[1]); destination[2] = convertColor16BigTo8(source[2]); destination[3] = 0xFF; } void unpackBGR8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[2]; destination[1] = source[1]; destination[2] = source[0]; destination[3] = 0xFF; } void unpackARGB8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[1]; destination[1] = source[2]; destination[2] = source[3]; destination[3] = source[0]; } void unpackARGB16LittleToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16LittleTo8(source[1]); destination[1] = convertColor16LittleTo8(source[2]); destination[2] = convertColor16LittleTo8(source[3]); destination[3] = convertColor16LittleTo8(source[0]); } void unpackARGB16BigToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16BigTo8(source[1]); destination[1] = convertColor16BigTo8(source[2]); destination[2] = convertColor16BigTo8(source[3]); destination[3] = convertColor16BigTo8(source[0]); } void unpackABGR8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[3]; destination[1] = source[2]; destination[2] = source[1]; destination[3] = source[0]; } void unpackBGRA8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[2]; destination[1] = source[1]; destination[2] = source[0]; destination[3] = source[3]; } void unpackBGRA16LittleToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16LittleTo8(source[2]); destination[1] = convertColor16LittleTo8(source[1]); destination[2] = convertColor16LittleTo8(source[0]); destination[3] = convertColor16LittleTo8(source[3]); } void unpackBGRA16BigToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16BigTo8(source[2]); destination[1] = convertColor16BigTo8(source[1]); destination[2] = convertColor16BigTo8(source[0]); destination[3] = convertColor16BigTo8(source[3]); } void unpackRGBA5551ToRGBA8(const uint16_t* source, uint8_t* destination) { uint16_t packedValue = source[0]; uint8_t r = packedValue >> 11; uint8_t g = (packedValue >> 6) & 0x1F; uint8_t b = (packedValue >> 1) & 0x1F; destination[0] = (r << 3) | (r & 0x7); destination[1] = (g << 3) | (g & 0x7); destination[2] = (b << 3) | (b & 0x7); destination[3] = (packedValue & 0x1) ? 0xFF : 0x0; } void unpackRGBA4444ToRGBA8(const uint16_t* source, uint8_t* destination) { uint16_t packedValue = source[0]; uint8_t r = packedValue >> 12; uint8_t g = (packedValue >> 8) & 0x0F; uint8_t b = (packedValue >> 4) & 0x0F; uint8_t a = packedValue & 0x0F; destination[0] = r << 4 | r; destination[1] = g << 4 | g; destination[2] = b << 4 | b; destination[3] = a << 4 | a; } void unpackRGB565ToRGBA8(const uint16_t* source, uint8_t* destination) { uint16_t packedValue = source[0]; uint8_t r = packedValue >> 11; uint8_t g = (packedValue >> 5) & 0x3F; uint8_t b = packedValue & 0x1F; destination[0] = (r << 3) | (r & 0x7); destination[1] = (g << 2) | (g & 0x3); destination[2] = (b << 3) | (b & 0x7); destination[3] = 0xFF; } void unpackR8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[0]; destination[1] = source[0]; destination[2] = source[0]; destination[3] = 0xFF; } void unpackR16LittleToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16LittleTo8(source[0]); destination[1] = convertColor16LittleTo8(source[0]); destination[2] = convertColor16LittleTo8(source[0]); destination[3] = 0xFF; } void unpackR16BigToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16BigTo8(source[0]); destination[1] = convertColor16BigTo8(source[0]); destination[2] = convertColor16BigTo8(source[0]); destination[3] = 0xFF; } void unpackRA8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[0]; destination[1] = source[0]; destination[2] = source[0]; destination[3] = source[1]; } void unpackRA16LittleToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16LittleTo8(source[0]); destination[1] = convertColor16LittleTo8(source[0]); destination[2] = convertColor16LittleTo8(source[0]); destination[3] = convertColor16LittleTo8(source[1]); } void unpackRA16BigToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16BigTo8(source[0]); destination[1] = convertColor16BigTo8(source[0]); destination[2] = convertColor16BigTo8(source[0]); destination[3] = convertColor16BigTo8(source[1]); } void unpackAR8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[1]; destination[1] = source[1]; destination[2] = source[1]; destination[3] = source[0]; } void unpackAR16LittleToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16LittleTo8(source[1]); destination[1] = convertColor16LittleTo8(source[1]); destination[2] = convertColor16LittleTo8(source[1]); destination[3] = convertColor16LittleTo8(source[0]); } void unpackAR16BigToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = convertColor16BigTo8(source[1]); destination[1] = convertColor16BigTo8(source[1]); destination[2] = convertColor16BigTo8(source[1]); destination[3] = convertColor16BigTo8(source[0]); } void unpackA8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = 0x0; destination[1] = 0x0; destination[2] = 0x0; destination[3] = source[0]; } void unpackA16LittleToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = 0x0; destination[1] = 0x0; destination[2] = 0x0; destination[3] = convertColor16LittleTo8(source[0]); } void unpackA16BigToRGBA8(const uint16_t* source, uint8_t* destination) { destination[0] = 0x0; destination[1] = 0x0; destination[2] = 0x0; destination[3] = convertColor16BigTo8(source[0]); } void unpackRGB32FToRGBA32F(const float* source, float* destination) { destination[0] = source[0]; destination[1] = source[1]; destination[2] = source[2]; destination[3] = 1; } void unpackR32FToRGBA32F(const float* source, float* destination) { destination[0] = source[0]; destination[1] = source[0]; destination[2] = source[0]; destination[3] = 1; } void unpackRA32FToRGBA32F(const float* source, float* destination) { destination[0] = source[0]; destination[1] = source[0]; destination[2] = source[0]; destination[3] = source[1]; } void unpackA32FToRGBA32F(const float* source, float* destination) { destination[0] = 0; destination[1] = 0; destination[2] = 0; destination[3] = source[0]; } //---------------------------------------------------------------------- // Pixel packing routines. // void packRGBA8ToA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[3]; } void packRGBA8ToR8(const uint8_t* source, uint8_t* destination) { destination[0] = source[0]; } void packRGBA8ToR8Premultiply(const uint8_t* source, uint8_t* destination) { float scaleFactor = source[3] / 255.0f; uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); destination[0] = sourceR; } // FIXME: this routine is lossy and must be removed. void packRGBA8ToR8Unmultiply(const uint8_t* source, uint8_t* destination) { float scaleFactor = 1.0f / (source[3] ? source[3] / 255.0f : 1.0f); uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); destination[0] = sourceR; } void packRGBA8ToRA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[0]; destination[1] = source[3]; } void packRGBA8ToRA8Premultiply(const uint8_t* source, uint8_t* destination) { float scaleFactor = source[3] / 255.0f; uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); destination[0] = sourceR; destination[1] = source[3]; } // FIXME: this routine is lossy and must be removed. void packRGBA8ToRA8Unmultiply(const uint8_t* source, uint8_t* destination) { float scaleFactor = 1.0f / (source[3] ? source[3] / 255.0f : 1.0f); uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); destination[0] = sourceR; destination[1] = source[3]; } void packRGBA8ToRGB8(const uint8_t* source, uint8_t* destination) { destination[0] = source[0]; destination[1] = source[1]; destination[2] = source[2]; } void packRGBA8ToRGB8Premultiply(const uint8_t* source, uint8_t* destination) { float scaleFactor = source[3] / 255.0f; uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); destination[0] = sourceR; destination[1] = sourceG; destination[2] = sourceB; } // FIXME: this routine is lossy and must be removed. void packRGBA8ToRGB8Unmultiply(const uint8_t* source, uint8_t* destination) { float scaleFactor = 1.0f / (source[3] ? source[3] / 255.0f : 1.0f); uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); destination[0] = sourceR; destination[1] = sourceG; destination[2] = sourceB; } // This is only used when the source format is different than SourceFormatRGBA8. void packRGBA8ToRGBA8(const uint8_t* source, uint8_t* destination) { destination[0] = source[0]; destination[1] = source[1]; destination[2] = source[2]; destination[3] = source[3]; } void packRGBA8ToRGBA8Premultiply(const uint8_t* source, uint8_t* destination) { float scaleFactor = source[3] / 255.0f; uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); destination[0] = sourceR; destination[1] = sourceG; destination[2] = sourceB; destination[3] = source[3]; } // FIXME: this routine is lossy and must be removed. void packRGBA8ToRGBA8Unmultiply(const uint8_t* source, uint8_t* destination) { float scaleFactor = 1.0f / (source[3] ? source[3] / 255.0f : 1.0f); uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); destination[0] = sourceR; destination[1] = sourceG; destination[2] = sourceB; destination[3] = source[3]; } void packRGBA8ToUnsignedShort4444(const uint8_t* source, uint16_t* destination) { *destination = (((source[0] & 0xF0) << 8) | ((source[1] & 0xF0) << 4) | (source[2] & 0xF0) | (source[3] >> 4)); } void packRGBA8ToUnsignedShort4444Premultiply(const uint8_t* source, uint16_t* destination) { float scaleFactor = source[3] / 255.0f; uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); *destination = (((sourceR & 0xF0) << 8) | ((sourceG & 0xF0) << 4) | (sourceB & 0xF0) | (source[3] >> 4)); } // FIXME: this routine is lossy and must be removed. void packRGBA8ToUnsignedShort4444Unmultiply(const uint8_t* source, uint16_t* destination) { float scaleFactor = 1.0f / (source[3] ? source[3] / 255.0f : 1.0f); uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); *destination = (((sourceR & 0xF0) << 8) | ((sourceG & 0xF0) << 4) | (sourceB & 0xF0) | (source[3] >> 4)); } void packRGBA8ToUnsignedShort5551(const uint8_t* source, uint16_t* destination) { *destination = (((source[0] & 0xF8) << 8) | ((source[1] & 0xF8) << 3) | ((source[2] & 0xF8) >> 2) | (source[3] >> 7)); } void packRGBA8ToUnsignedShort5551Premultiply(const uint8_t* source, uint16_t* destination) { float scaleFactor = source[3] / 255.0f; uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); *destination = (((sourceR & 0xF8) << 8) | ((sourceG & 0xF8) << 3) | ((sourceB & 0xF8) >> 2) | (source[3] >> 7)); } // FIXME: this routine is lossy and must be removed. void packRGBA8ToUnsignedShort5551Unmultiply(const uint8_t* source, uint16_t* destination) { float scaleFactor = 1.0f / (source[3] ? source[3] / 255.0f : 1.0f); uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); *destination = (((sourceR & 0xF8) << 8) | ((sourceG & 0xF8) << 3) | ((sourceB & 0xF8) >> 2) | (source[3] >> 7)); } void packRGBA8ToUnsignedShort565(const uint8_t* source, uint16_t* destination) { *destination = (((source[0] & 0xF8) << 8) | ((source[1] & 0xFC) << 3) | ((source[2] & 0xF8) >> 3)); } void packRGBA8ToUnsignedShort565Premultiply(const uint8_t* source, uint16_t* destination) { float scaleFactor = source[3] / 255.0f; uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); *destination = (((sourceR & 0xF8) << 8) | ((sourceG & 0xFC) << 3) | ((sourceB & 0xF8) >> 3)); } // FIXME: this routine is lossy and must be removed. void packRGBA8ToUnsignedShort565Unmultiply(const uint8_t* source, uint16_t* destination) { float scaleFactor = 1.0f / (source[3] ? source[3] / 255.0f : 1.0f); uint8_t sourceR = static_cast(static_cast(source[0]) * scaleFactor); uint8_t sourceG = static_cast(static_cast(source[1]) * scaleFactor); uint8_t sourceB = static_cast(static_cast(source[2]) * scaleFactor); *destination = (((sourceR & 0xF8) << 8) | ((sourceG & 0xFC) << 3) | ((sourceB & 0xF8) >> 3)); } void packRGBA32FToRGB32F(const float* source, float* destination) { destination[0] = source[0]; destination[1] = source[1]; destination[2] = source[2]; } void packRGBA32FToRGB32FPremultiply(const float* source, float* destination) { float scaleFactor = source[3]; destination[0] = source[0] * scaleFactor; destination[1] = source[1] * scaleFactor; destination[2] = source[2] * scaleFactor; } void packRGBA32FToRGBA32FPremultiply(const float* source, float* destination) { float scaleFactor = source[3]; destination[0] = source[0] * scaleFactor; destination[1] = source[1] * scaleFactor; destination[2] = source[2] * scaleFactor; destination[3] = source[3]; } void packRGBA32FToA32F(const float* source, float* destination) { destination[0] = source[3]; } void packRGBA32FToR32F(const float* source, float* destination) { destination[0] = source[0]; } void packRGBA32FToR32FPremultiply(const float* source, float* destination) { float scaleFactor = source[3]; destination[0] = source[0] * scaleFactor; } void packRGBA32FToRA32F(const float* source, float* destination) { destination[0] = source[0]; destination[1] = source[3]; } void packRGBA32FToRA32FPremultiply(const float* source, float* destination) { float scaleFactor = source[3]; destination[0] = source[0] * scaleFactor; destination[1] = scaleFactor; } } // anonymous namespace // This is used whenever unpacking is necessary; i.e., the source data // is not in RGBA8/RGBA32F format, or the unpack alignment specifies // that rows are not tightly packed. template static void doUnpackingAndPacking(const SourceType* sourceData, unsigned int width, unsigned int height, unsigned int sourceElementsPerPixel, unsigned int sourceElementsPerRow, DestType* destinationData, unsigned int destinationElementsPerPixel) { if (!sourceElementsPerRow) { unsigned int numElements = width * height * sourceElementsPerPixel; const SourceType* endPointer = sourceData + numElements; IntermediateType temporaryRGBAData[4]; while (sourceData < endPointer) { unpackingFunc(sourceData, temporaryRGBAData); packingFunc(temporaryRGBAData, destinationData); sourceData += sourceElementsPerPixel; destinationData += destinationElementsPerPixel; } } else { IntermediateType temporaryRGBAData[4]; for (unsigned int y = 0; y < height; ++y) { const SourceType* currentSource = sourceData; for (unsigned int x = 0; x < width; ++x) { unpackingFunc(currentSource, temporaryRGBAData); packingFunc(temporaryRGBAData, destinationData); currentSource += sourceElementsPerPixel; destinationData += destinationElementsPerPixel; } sourceData += sourceElementsPerRow; } } } template static void computeIncrementParameters(unsigned int width, unsigned int bytesPerPixel, unsigned int unpackAlignment, unsigned int* sourceElementsPerPixel, unsigned int* sourceElementsPerRow) { unsigned int elementSizeInBytes = sizeof(SourceType); ASSERT(elementSizeInBytes <= bytesPerPixel); ASSERT(!(bytesPerPixel % elementSizeInBytes)); unsigned int validRowBytes = width * bytesPerPixel; unsigned int totalRowBytes = validRowBytes; if (unpackAlignment) { unsigned int remainder = validRowBytes % unpackAlignment; if (remainder) totalRowBytes += (unpackAlignment - remainder); } *sourceElementsPerPixel = bytesPerPixel / elementSizeInBytes; if (validRowBytes == totalRowBytes) *sourceElementsPerRow = 0; else *sourceElementsPerRow = totalRowBytes / elementSizeInBytes; } // This handles all conversions with a faster path for tightly packed RGBA8 source data. template static void doPacking(const void* sourceData, GraphicsContext3D::SourceDataFormat sourceDataFormat, unsigned int width, unsigned int height, unsigned int sourceUnpackAlignment, DestType* destinationData, unsigned int destinationElementsPerPixel) { switch (sourceDataFormat) { case GraphicsContext3D::SourceFormatRGBA8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); if (!sourceElementsPerRow) { const uint8_t* source = static_cast(sourceData); unsigned int numElements = width * height * 4; const uint8_t* endPointer = source + numElements; while (source < endPointer) { packingFunc(source, destinationData); source += sourceElementsPerPixel; destinationData += destinationElementsPerPixel; } } else { doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); } break; } case GraphicsContext3D::SourceFormatRGBA16Little: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 8, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRGBA16Big: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 8, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRGB8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 3, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRGB16Little: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 6, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRGB16Big: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 6, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatBGR8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 3, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatARGB8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatARGB16Little: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 8, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatARGB16Big: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 8, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatABGR8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatBGRA8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatBGRA16Little: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 8, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatBGRA16Big: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 8, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRGBA5551: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRGBA4444: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRGB565: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatR8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 1, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatR16Little: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatR16Big: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRA8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRA16Little: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRA16Big: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatAR8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatAR16Little: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatAR16Big: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatA8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 1, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatA16Little: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatA16Big: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } default: ASSERT(false); } } // This specialized routine is used only for floating-point texture uploads. It // does not need to be as general as doPacking, above; because there are // currently no native floating-point image formats in WebKit, there are only a // few upload paths. template static void doFloatingPointPacking(const void* sourceData, GraphicsContext3D::SourceDataFormat sourceDataFormat, unsigned int width, unsigned int height, unsigned int sourceUnpackAlignment, float* destinationData, unsigned int destinationElementsPerPixel) { switch (sourceDataFormat) { case GraphicsContext3D::SourceFormatRGBA8: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 4, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); ASSERT(!sourceElementsPerRow); // Guaranteed because each color channel is sizeof(float) bytes. const float* source = static_cast(sourceData); unsigned int numElements = width * height * 4; const float* endPointer = source + numElements; while (source < endPointer) { packingFunc(source, destinationData); source += sourceElementsPerPixel; destinationData += destinationElementsPerPixel; } break; } case GraphicsContext3D::SourceFormatRGB32F: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 3, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatR32F: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 1, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatRA32F: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 2, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } case GraphicsContext3D::SourceFormatA32F: { unsigned int sourceElementsPerPixel, sourceElementsPerRow; computeIncrementParameters(width, 1, sourceUnpackAlignment, &sourceElementsPerPixel, &sourceElementsPerRow); doUnpackingAndPacking(static_cast(sourceData), width, height, sourceElementsPerPixel, sourceElementsPerRow, destinationData, destinationElementsPerPixel); break; } default: ASSERT_NOT_REACHED(); } } bool GraphicsContext3D::packPixels(const uint8_t* sourceData, GraphicsContext3D::SourceDataFormat sourceDataFormat, unsigned int width, unsigned int height, unsigned int sourceUnpackAlignment, unsigned int destinationFormat, unsigned int destinationType, AlphaOp alphaOp, void* destinationData) { switch (destinationType) { case UNSIGNED_BYTE: { uint8_t* destination = static_cast(destinationData); if (sourceDataFormat == SourceFormatRGBA8 && destinationFormat == RGBA && sourceUnpackAlignment <= 4 && alphaOp == AlphaDoNothing) { // No conversion necessary. memcpy(destinationData, sourceData, width * height * 4); break; } switch (destinationFormat) { case RGB: switch (alphaOp) { case AlphaDoNothing: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 3); break; case AlphaDoPremultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 3); break; case AlphaDoUnmultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 3); break; } break; case RGBA: switch (alphaOp) { case AlphaDoNothing: ASSERT(sourceDataFormat != SourceFormatRGBA8 || sourceUnpackAlignment > 4); // Handled above with fast case. doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 4); break; case AlphaDoPremultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 4); break; case AlphaDoUnmultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 4); break; default: ASSERT_NOT_REACHED(); } break; case ALPHA: // From the desktop OpenGL conversion rules (OpenGL 2.1 // specification, Table 3.15), the alpha channel is chosen // from the RGBA data. doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case LUMINANCE: // From the desktop OpenGL conversion rules (OpenGL 2.1 // specification, Table 3.15), the red channel is chosen // from the RGBA data. switch (alphaOp) { case AlphaDoNothing: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoPremultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoUnmultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; } break; case LUMINANCE_ALPHA: // From the desktop OpenGL conversion rules (OpenGL 2.1 // specification, Table 3.15), the red and alpha channels // are chosen from the RGBA data. switch (alphaOp) { case AlphaDoNothing: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 2); break; case AlphaDoPremultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 2); break; case AlphaDoUnmultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 2); break; } break; } break; } case UNSIGNED_SHORT_4_4_4_4: { uint16_t* destination = static_cast(destinationData); switch (alphaOp) { case AlphaDoNothing: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoPremultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoUnmultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; } break; } case UNSIGNED_SHORT_5_5_5_1: { uint16_t* destination = static_cast(destinationData); switch (alphaOp) { case AlphaDoNothing: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoPremultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoUnmultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; } break; } case UNSIGNED_SHORT_5_6_5: { uint16_t* destination = static_cast(destinationData); switch (alphaOp) { case AlphaDoNothing: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoPremultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoUnmultiply: doPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; } break; } case FLOAT: { // OpenGL ES, and therefore WebGL, require that the format and // internalformat be identical, which implies that the source and // destination formats will both be floating-point in this branch -- at // least, until WebKit supports floating-point image formats natively. ASSERT(sourceDataFormat == SourceFormatRGBA32F || sourceDataFormat == SourceFormatRGB32F || sourceDataFormat == SourceFormatRA32F || sourceDataFormat == SourceFormatR32F || sourceDataFormat == SourceFormatA32F); // Because WebKit doesn't use floating-point color channels for anything // internally, there's no chance we have to do a (lossy) unmultiply // operation. ASSERT(alphaOp == AlphaDoNothing || alphaOp == AlphaDoPremultiply); // For the source formats with an even number of channels (RGBA32F, // RA32F) it is guaranteed that the pixel data is tightly packed because // unpack alignment <= sizeof(float) * number of channels. float* destination = static_cast(destinationData); if (alphaOp == AlphaDoNothing && ((sourceDataFormat == SourceFormatRGBA32F && destinationFormat == RGBA) || (sourceDataFormat == SourceFormatRA32F && destinationFormat == LUMINANCE_ALPHA))) { // No conversion necessary. int numChannels = (sourceDataFormat == SourceFormatRGBA32F ? 4 : 2); memcpy(destinationData, sourceData, width * height * numChannels * sizeof(float)); break; } switch (destinationFormat) { case RGB: switch (alphaOp) { case AlphaDoNothing: doFloatingPointPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 3); break; case AlphaDoPremultiply: doFloatingPointPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 3); break; default: ASSERT_NOT_REACHED(); } break; case RGBA: // AlphaDoNothing is handled above with fast path. ASSERT(alphaOp == AlphaDoPremultiply); doFloatingPointPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 4); break; case ALPHA: // From the desktop OpenGL conversion rules (OpenGL 2.1 // specification, Table 3.15), the alpha channel is chosen // from the RGBA data. doFloatingPointPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case LUMINANCE: // From the desktop OpenGL conversion rules (OpenGL 2.1 // specification, Table 3.15), the red channel is chosen // from the RGBA data. switch (alphaOp) { case AlphaDoNothing: doFloatingPointPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; case AlphaDoPremultiply: doFloatingPointPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 1); break; default: ASSERT_NOT_REACHED(); } break; case LUMINANCE_ALPHA: // From the desktop OpenGL conversion rules (OpenGL 2.1 // specification, Table 3.15), the red and alpha channels // are chosen from the RGBA data. switch (alphaOp) { case AlphaDoNothing: doFloatingPointPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 2); break; case AlphaDoPremultiply: doFloatingPointPacking(sourceData, sourceDataFormat, width, height, sourceUnpackAlignment, destination, 2); break; default: ASSERT_NOT_REACHED(); } break; } break; } } return true; } } // namespace WebCore #endif // ENABLE(WEBGL) ",16287,True,3387.099851053988,median "[[java-dsl]] == Java DSL The Spring Integration Java configuration and DSL provides a set of convenient builders and a fluent API that lets you configure Spring Integration message flows from Spring `@Configuration` classes. (See also <<./kotlin-dsl.adoc#kotlin-dsl,Kotlin DSL>>.) The Java DSL for Spring Integration is essentially a facade for Spring Integration. The DSL provides a simple way to embed Spring Integration Message Flows into your application by using the fluent `Builder` pattern together with existing Java configuration from Spring Framework and Spring Integration. We also use and support lambdas (available with Java 8) to further simplify Java configuration. The https://github.com/spring-projects/spring-integration-samples/tree/main/dsl/cafe-dsl[cafe] offers a good example of using the DSL. The DSL is presented by the `IntegrationFlows` factory for the `IntegrationFlowBuilder`. This produces the `IntegrationFlow` component, which should be registered as a Spring bean (by using the `@Bean` annotation). The builder pattern is used to express arbitrarily complex structures as a hierarchy of methods that can accept lambdas as arguments. The `IntegrationFlowBuilder` only collects integration components (`MessageChannel` instances, `AbstractEndpoint` instances, and so on) in the `IntegrationFlow` bean for further parsing and registration of concrete beans in the application context by the `IntegrationFlowBeanPostProcessor`. The Java DSL uses Spring Integration classes directly and bypasses any XML generation and parsing. However, the DSL offers more than syntactic sugar on top of XML. One of its most compelling features is the ability to define inline lambdas to implement endpoint logic, eliminating the need for external classes to implement custom logic. In some sense, Spring Integration's support for the Spring Expression Language (SpEL) and inline scripting address this, but lambdas are easier and much more powerful. The following example shows how to use Java Configuration for Spring Integration: ==== [source,java] ---- @Configuration @EnableIntegration public class MyConfiguration { @Bean public AtomicInteger integerSource() { return new AtomicInteger(); } @Bean public IntegrationFlow myFlow() { return IntegrationFlows.fromSupplier(integerSource()::getAndIncrement, c -> c.poller(Pollers.fixedRate(100))) .channel(""inputChannel"") .filter((Integer p) -> p > 0) .transform(Object::toString) .channel(MessageChannels.queue()) .get(); } } ---- ==== The result of the preceding configuration example is that it creates, after `ApplicationContext` start up, Spring Integration endpoints and message channels. Java configuration can be used both to replace and augment XML configuration. You need not replace all of your existing XML configuration to use Java configuration. [[java-dsl-basics]] === DSL Basics The `org.springframework.integration.dsl` package contains the `IntegrationFlowBuilder` API mentioned earlier and a number of `IntegrationComponentSpec` implementations, which are also builders and provide the fluent API to configure concrete endpoints. The `IntegrationFlowBuilder` infrastructure provides common https://www.enterpriseintegrationpatterns.com/[enterprise integration patterns] (EIP) for message-based applications, such as channels, endpoints, pollers, and channel interceptors. Endpoints are expressed as verbs in the DSL to improve readability. The following list includes the common DSL method names and the associated EIP endpoint: * transform -> `Transformer` * filter -> `Filter` * handle -> `ServiceActivator` * split -> `Splitter` * aggregate -> `Aggregator` * route -> `Router` * bridge -> `Bridge` Conceptually, integration processes are constructed by composing these endpoints into one or more message flows. Note that EIP does not formally define the term 'message flow', but it is useful to think of it as a unit of work that uses well known messaging patterns. The DSL provides an `IntegrationFlow` component to define a composition of channels and endpoints between them, but now `IntegrationFlow` plays only the configuration role to populate real beans in the application context and is not used at runtime. However the bean for `IntegrationFlow` can be autowired as a `Lifecycle` to control `start()` and `stop()` for the whole flow which is delegated to all the Spring Integration components associated with this `IntegrationFlow`. The following example uses the `IntegrationFlows` factory to define an `IntegrationFlow` bean by using EIP-methods from `IntegrationFlowBuilder`: ==== [source,java] ---- @Bean public IntegrationFlow integerFlow() { return IntegrationFlows.from(""input"") .transform(Integer::parseInt) .get(); } ---- ==== The `transform` method accepts a lambda as an endpoint argument to operate on the message payload. The real argument of this method is `GenericTransformer`. Consequently, any of the provided transformers (`ObjectToJsonTransformer`, `FileToStringTransformer`, and other) can be used here. Under the covers, `IntegrationFlowBuilder` recognizes the `MessageHandler` and the endpoint for it, with `MessageTransformingHandler` and `ConsumerEndpointFactoryBean`, respectively. Consider another example: ==== [source,java] ---- @Bean public IntegrationFlow myFlow() { return IntegrationFlows.from(""input"") .filter(""World""::equals) .transform(""Hello ""::concat) .handle(System.out::println) .get(); } ---- ==== The preceding example composes a sequence of `Filter -> Transformer -> Service Activator`. The flow is ""'one way'"". That is, it does not provide a reply message but only prints the payload to STDOUT. The endpoints are automatically wired together by using direct channels. [[java-dsl-class-cast]] .Lambdas And `Message` Arguments [IMPORTANT] ==== When using lambdas in EIP methods, the ""input"" argument is generally the message payload. If you wish to access the entire message, use one of the overloaded methods that take a `Class` as the first parameter. For example, this won't work: [source, java] ---- ., Foo>transform(m -> newFooFromMessage(m)) ---- This will fail at runtime with a `ClassCastException` because the lambda doesn't retain the argument type and the framework will attempt to cast the payload to a `Message`. Instead, use: [source, java] ---- .(Message.class, m -> newFooFromMessage(m)) ---- ==== [[bean-definitions-override]] .Bean Definitions override [IMPORTANT] ==== The Java DSL can register beans for the object defined in-line in the flow definition, as well as can reuse existing, injected beans. In case of the same bean name defined for in-line object and existing bean definition, a `BeanDefinitionOverrideException` is thrown indicating that such a configuration is wrong. However when you deal with `prototype` beans, there is no way to detect from the integration flow processor an existing bean definition because every time we call a `prototype` bean from the `BeanFactory` we get a new instance. This way a provided instance is used in the `IntegrationFlow` as is without any bean registration and any possible check against existing `prototype` bean definition. However `BeanFactory.initializeBean()` is called for this object if it has an explicit `id` and bean definition for this name is in `prototype` scope. ==== [[java-dsl-channels]] === Message Channels In addition to the `IntegrationFlowBuilder` with EIP methods, the Java DSL provides a fluent API to configure `MessageChannel` instances. For this purpose the `MessageChannels` builder factory is provided. The following example shows how to use it: ==== [source,java] ---- @Bean public MessageChannel priorityChannel() { return MessageChannels.priority(this.mongoDbChannelMessageStore, ""priorityGroup"") .interceptor(wireTap()) .get(); } ---- ==== The same `MessageChannels` builder factory can be used in the `channel()` EIP method from `IntegrationFlowBuilder` to wire endpoints, similar to wiring an `input-channel`/`output-channel` pair in the XML configuration. By default, endpoints are wired with `DirectChannel` instances where the bean name is based on the following pattern: `[IntegrationFlow.beanName].channel#[channelNameIndex]`. This rule is also applied for unnamed channels produced by inline `MessageChannels` builder factory usage. However all `MessageChannels` methods have a variant that is aware of the `channelId` that you can use to set the bean names for `MessageChannel` instances. The `MessageChannel` references and `beanName` can be used as bean-method invocations. The following example shows the possible ways to use the `channel()` EIP method: [source,java] ---- @Bean public MessageChannel queueChannel() { return MessageChannels.queue().get(); } @Bean public MessageChannel publishSubscribe() { return MessageChannels.publishSubscribe().get(); } @Bean public IntegrationFlow channelFlow() { return IntegrationFlows.from(""input"") .fixedSubscriberChannel() .channel(""queueChannel"") .channel(publishSubscribe()) .channel(MessageChannels.executor(""executorChannel"", this.taskExecutor)) .channel(""output"") .get(); } ---- * `from(""input"")` means ""'find and use the `MessageChannel` with the ""input"" id, or create one'"". * `fixedSubscriberChannel()` produces an instance of `FixedSubscriberChannel` and registers it with a name of `channelFlow.channel#0`. * `channel(""queueChannel"")` works the same way but uses an existing `queueChannel` bean. * `channel(publishSubscribe())` is the bean-method reference. * `channel(MessageChannels.executor(""executorChannel"", this.taskExecutor))` is the `IntegrationFlowBuilder` that exposes `IntegrationComponentSpec` to the `ExecutorChannel` and registers it as `executorChannel`. * `channel(""output"")` registers the `DirectChannel` bean with `output` as its name, as long as no beans with this name already exist. Note: The preceding `IntegrationFlow` definition is valid, and all of its channels are applied to endpoints with `BridgeHandler` instances. IMPORTANT: Be careful to use the same inline channel definition through `MessageChannels` factory from different `IntegrationFlow` instances. Even if the DSL parser registers non-existent objects as beans, it cannot determine the same object (`MessageChannel`) from different `IntegrationFlow` containers. The following example is wrong: [source,java] ---- @Bean public IntegrationFlow startFlow() { return IntegrationFlows.from(""input"") .transform(...) .channel(MessageChannels.queue(""queueChannel"")) .get(); } @Bean public IntegrationFlow endFlow() { return IntegrationFlows.from(MessageChannels.queue(""queueChannel"")) .handle(...) .get(); } ---- The result of that bad example is the following exception: ``` Caused by: java.lang.IllegalStateException: Could not register object [queueChannel] under bean name 'queueChannel': there is already object [queueChannel] bound at o.s.b.f.s.DefaultSingletonBeanRegistry.registerSingleton(DefaultSingletonBeanRegistry.java:129) ``` To make it work, you need to declare `@Bean` for that channel and use its bean method from different `IntegrationFlow` instances. [[java-dsl-pollers]] === Pollers Spring Integration also provides a fluent API that lets you configure `PollerMetadata` for `AbstractPollingEndpoint` implementations. You can use the `Pollers` builder factory to configure common bean definitions or those created from `IntegrationFlowBuilder` EIP methods, as the following example shows: [source,java] ---- @Bean(name = PollerMetadata.DEFAULT_POLLER) public PollerSpec poller() { return Pollers.fixedRate(500) .errorChannel(""myErrors""); } ---- See https://docs.spring.io/spring-integration/api/org/springframework/integration/dsl/Pollers.html[`Pollers`] and https://docs.spring.io/spring-integration/api/org/springframework/integration/dsl/PollerSpec.html[`PollerSpec`] in the Javadoc for more information. IMPORTANT: If you use the DSL to construct a `PollerSpec` as a `@Bean`, do not call the `get()` method in the bean definition. The `PollerSpec` is a `FactoryBean` that generates the `PollerMetadata` object from the specification and initializes all of its properties. [[java-dsl-reactive]] === The `reactive()` Endpoint Starting with version 5.5, the `ConsumerEndpointSpec` provides a `reactive()` configuration property with an optional customizer `Function>, ? extends Publisher>>`. This option configures the target endpoint as a `ReactiveStreamsConsumer` instance, independently of the input channel type, which is converted to a `Flux` via `IntegrationReactiveUtils.messageChannelToFlux()`. The provided function is used from the `Flux.transform()` operator to customize (`publishOn()`, `log()`, `doOnNext()` etc.) a reactive stream source from the input channel. The following example demonstrates how to change the publishing thread from the input channel independently of the final subscriber and producer to that `DirectChannel`: ==== [source,java] ---- @Bean public IntegrationFlow reactiveEndpointFlow() { return IntegrationFlows .from(""inputChannel"") .transform(Integer::parseInt, e -> e.reactive(flux -> flux.publishOn(Schedulers.parallel()))) .get(); } ---- ==== See <<./reactive-streams.adoc#reactive-streams, Reactive Streams Support>> for more information. [[java-dsl-endpoints]] === DSL and Endpoint Configuration All `IntegrationFlowBuilder` EIP methods have a variant that applies the lambda parameter to provide options for `AbstractEndpoint` instances: `SmartLifecycle`, `PollerMetadata`, `request-handler-advice-chain`, and others. Each of them has generic arguments, so it lets you configure an endpoint and even its `MessageHandler` in the context, as the following example shows: ==== [source,java] ---- @Bean public IntegrationFlow flow2() { return IntegrationFlows.from(this.inputChannel) .transform(new PayloadSerializingTransformer(), c -> c.autoStartup(false).id(""payloadSerializingTransformer"")) .transform((Integer p) -> p * 2, c -> c.advice(this.expressionAdvice())) .get(); } ---- ==== In addition, the `EndpointSpec` provides an `id()` method to let you register an endpoint bean with a given bean name, rather than a generated one. If the `MessageHandler` is referenced as a bean, then any existing `adviceChain` configuration will be overridden if the `.advice()` method is present in the DSL definition: [source,java] ---- @Bean public TcpOutboundGateway tcpOut() { TcpOutboundGateway gateway = new TcpOutboundGateway(); gateway.setConnectionFactory(cf()); gateway.setAdviceChain(Collections.singletonList(fooAdvice())); return gateway; } @Bean public IntegrationFlow clientTcpFlow() { return f -> f .handle(tcpOut(), e -> e.advice(testAdvice())) .transform(Transformers.objectToString()); } ---- That is they are not merged, only the `testAdvice()` bean is used in this case. [[java-dsl-transformers]] === Transformers The DSL API provides a convenient, fluent `Transformers` factory to be used as inline target object definition within the `.transform()` EIP method. The following example shows how to use it: ==== [source,java] ---- @Bean public IntegrationFlow transformFlow() { return IntegrationFlows.from(""input"") .transform(Transformers.fromJson(MyPojo.class)) .transform(Transformers.serializer()) .get(); } ---- ==== It avoids inconvenient coding using setters and makes the flow definition more straightforward. Note that you can use `Transformers` to declare target `Transformer` instances as `@Bean` instances and, again, use them from `IntegrationFlow` definition as bean methods. Nevertheless, the DSL parser takes care of bean declarations for inline objects, if they are not yet defined as beans. See https://docs.spring.io/spring-integration/api/org/springframework/integration/dsl/Transformers.html[Transformers] in the Javadoc for more information and supported factory methods. Also see <>. [[java-dsl-inbound-adapters]] === Inbound Channel Adapters Typically, message flows start from an inbound channel adapter (such as ``). The adapter is configured with ``, and it asks a `MessageSource` to periodically produce messages. Java DSL allows for starting `IntegrationFlow` from a `MessageSource`, too. For this purpose, the `IntegrationFlows` builder factory provides an overloaded `IntegrationFlows.from(MessageSource messageSource)` method. You can configure the `MessageSource` as a bean and provide it as an argument for that method. The second parameter of `IntegrationFlows.from()` is a `Consumer` lambda that lets you provide options (such as `PollerMetadata` or `SmartLifecycle`) for the `SourcePollingChannelAdapter`. The following example shows how to use the fluent API and a lambda to create an `IntegrationFlow`: ==== [source,java] ---- @Bean public MessageSource jdbcMessageSource() { return new JdbcPollingChannelAdapter(this.dataSource, ""SELECT * FROM something""); } @Bean public IntegrationFlow pollingFlow() { return IntegrationFlows.from(jdbcMessageSource(), c -> c.poller(Pollers.fixedRate(100).maxMessagesPerPoll(1))) .transform(Transformers.toJson()) .channel(""furtherProcessChannel"") .get(); } ---- ==== For those cases that have no requirements to build `Message` objects directly, you can use a `IntegrationFlows.fromSupplier()` variant that is based on the `java.util.function.Supplier` . The result of the `Supplier.get()` is automatically wrapped in a `Message` (if it is not already a `Message`). [[java-dsl-routers]] === Message Routers Spring Integration natively provides specialized router types, including: * `HeaderValueRouter` * `PayloadTypeRouter` * `ExceptionTypeRouter` * `RecipientListRouter` * `XPathRouter` As with many other DSL `IntegrationFlowBuilder` EIP methods, the `route()` method can apply any `AbstractMessageRouter` implementation or, for convenience, a `String` as a SpEL expression or a `ref`-`method` pair. In addition, you can configure `route()` with a lambda and use a lambda for a `Consumer>`. The fluent API also provides `AbstractMappingMessageRouter` options such as `channelMapping(String key, String channelName)` pairs, as the following example shows: ==== [source,java] ---- @Bean public IntegrationFlow routeFlowByLambda() { return IntegrationFlows.from(""routerInput"") .route(p -> p % 2 == 0, m -> m.suffix(""Channel"") .channelMapping(true, ""even"") .channelMapping(false, ""odd"") ) .get(); } ---- ==== The following example shows a simple expression-based router: ==== [source,java] ---- @Bean public IntegrationFlow routeFlowByExpression() { return IntegrationFlows.from(""routerInput"") .route(""headers['destChannel']"") .get(); } ---- ==== The `routeToRecipients()` method takes a `Consumer`, as the following example shows: ==== [source,java] ---- @Bean public IntegrationFlow recipientListFlow() { return IntegrationFlows.from(""recipientListInput"") .transform(p -> p.replaceFirst(""Payload"", """")) .routeToRecipients(r -> r .recipient(""thing1-channel"", ""'thing1' == payload"") .recipientMessageSelector(""thing2-channel"", m -> m.getHeaders().containsKey(""recipient"") && (boolean) m.getHeaders().get(""recipient"")) .recipientFlow(""'thing1' == payload or 'thing2' == payload or 'thing3' == payload"", f -> f.transform(String::toUpperCase) .channel(c -> c.queue(""recipientListSubFlow1Result""))) .recipientFlow((String p) -> p.startsWith(""thing3""), f -> f.transform(""Hello ""::concat) .channel(c -> c.queue(""recipientListSubFlow2Result""))) .recipientFlow(new FunctionExpression>(m -> ""thing3"".equals(m.getPayload())), f -> f.channel(c -> c.queue(""recipientListSubFlow3Result""))) .defaultOutputToParentFlow()) .get(); } ---- ==== The `.defaultOutputToParentFlow()` of the `.routeToRecipients()` definition lets you set the router's `defaultOutput` as a gateway to continue a process for the unmatched messages in the main flow. Also see <>. [[java-dsl-splitters]] === Splitters To create a splitter, use the `split()` EIP method. By default, if the payload is an `Iterable`, an `Iterator`, an `Array`, a `Stream`, or a reactive `Publisher`, the `split()` method outputs each item as an individual message. It accepts a lambda, a SpEL expression, or any `AbstractMessageSplitter` implementation. Alternatively, you can use it without parameters to provide the `DefaultMessageSplitter`. The following example shows how to use the `split()` method by providing a lambda: [source,java] ---- @Bean public IntegrationFlow splitFlow() { return IntegrationFlows.from(""splitInput"") .split(s -> s.applySequence(false).delimiters("","")) .channel(MessageChannels.executor(taskExecutor())) .get(); } ---- The preceding example creates a splitter that splits a message containing a comma-delimited `String`. Also see <>. [[java-dsl-aggregators]] === Aggregators and Resequencers An `Aggregator` is conceptually the opposite of a `Splitter`. It aggregates a sequence of individual messages into a single message and is necessarily more complex. By default, an aggregator returns a message that contains a collection of payloads from incoming messages. The same rules are applied for the `Resequencer`. The following example shows a canonical example of the splitter-aggregator pattern: [source,java] ---- @Bean public IntegrationFlow splitAggregateFlow() { return IntegrationFlows.from(""splitAggregateInput"") .split() .channel(MessageChannels.executor(this.taskExecutor())) .resequence() .aggregate() .get(); } ---- The `split()` method splits the list into individual messages and sends them to the `ExecutorChannel`. The `resequence()` method reorders messages by sequence details found in the message headers. The `aggregate()` method collects those messages. However, you can change the default behavior by specifying a release strategy and correlation strategy, among other things. Consider the following example: ==== [source,java] ---- .aggregate(a -> a.correlationStrategy(m -> m.getHeaders().get(""myCorrelationKey"")) .releaseStrategy(g -> g.size() > 10) .messageStore(messageStore())) ---- ==== The preceding example correlates messages that have `myCorrelationKey` headers and releases the messages once at least ten have been accumulated. Similar lambda configurations are provided for the `resequence()` EIP method. [[java-dsl-handle]] === Service Activators and the `.handle()` method The `.handle()` EIP method's goal is to invoke any `MessageHandler` implementation or any method on some POJO. Another option is to define an ""`activity`"" by using lambda expressions. Consequently, we introduced a generic `GenericHandler

` functional interface. Its `handle` method requires two arguments: `P payload` and `MessageHeaders headers` (starting with version 5.1). Having that, we can define a flow as follows: ==== [source,java] ---- @Bean public IntegrationFlow myFlow() { return IntegrationFlows.from(""flow3Input"") .handle((p, h) -> p * 2) .get(); } ---- ==== The preceding example doubles any integer it receives. However, one main goal of Spring Integration is `loose coupling`, through runtime type conversion from message payload to the target arguments of the message handler. Since Java does not support generic type resolution for lambda classes, we introduced a workaround with an additional `payloadType` argument for the most EIP methods and `LambdaMessageProcessor`. Doing so delegates the hard conversion work to Spring's `ConversionService`, which uses the provided `type` and the requested message to target method arguments. The following example shows what the resulting `IntegrationFlow` might look like: ==== [source,java] ---- @Bean public IntegrationFlow integerFlow() { return IntegrationFlows.from(""input"") .transform(p - > new String(p, ""UTF-8"")) .handle(Integer.class, (p, h) -> p * 2) .get(); } ---- ==== We also can register some `BytesToIntegerConverter` within `ConversionService` to get rid of that additional `.transform()`: ==== [source,java] ---- @Bean @IntegrationConverter public BytesToIntegerConverter bytesToIntegerConverter() { return new BytesToIntegerConverter(); } @Bean public IntegrationFlow integerFlow() { return IntegrationFlows.from(""input"") .handle(Integer.class, (p, h) -> p * 2) .get(); } ---- ==== Also see <>. [[java-dsl-gateway]] === Operator gateway() The `gateway()` operator in an `IntegrationFlow` definition is a special service activator implementation, to call some other endpoint or integration flow via its input channel and wait for reply. Technically it plays the same role as a nested `` component in a `` definition (see <<./chain.adoc#chain-gateway,Calling a Chain from within a Chain>>) and allows a flow to be cleaner and more straightforward. Logically, and from business perspective, it is a messaging gateway to allow the distribution and reuse of functionality between different parts of the target integration solution (see <<./gateway.adoc#gateway,Messaging Gateways>>). This operator has several overloads for different goals: - `gateway(String requestChannel)` to send a message to some endpoint's input channel by its name; - `gateway(MessageChannel requestChannel)` to send a message to some endpoint's input channel by its direct injection; - `gateway(IntegrationFlow flow)` to send a message to the input channel of the provided `IntegrationFlow`. All of these have a variant with the second `Consumer` argument to configure the target `GatewayMessageHandler` and respective `AbstractEndpoint`. Also the `IntegrationFlow`-based methods allows calling existing `IntegrationFlow` bean or declare the flow as a sub-flow via an in-place lambda for an `IntegrationFlow` functional interface or have it extracted in a `private` method cleaner code style: ==== [source,java] ---- @Bean IntegrationFlow someFlow() { return IntegrationFlows .from(...) .gateway(subFlow()) .handle(...) .get(); } private static IntegrationFlow subFlow() { return f -> f .scatterGather(s -> s.recipientFlow(...), g -> g.outputProcessor(MessageGroup::getOne)) } ---- ==== IMPORTANT: If the downstream flow does not always return a reply, you should set the `requestTimeout` to 0 to prevent hanging the calling thread indefinitely. In that case, the flow will end at that point and the thread released for further work. [[java-dsl-log]] === Operator log() For convenience, to log the message journey through the Spring Integration flow (``), a `log()` operator is presented. Internally, it is represented by the `WireTap` `ChannelInterceptor` with a `LoggingHandler` as its subscriber. It is responsible for logging the incoming message into the next endpoint or the current channel. The following example shows how to use `LoggingHandler`: ==== [source,java] ---- .filter(...) .log(LoggingHandler.Level.ERROR, ""test.category"", m -> m.getHeaders().getId()) .route(...) ---- ==== In the preceding example, an `id` header is logged at the `ERROR` level onto `test.category` only for messages that passed the filter and before routing. When this operator is used at the end of a flow, it is a one-way handler and the flow ends. To make it as a reply-producing flow, you can either use a simple `bridge()` after the `log()` or, starting with version 5.1, you can use a `logAndReply()` operator instead. `logAndReply` can only be used at the end of a flow. [[java-dsl-intercept]] === Operator intercept() Starting with version 5.3, the `intercept()` operator allows to register one or more `ChannelInterceptor` instances at the current `MessageChannel` in the flow. This is an alternative to creating an explicit `MessageChannel` via the `MessageChannels` API. The following example uses a `MessageSelectingInterceptor` to reject certain messages with an exception: ==== [source,java] ---- .transform(...) .intercept(new MessageSelectingInterceptor(m -> m.getPayload().isValid())) .handle(...) ---- ==== [[java-dsl-wiretap]] === `MessageChannelSpec.wireTap()` Spring Integration includes a `.wireTap()` fluent API `MessageChannelSpec` builders. The following example shows how to use the `wireTap` method to log input: ==== [source,java] ---- @Bean public QueueChannelSpec myChannel() { return MessageChannels.queue() .wireTap(""loggingFlow.input""); } @Bean public IntegrationFlow loggingFlow() { return f -> f.log(); } ---- ==== [IMPORTANT] ==== If the `MessageChannel` is an instance of `InterceptableChannel`, the `log()`, `wireTap()` or `intercept()` operators are applied to the current `MessageChannel`. Otherwise, an intermediate `DirectChannel` is injected into the flow for the currently configured endpoint. In the following example, the `WireTap` interceptor is added to `myChannel` directly, because `DirectChannel` implements `InterceptableChannel`: [source,java] ---- @Bean MessageChannel myChannel() { return new DirectChannel(); } ... .channel(myChannel()) .log() } ---- ==== When the current `MessageChannel` does not implement `InterceptableChannel`, an implicit `DirectChannel` and `BridgeHandler` are injected into the `IntegrationFlow`, and the `WireTap` is added to this new `DirectChannel`. The following example does not have any channel declaration: ==== [source,java] ---- .handle(...) .log() } ---- ==== In the preceding example (and any time no channel has been declared), an implicit `DirectChannel` is injected in the current position of the `IntegrationFlow` and used as an output channel for the currently configured `ServiceActivatingHandler` (from the `.handle()`, <>). [[java-dsl-flows]] === Working With Message Flows `IntegrationFlowBuilder` provides a top-level API to produce integration components wired to message flows. When your integration may be accomplished with a single flow (which is often the case), this is convenient. Alternately `IntegrationFlow` instances can be joined via `MessageChannel` instances. By default, `MessageFlow` behaves as a ""`chain`"" in Spring Integration parlance. That is, the endpoints are automatically and implicitly wired by `DirectChannel` instances. The message flow is not actually constructed as a chain, which offers much more flexibility. For example, you may send a message to any component within the flow, if you know its `inputChannel` name (that is, if you explicitly define it). You may also reference externally defined channels within a flow to allow the use of channel adapters (to enable remote transport protocols, file I/O, and so on), instead of direct channels. As such, the DSL does not support the Spring Integration `chain` element, because it does not add much value in this case. Since the Spring Integration Java DSL produces the same bean definition model as any other configuration options and is based on the existing Spring Framework `@Configuration` infrastructure, it can be used together with XML definitions and wired with Spring Integration messaging annotation configuration. You can also define direct `IntegrationFlow` instances by using a lambda. The following example shows how to do so: ==== [source,java] ---- @Bean public IntegrationFlow lambdaFlow() { return f -> f.filter(""World""::equals) .transform(""Hello ""::concat) .handle(System.out::println); } ---- ==== The result of this definition is the same set of integration components that are wired with an implicit direct channel. The only limitation here is that this flow is started with a named direct channel - `lambdaFlow.input`. Also, a Lambda flow cannot start from `MessageSource` or `MessageProducer`. Starting with version 5.1, this kind of `IntegrationFlow` is wrapped to the proxy to expose lifecycle control and provide access to the `inputChannel` of the internally associated `StandardIntegrationFlow`. Starting with version 5.0.6, the generated bean names for the components in an `IntegrationFlow` include the flow bean followed by a dot (`.`) as a prefix. For example, the `ConsumerEndpointFactoryBean` for the `.transform(""Hello ""::concat)` in the preceding sample results in a bean name of `lambdaFlow.o.s.i.config.ConsumerEndpointFactoryBean#0`. (The `o.s.i` is a shortened from `org.springframework.integration` to fit on the page.) The `Transformer` implementation bean for that endpoint has a bean name of `lambdaFlow.transformer#0` (starting with version 5.1), where instead of a fully qualified name of the `MethodInvokingTransformer` class, its component type is used. The same pattern is applied for all the `NamedComponent` s when the bean name has to be generated within the flow. These generated bean names are prepended with the flow ID for purposes such as parsing logs or grouping components together in some analysis tool, as well as to avoid a race condition when we concurrently register integration flows at runtime. See <> for more information. [[java-dsl-function-expression]] === `FunctionExpression` We introduced the `FunctionExpression` class (an implementation of SpEL's `Expression` interface) to let us use lambdas and `generics`. The `Function` option is provided for the DSL components, along with an `expression` option, when there is the implicit `Strategy` variant from Core Spring Integration. The following example shows how to use a function expression: ==== [source,java] ---- .enrich(e -> e.requestChannel(""enrichChannel"") .requestPayload(Message::getPayload) .propertyFunction(""date"", m -> new Date())) ---- ==== The `FunctionExpression` also supports runtime type conversion, as is done in `SpelExpression`. [[java-dsl-subflows]] === Sub-flows support Some of `if...else` and `publish-subscribe` components provide the ability to specify their logic or mapping by using sub-flows. The simplest sample is `.publishSubscribeChannel()`, as the following example shows: ==== [source,java] ---- @Bean public IntegrationFlow subscribersFlow() { return flow -> flow .publishSubscribeChannel(Executors.newCachedThreadPool(), s -> s .subscribe(f -> f .handle((p, h) -> p / 2) .channel(c -> c.queue(""subscriber1Results""))) .subscribe(f -> f .handle((p, h) -> p * 2) .channel(c -> c.queue(""subscriber2Results"")))) .handle((p, h) -> p * 3) .channel(c -> c.queue(""subscriber3Results"")); } ---- ==== You can achieve the same result with separate `IntegrationFlow` `@Bean` definitions, but we hope you find the sub-flow style of logic composition useful. We find that it results in shorter (and so more readable) code. Starting with version 5.3, a `BroadcastCapableChannel`-based `publishSubscribeChannel()` implementation is provided to configure sub-flow subscribers on broker-backed message channels. For example we now can configure several subscribers as sub-flows on the `Jms.publishSubscribeChannel()`: ==== [source,java] ---- @Bean public BroadcastCapableChannel jmsPublishSubscribeChannel() { return Jms.publishSubscribeChannel(jmsConnectionFactory()) .destination(""pubsub"") .get(); } @Bean public IntegrationFlow pubSubFlow() { return f -> f .publishSubscribeChannel(jmsPublishSubscribeChannel(), pubsub -> pubsub .subscribe(subFlow -> subFlow .channel(c -> c.queue(""jmsPubSubBridgeChannel1""))) .subscribe(subFlow -> subFlow .channel(c -> c.queue(""jmsPubSubBridgeChannel2"")))); } @Bean public BroadcastCapableChannel jmsPublishSubscribeChannel(ConnectionFactory jmsConnectionFactory) { return (BroadcastCapableChannel) Jms.publishSubscribeChannel(jmsConnectionFactory) .destination(""pubsub"") .get(); } ---- ==== A similar `publish-subscribe` sub-flow composition provides the `.routeToRecipients()` method. Another example is using `.discardFlow()` instead of `.discardChannel()` on the `.filter()` method. The `.route()` deserves special attention. Consider the following example: ==== [source,java] ---- @Bean public IntegrationFlow routeFlow() { return f -> f .route(p -> p % 2 == 0, m -> m.channelMapping(""true"", ""evenChannel"") .subFlowMapping(""false"", sf -> sf.handle((p, h) -> p * 3))) .transform(Object::toString) .channel(c -> c.queue(""oddChannel"")); } ---- ==== The `.channelMapping()` continues to work as it does in regular `Router` mapping, but the `.subFlowMapping()` tied that sub-flow to the main flow. In other words, any router's sub-flow returns to the main flow after `.route()`. [IMPORTANT] ==== Sometimes, you need to refer to an existing `IntegrationFlow` `@Bean` from the `.subFlowMapping()`. The following example shows how to do so: [source,java] ---- @Bean public IntegrationFlow splitRouteAggregate() { return f -> f .split() .route(o -> o % 2 == 0, m -> m .subFlowMapping(true, oddFlow()) .subFlowMapping(false, sf -> sf.gateway(evenFlow()))) .aggregate(); } @Bean public IntegrationFlow oddFlow() { return f -> f.handle(m -> System.out.println(""odd"")); } @Bean public IntegrationFlow evenFlow() { return f -> f.handle((p, h) -> ""even""); } ---- {empty} + In this case, when you need to receive a reply from such a sub-flow and continue the main flow, this `IntegrationFlow` bean reference (or its input channel) has to be wrapped with a `.gateway()` as shown in the preceding example. The `oddFlow()` reference in the preceding example is not wrapped to the `.gateway()`. Therefore, we do not expect a reply from this routing branch. Otherwise, you end up with an exception similar to the following: .... Caused by: org.springframework.beans.factory.BeanCreationException: The 'currentComponent' (org.springframework.integration.router.MethodInvokingRouter@7965a51c) is a one-way 'MessageHandler' and it isn't appropriate to configure 'outputChannel'. This is the end of the integration flow. .... When you configure a sub-flow as a lambda, the framework handles the request-reply interaction with the sub-flow and a gateway is not needed. ==== Sub-flows can be nested to any depth, but we do not recommend doing so. In fact, even in the router case, adding complex sub-flows within a flow would quickly begin to look like a plate of spaghetti and be difficult for a human to parse. [NOTE] ==== In cases where the DSL supports a subflow configuration, when a channel is normally needed for the component being configured, and that subflow starts with a `channel()` element, the framework implicitly places a `bridge()` between the component output channel and the flow's input channel. For example, in this `filter` definition: [source,java] ---- .filter(p -> p instanceof String, e -> e .discardFlow(df -> df .channel(MessageChannels.queue()) ...) ---- the Framework internally creates a `DirectChannel` bean for injecting into the `MessageFilter.discardChannel`. Then it wraps the subflow into an `IntegrationFlow` starting with this implicit channel for the subscription and places a `bridge` before the `channel()` specified in the flow. When an existing `IntegrationFlow` bean is used as a subflow reference (instead of an inline subflow, e.g. a lambda), there is no such bridge required because the framework can resolve the first channel from the flow bean. With an inline subflow, the input channel is not yet available. ==== [[java-dsl-protocol-adapters]] === Using Protocol Adapters All of the examples shown so far illustrate how the DSL supports a messaging architecture by using the Spring Integration programming model. However, we have yet to do any real integration. Doing so requires access to remote resources over HTTP, JMS, AMQP, TCP, JDBC, FTP, SMTP, and so on or access to the local file system. Spring Integration supports all of these and more. Ideally, the DSL should offer first class support for all of them, but it is a daunting task to implement all of these and keep up as new adapters are added to Spring Integration. So the expectation is that the DSL is continually catching up with Spring Integration. Consequently, we provide the high-level API to seamlessly define protocol-specific messaging. We do so with the factory and builder patterns and with lambdas. You can think of the factory classes as ""`Namespace Factories`"", because they play the same role as the XML namespace for components from the concrete protocol-specific Spring Integration modules. Currently, Spring Integration Java DSL supports the `Amqp`, `Feed`, `Jms`, `Files`, `(S)Ftp`, `Http`, `JPA`, `MongoDb`, `TCP/UDP`, `Mail`, `WebFlux`, and `Scripts` namespace factories. The following example shows how to use three of them (`Amqp`, `Jms`, and `Mail`): ==== [source,java] ---- @Bean public IntegrationFlow amqpFlow() { return IntegrationFlows.from(Amqp.inboundGateway(this.rabbitConnectionFactory, queue())) .transform(""hello ""::concat) .transform(String.class, String::toUpperCase) .get(); } @Bean public IntegrationFlow jmsOutboundGatewayFlow() { return IntegrationFlows.from(""jmsOutboundGatewayChannel"") .handle(Jms.outboundGateway(this.jmsConnectionFactory) .replyContainer(c -> c.concurrentConsumers(3) .sessionTransacted(true)) .requestDestination(""jmsPipelineTest"")) .get(); } @Bean public IntegrationFlow sendMailFlow() { return IntegrationFlows.from(""sendMailChannel"") .handle(Mail.outboundAdapter(""localhost"") .port(smtpPort) .credentials(""user"", ""pw"") .protocol(""smtp"") .javaMailProperties(p -> p.put(""mail.debug"", ""true"")), e -> e.id(""sendMailEndpoint"")) .get(); } ---- ==== The preceding example shows how to use the ""`namespace factories`"" as inline adapters declarations. However, you can use them from `@Bean` definitions to make the `IntegrationFlow` method chain more readable. NOTE: We are soliciting community feedback on these namespace factories before we spend effort on others. We also appreciate any input into prioritization for which adapters and gateways we should support next. You can find more Java DSL samples in the protocol-specific chapters throughout this reference manual. All other protocol channel adapters may be configured as generic beans and wired to the `IntegrationFlow`, as the following examples show: ==== [source,java] ---- @Bean public QueueChannelSpec wrongMessagesChannel() { return MessageChannels .queue() .wireTap(""wrongMessagesWireTapChannel""); } @Bean public IntegrationFlow xpathFlow(MessageChannel wrongMessagesChannel) { return IntegrationFlows.from(""inputChannel"") .filter(new StringValueTestXPathMessageSelector(""namespace-uri(/*)"", ""my:namespace""), e -> e.discardChannel(wrongMessagesChannel)) .log(LoggingHandler.Level.ERROR, ""test.category"", m -> m.getHeaders().getId()) .route(xpathRouter(wrongMessagesChannel)) .get(); } @Bean public AbstractMappingMessageRouter xpathRouter(MessageChannel wrongMessagesChannel) { XPathRouter router = new XPathRouter(""local-name(/*)""); router.setEvaluateAsString(true); router.setResolutionRequired(false); router.setDefaultOutputChannel(wrongMessagesChannel); router.setChannelMapping(""Tags"", ""splittingChannel""); router.setChannelMapping(""Tag"", ""receivedChannel""); return router; } ---- ==== [[java-dsl-flow-adapter]] === `IntegrationFlowAdapter` The `IntegrationFlow` interface can be implemented directly and specified as a component for scanning, as the following example shows: ==== [source,java] ---- @Component public class MyFlow implements IntegrationFlow { @Override public void configure(IntegrationFlowDefinition f) { f.transform(String::toUpperCase); } } ---- ==== It is picked up by the `IntegrationFlowBeanPostProcessor` and correctly parsed and registered in the application context. For convenience and to gain the benefits of loosely coupled architecture, we provide the `IntegrationFlowAdapter` base class implementation. It requires a `buildFlow()` method implementation to produce an `IntegrationFlowDefinition` by using one of `from()` methods, as the following example shows: ==== [source,java] ---- @Component public class MyFlowAdapter extends IntegrationFlowAdapter { private final AtomicBoolean invoked = new AtomicBoolean(); public Date nextExecutionTime(TriggerContext triggerContext) { return this.invoked.getAndSet(true) ? null : new Date(); } @Override protected IntegrationFlowDefinition buildFlow() { return from(this::messageSource, e -> e.poller(p -> p.trigger(this::nextExecutionTime))) .split(this) .transform(this) .aggregate(a -> a.processor(this, null), null) .enrichHeaders(Collections.singletonMap(""thing1"", ""THING1"")) .filter(this) .handle(this) .channel(c -> c.queue(""myFlowAdapterOutput"")); } public String messageSource() { return ""T,H,I,N,G,2""; } @Splitter public String[] split(String payload) { return StringUtils.commaDelimitedListToStringArray(payload); } @Transformer public String transform(String payload) { return payload.toLowerCase(); } @Aggregator public String aggregate(List payloads) { return payloads.stream().collect(Collectors.joining()); } @Filter public boolean filter(@Header Optional thing1) { return thing1.isPresent(); } @ServiceActivator public String handle(String payload, @Header String thing1) { return payload + "":"" + thing1; } } ---- ==== [[java-dsl-runtime-flows]] === Dynamic and Runtime Integration Flows `IntegrationFlow` and all its dependent components can be registered at runtime. Before version 5.0, we used the `BeanFactory.registerSingleton()` hook. Starting in the Spring Framework `5.0`, we use the `instanceSupplier` hook for programmatic `BeanDefinition` registration. The following example shows how to programmatically register a bean: ==== [source,java] ---- BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition((Class) bean.getClass(), () -> bean) .getRawBeanDefinition(); ((BeanDefinitionRegistry) this.beanFactory).registerBeanDefinition(beanName, beanDefinition); ---- ==== Note that, in the preceding example, the `instanceSupplier` hook is the last parameter to the `genericBeanDefinition` method, provided by a lambda in this case. All the necessary bean initialization and lifecycle is done automatically, as it is with the standard context configuration bean definitions. To simplify the development experience, Spring Integration introduced `IntegrationFlowContext` to register and manage `IntegrationFlow` instances at runtime, as the following example shows: ==== [source,java] ---- @Autowired private AbstractServerConnectionFactory server1; @Autowired private IntegrationFlowContext flowContext; ... @Test public void testTcpGateways() { TestingUtilities.waitListening(this.server1, null); IntegrationFlow flow = f -> f .handle(Tcp.outboundGateway(Tcp.netClient(""localhost"", this.server1.getPort()) .serializer(TcpCodecs.crlf()) .deserializer(TcpCodecs.lengthHeader1()) .id(""client1"")) .remoteTimeout(m -> 5000)) .transform(Transformers.objectToString()); IntegrationFlowRegistration theFlow = this.flowContext.registration(flow).register(); assertThat(theFlow.getMessagingTemplate().convertSendAndReceive(""foo"", String.class), equalTo(""FOO"")); } ---- ==== This is useful when we have multiple configuration options and have to create several instances of similar flows. To do so, we can iterate our options and create and register `IntegrationFlow` instances within a loop. Another variant is when our source of data is not Spring-based and we must create it on the fly. Such a sample is Reactive Streams event source, as the following example shows: ==== [source,java] ---- Flux> messageFlux = Flux.just(""1,2,3,4"") .map(v -> v.split("","")) .flatMapIterable(Arrays::asList) .map(Integer::parseInt) .map(GenericMessage::new); QueueChannel resultChannel = new QueueChannel(); IntegrationFlow integrationFlow = IntegrationFlows.from(messageFlux) .transform(p -> p * 2) .channel(resultChannel) .get(); this.integrationFlowContext.registration(integrationFlow) .register(); ---- ==== The `IntegrationFlowRegistrationBuilder` (as a result of the `IntegrationFlowContext.registration()`) can be used to specify a bean name for the `IntegrationFlow` to register, to control its `autoStartup`, and to register, non-Spring Integration beans. Usually, those additional beans are connection factories (AMQP, JMS, (S)FTP, TCP/UDP, and others.), serializers and deserializers, or any other required support components. You can use the `IntegrationFlowRegistration.destroy()` callback to remove a dynamically registered `IntegrationFlow` and all its dependent beans when you no longer need them. See the https://docs.spring.io/spring-integration/api/org/springframework/integration/dsl/context/IntegrationFlowContext.html[`IntegrationFlowContext` Javadoc] for more information. NOTE: Starting with version 5.0.6, all generated bean names in an `IntegrationFlow` definition are prepended with the flow ID as a prefix. We recommend always specifying an explicit flow ID. Otherwise, a synchronization barrier is initiated in the `IntegrationFlowContext`, to generate the bean name for the `IntegrationFlow` and register its beans. We synchronize on these two operations to avoid a race condition when the same generated bean name may be used for different `IntegrationFlow` instances. Also, starting with version 5.0.6, the registration builder API has a new method: `useFlowIdAsPrefix()`. This is useful if you wish to declare multiple instances of the same flow and avoid bean name collisions when components in the flows have the same ID, as the following example shows: ==== [source, java] ---- private void registerFlows() { IntegrationFlowRegistration flow1 = this.flowContext.registration(buildFlow(1234)) .id(""tcp1"") .useFlowIdAsPrefix() .register(); IntegrationFlowRegistration flow2 = this.flowContext.registration(buildFlow(1235)) .id(""tcp2"") .useFlowIdAsPrefix() .register(); } private IntegrationFlow buildFlow(int port) { return f -> f .handle(Tcp.outboundGateway(Tcp.netClient(""localhost"", port) .serializer(TcpCodecs.crlf()) .deserializer(TcpCodecs.lengthHeader1()) .id(""client"")) .remoteTimeout(m -> 5000)) .transform(Transformers.objectToString()); } ---- ==== In this case, the message handler for the first flow can be referenced with bean a name of `tcp1.client.handler`. NOTE: An `id` attribute is required when you usE `useFlowIdAsPrefix()`. [[integration-flow-as-gateway]] === `IntegrationFlow` as a Gateway The `IntegrationFlow` can start from the service interface that provides a `GatewayProxyFactoryBean` component, as the following example shows: ==== [source,java] ---- public interface ControlBusGateway { void send(String command); } ... @Bean public IntegrationFlow controlBusFlow() { return IntegrationFlows.from(ControlBusGateway.class) .controlBus() .get(); } ---- ==== All the proxy for interface methods are supplied with the channel to send messages to the next integration component in the `IntegrationFlow`. You can mark the service interface with the `@MessagingGateway` annotation and mark the methods with the `@Gateway` annotations. Nevertheless, the `requestChannel` is ignored and overridden with that internal channel for the next component in the `IntegrationFlow`. Otherwise, creating such a configuration by using `IntegrationFlow` does not make sense. By default a `GatewayProxyFactoryBean` gets a conventional bean name, such as `[FLOW_BEAN_NAME.gateway]`. You can change that ID by using the `@MessagingGateway.name()` attribute or the overloaded `IntegrationFlows.from(Class serviceInterface, Consumer endpointConfigurer)` factory method. Also all the attributes from the `@MessagingGateway` annotation on the interface are applied to the target `GatewayProxyFactoryBean`. When annotation configuration is not applicable, the `Consumer` variant can be used for providing appropriate option for the target proxy. This DSL method is available starting with version 5.2. With Java 8, you can even create an integration gateway with the `java.util.function` interfaces, as the following example shows: ==== [source,java] ---- @Bean public IntegrationFlow errorRecovererFlow() { return IntegrationFlows.from(Function.class, (gateway) -> gateway.beanName(""errorRecovererFunction"")) .handle((GenericHandler) (p, h) -> { throw new RuntimeException(""intentional""); }, e -> e.advice(retryAdvice())) .get(); } ---- ==== That `errorRecovererFlow` can be used as follows: ==== [source,java] ---- @Autowired @Qualifier(""errorRecovererFunction"") private Function errorRecovererFlowGateway; ---- ==== [[java-dsl-extensions]] === DSL Extensions Starting with version 5.3, an `IntegrationFlowExtension` has been introduced to allow extension of the existing Java DSL with custom or composed EIP-operators. All that is needed is an extension of this class that provides methods which can be used in the `IntegrationFlow` bean definitions. The extension class can also be used for custom `IntegrationComponentSpec` configuration; for example, missed or default options can be implemented in the existing `IntegrationComponentSpec` extension. The sample below demonstrates a composite custom operator and usage of an `AggregatorSpec` extension for a default custom `outputProcessor`: ==== [source,java] ---- public class CustomIntegrationFlowDefinition extends IntegrationFlowExtension { public CustomIntegrationFlowDefinition upperCaseAfterSplit() { return split() .transform(""payload.toUpperCase()""); } public CustomIntegrationFlowDefinition customAggregate(Consumer aggregator) { return register(new CustomAggregatorSpec(), aggregator); } } public class CustomAggregatorSpec extends AggregatorSpec { CustomAggregatorSpec() { outputProcessor(group -> group.getMessages() .stream() .map(Message::getPayload) .map(String.class::cast) .collect(Collectors.joining("", ""))); } } ---- ==== For a method chain flow the new DSL operator in these extensions must return the extension class. This way a target `IntegrationFlow` definition will work with new and existing DSL operators: ==== [source,java] ---- @Bean public IntegrationFlow customFlowDefinition() { return new CustomIntegrationFlowDefinition() .log() .upperCaseAfterSplit() .channel(""innerChannel"") .customAggregate(customAggregatorSpec -> customAggregatorSpec.expireGroupsUponCompletion(true)) .logAndReply(); } ---- ==== ",12124,False,2497.5346257678475,median "// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the ""Irrlicht Engine"". // For conditions of distribution and use, see copyright notice in irrlicht.h #include #include #include #include #include #include #include ""os.h"" #include ""irr/asset/asset.h"" #include ""irr/asset/CMeshManipulator.h"" #include ""irr/asset/CSmoothNormalGenerator.h"" #include ""irr/asset/CForsythVertexCacheOptimizer.h"" #include ""irr/asset/COverdrawMeshOptimizer.h"" namespace irr { namespace asset { //! Flips the direction of surfaces. Changes backfacing triangles to frontfacing //! triangles and vice versa. //! \\param mesh: Mesh on which the operation is performed. void IMeshManipulator::flipSurfaces(ICPUMeshBuffer* inbuffer) { #ifndef NEW_SHADERS if (!inbuffer) return; const uint32_t idxcnt = inbuffer->getIndexCount(); if (!inbuffer->getIndices()) return; if (inbuffer->getIndexType() == EIT_16BIT) { uint16_t* idx = reinterpret_cast(inbuffer->getIndices()); switch (inbuffer->getPrimitiveType()) { case EPT_TRIANGLE_FAN: for (uint32_t i=1; i>1); i++) { const uint16_t tmp = idx[i]; idx[i] = idx[idxcnt-1-i]; idx[idxcnt-1-i] = tmp; } } else //even { auto newIndexBuffer = core::make_smart_refctd_ptr((idxcnt+1u)*sizeof(uint16_t)); auto* destPtr = reinterpret_cast(newIndexBuffer->getPointer()); destPtr[0] = idx[0]; memcpy(destPtr+1u,idx,sizeof(uint16_t)*idxcnt); inbuffer->setIndexCount(idxcnt+1u); inbuffer->setIndexBufferOffset(0); inbuffer->getMeshDataAndFormat()->setIndexBuffer(std::move(newIndexBuffer)); } break; case EPT_TRIANGLES: for (uint32_t i=0; igetIndexType() == EIT_32BIT) { uint32_t* idx = reinterpret_cast(inbuffer->getIndices()); switch (inbuffer->getPrimitiveType()) { case EPT_TRIANGLE_FAN: for (uint32_t i=1; i>1); i++) { const uint32_t tmp = idx[i]; idx[i] = idx[idxcnt-1-i]; idx[idxcnt-1-i] = tmp; } } else //even { auto newIndexBuffer = core::make_smart_refctd_ptr((idxcnt+1u)*sizeof(uint32_t)); auto* destPtr = reinterpret_cast(newIndexBuffer->getPointer()); destPtr[0] = idx[0]; memcpy(destPtr+1u,idx,sizeof(uint32_t)*idxcnt); inbuffer->setIndexCount(idxcnt+1); inbuffer->setIndexBufferOffset(0); inbuffer->getMeshDataAndFormat()->setIndexBuffer(std::move(newIndexBuffer)); } break; case EPT_TRIANGLES: for (uint32_t i=0; i CMeshManipulator::createMeshBufferFetchOptimized(const ICPUMeshBuffer* _inbuffer) { #ifndef NEW_SHADERS if (!_inbuffer || !_inbuffer->getMeshDataAndFormat() || !_inbuffer->getIndices()) return NULL; auto outbuffer = createMeshBufferDuplicate(_inbuffer); IMeshDataFormatDesc* outDesc = outbuffer->getMeshDataAndFormat(); // Find vertex count size_t vertexCount = _inbuffer->calcVertexCount(); const void* ind = _inbuffer->getIndices(); core::unordered_set buffers; for (size_t i = 0; i < EVAI_COUNT; ++i) buffers.insert(outDesc->getMappedBuffer((E_VERTEX_ATTRIBUTE_ID)i)); size_t offsets[EVAI_COUNT]; memset(offsets, -1, sizeof(offsets)); E_FORMAT types[EVAI_COUNT]; if (buffers.size() != 1) { size_t lastOffset = 0u; size_t lastSize = 0u; for (size_t i = 0; i < EVAI_COUNT; ++i) { if (outDesc->getMappedBuffer((E_VERTEX_ATTRIBUTE_ID)i)) { types[i] = outDesc->getAttribFormat((E_VERTEX_ATTRIBUTE_ID)i); const uint32_t typeSz = getTexelOrBlockBytesize(types[i]); const size_t alignment = (typeSz/getFormatChannelCount(types[i]) == 8u) ? 8ull : 4ull; // if format 64bit per channel, than align to 8 offsets[i] = lastOffset + lastSize; const size_t mod = offsets[i] % alignment; offsets[i] += mod; lastOffset = offsets[i]; lastSize = typeSz; } } const size_t vertexSize = lastOffset + lastSize; auto newVertBuffer = core::make_smart_refctd_ptr(vertexCount*vertexSize); for (size_t i = 0; i < EVAI_COUNT; ++i) { if (offsets[i] < 0xffffffff) { outDesc->setVertexAttrBuffer(core::smart_refctd_ptr(newVertBuffer), (E_VERTEX_ATTRIBUTE_ID)i, types[i], vertexSize, offsets[i]); } } } outbuffer->setBaseVertex(0); core::vector activeAttribs; for (size_t i = 0; i < EVAI_COUNT; ++i) if (outDesc->getMappedBuffer((E_VERTEX_ATTRIBUTE_ID)i)) activeAttribs.push_back((E_VERTEX_ATTRIBUTE_ID)i); uint32_t* remapBuffer = (uint32_t*)_IRR_ALIGNED_MALLOC(vertexCount*4,_IRR_SIMD_ALIGNMENT); memset(remapBuffer, 0xffffffffu, vertexCount*4); const E_INDEX_TYPE idxType = outbuffer->getIndexType(); void* indices = outbuffer->getIndices(); size_t nextVert = 0u; for (size_t i = 0; i < outbuffer->getIndexCount(); ++i) { const uint32_t index = idxType == EIT_32BIT ? ((uint32_t*)indices)[i] : ((uint16_t*)indices)[i]; uint32_t& remap = remapBuffer[index]; if (remap == 0xffffffffu) { for (size_t j = 0; j < activeAttribs.size(); ++j) { E_FORMAT type = types[activeAttribs[j]]; if (!isNormalizedFormat(type) && (isIntegerFormat(type) || isScaledFormat(type))) { uint32_t dst[4]; _inbuffer->getAttribute(dst, (E_VERTEX_ATTRIBUTE_ID)activeAttribs[j], index); outbuffer->setAttribute(dst, (E_VERTEX_ATTRIBUTE_ID)activeAttribs[j], nextVert); } else { core::vectorSIMDf dst; _inbuffer->getAttribute(dst, (E_VERTEX_ATTRIBUTE_ID)activeAttribs[j], index); outbuffer->setAttribute(dst, (E_VERTEX_ATTRIBUTE_ID)activeAttribs[j], nextVert); } } remap = nextVert++; } if (idxType == EIT_32BIT) ((uint32_t*)indices)[i] = remap; else ((uint16_t*)indices)[i] = remap; } _IRR_ALIGNED_FREE(remapBuffer); _IRR_DEBUG_BREAK_IF(nextVert > vertexCount) return outbuffer; #else return nullptr; #endif } //! Creates a copy of the mesh, which will only consist of unique primitives core::smart_refctd_ptr IMeshManipulator::createMeshBufferUniquePrimitives(ICPUMeshBuffer* inbuffer, bool _makeIndexBuf) { #ifndef NEW_SHADERS if (!inbuffer) return 0; IMeshDataFormatDesc* oldDesc = inbuffer->getMeshDataAndFormat(); if (!oldDesc) return 0; if (!inbuffer->getIndices()) return core::smart_refctd_ptr(inbuffer); // yes we want an extra grab const uint32_t idxCnt = inbuffer->getIndexCount(); auto clone = core::make_smart_refctd_ptr(); clone->setBoundingBox(inbuffer->getBoundingBox()); clone->setIndexCount(idxCnt); const E_PRIMITIVE_TYPE ept = inbuffer->getPrimitiveType(); clone->setPrimitiveType(ept); clone->getMaterial() = inbuffer->getMaterial(); { auto desc = core::make_smart_refctd_ptr(); size_t stride = 0; int32_t offset[EVAI_COUNT]; size_t newAttribSizes[EVAI_COUNT]; uint8_t* sourceBuffers[EVAI_COUNT] = {NULL}; size_t sourceBufferStrides[EVAI_COUNT]; for (size_t i=0; i< EVAI_COUNT; i++) { const ICPUBuffer* vbuf = oldDesc->getMappedBuffer((E_VERTEX_ATTRIBUTE_ID)i); if (vbuf) { offset[i] = stride; newAttribSizes[i] = getTexelOrBlockBytesize(oldDesc->getAttribFormat((E_VERTEX_ATTRIBUTE_ID)i)); stride += newAttribSizes[i]; if (stride>=0xdeadbeefu) return nullptr; sourceBuffers[i] = (uint8_t*)vbuf->getPointer(); sourceBuffers[i] += oldDesc->getMappedBufferOffset((E_VERTEX_ATTRIBUTE_ID)i); sourceBufferStrides[i] = oldDesc->getMappedBufferStride((E_VERTEX_ATTRIBUTE_ID)i); } else offset[i] = -1; } auto vertexBuffer = core::make_smart_refctd_ptr(stride*idxCnt); for (size_t i=0; i=0) desc->setVertexAttrBuffer(core::smart_refctd_ptr(vertexBuffer),(E_VERTEX_ATTRIBUTE_ID)i,oldDesc->getAttribFormat((E_VERTEX_ATTRIBUTE_ID)i),stride,offset[i]); } uint8_t* destPointer = (uint8_t*)vertexBuffer->getPointer(); if (inbuffer->getIndexType()==EIT_16BIT) { uint16_t* idx = reinterpret_cast(inbuffer->getIndices()); for (uint64_t i=0; igetBaseVertex())*sourceBufferStrides[j],newAttribSizes[j]); destPointer += newAttribSizes[j]; } } else if (inbuffer->getIndexType()==EIT_32BIT) { uint32_t* idx = reinterpret_cast(inbuffer->getIndices()); for (uint64_t i=0; igetBaseVertex())*sourceBufferStrides[j],newAttribSizes[j]); destPointer += newAttribSizes[j]; } } if (_makeIndexBuf) { auto idxbuf = core::make_smart_refctd_ptr(idxCnt*(idxCnt<0x10000 ? 2u : 4u)); if (idxCnt<0x10000u) { for (uint32_t i = 0u; i < idxCnt; ++i) reinterpret_cast(idxbuf->getPointer())[i] = i; clone->setIndexType(EIT_16BIT); clone->setIndexBufferOffset(0); } else { for (uint32_t i = 0u; i < idxCnt; ++i) reinterpret_cast(idxbuf->getPointer())[i] = i; clone->setIndexType(EIT_32BIT); clone->setIndexBufferOffset(0); } desc->setIndexBuffer(std::move(idxbuf)); } clone->setMeshDataAndFormat(std::move(desc)); } return clone; #else return nullptr; #endif } // core::smart_refctd_ptr IMeshManipulator::calculateSmoothNormals(ICPUMeshBuffer* inbuffer, bool makeNewMesh, float epsilon, uint32_t normalAttrID, VxCmpFunction vxcmp) { if (inbuffer == nullptr) { _IRR_DEBUG_BREAK_IF(true); return nullptr; } //Mesh has to have unique primitives if (inbuffer->getIndexType() != E_INDEX_TYPE::EIT_UNKNOWN) { _IRR_DEBUG_BREAK_IF(true); return nullptr; } auto outbuffer = makeNewMesh ? createMeshBufferDuplicate(inbuffer) : core::smart_refctd_ptr(inbuffer); CSmoothNormalGenerator::calculateNormals(outbuffer.get(), epsilon, normalAttrID, vxcmp); return outbuffer; } // Used by createMeshBufferWelded only static bool cmpVertices(ICPUMeshBuffer* _inbuf, const void* _va, const void* _vb, size_t _vsize, const IMeshManipulator::SErrorMetric* _errMetrics) { #ifndef NEW_SHADERS auto cmpInteger = [](uint32_t* _a, uint32_t* _b, size_t _n) -> bool { return !memcmp(_a, _b, _n*4); }; const uint8_t* va = (uint8_t*)_va, *vb = (uint8_t*)_vb; auto desc = _inbuf->getMeshDataAndFormat(); for (size_t i = 0u; i < EVAI_COUNT; ++i) { if (!desc->getMappedBuffer((E_VERTEX_ATTRIBUTE_ID)i)) continue; const auto atype = desc->getAttribFormat((E_VERTEX_ATTRIBUTE_ID)i); const auto cpa = getFormatChannelCount(atype); if (isIntegerFormat(atype) || isScaledFormat(atype)) { uint32_t attr[8]; ICPUMeshBuffer::getAttribute(attr, va, atype); ICPUMeshBuffer::getAttribute(attr+4, vb, atype); if (!cmpInteger(attr, attr+4, cpa)) return false; } else { core::vectorSIMDf attr[2]; ICPUMeshBuffer::getAttribute(attr[0], va, atype); ICPUMeshBuffer::getAttribute(attr[1], vb, atype); if (!IMeshManipulator::compareFloatingPointAttribute(attr[0], attr[1], cpa, _errMetrics[i])) return false; } const uint32_t sz = getTexelOrBlockBytesize(atype); va += sz; vb += sz; } return true; #else return false; #endif } //! Creates a copy of a mesh, which will have identical vertices welded together core::smart_refctd_ptr IMeshManipulator::createMeshBufferWelded(ICPUMeshBuffer *inbuffer, const SErrorMetric* _errMetrics, const bool& optimIndexType, const bool& makeNewMesh) { #ifndef NEW_SHADERS if (!inbuffer) return nullptr; IMeshDataFormatDesc* oldDesc = inbuffer->getMeshDataAndFormat(); if (!oldDesc) return nullptr; bool bufferPresent[EVAI_COUNT]; size_t vertexAttrSize[EVAI_COUNT]; size_t vertexSize = 0; for (size_t i=0; igetMappedBuffer((E_VERTEX_ATTRIBUTE_ID)i); bufferPresent[i] = buf; if (buf) { const E_FORMAT componentType = oldDesc->getAttribFormat((E_VERTEX_ATTRIBUTE_ID)i); vertexAttrSize[i] = getTexelOrBlockBytesize(componentType); vertexSize += vertexAttrSize[i]; } } auto cmpfunc = [&, inbuffer, vertexSize, _errMetrics](const void* _va, const void* _vb) { return cmpVertices(inbuffer, _va, _vb, vertexSize, _errMetrics); }; size_t vertexCount = inbuffer->calcVertexCount(); E_INDEX_TYPE oldIndexType = inbuffer->getIndexType(); if (vertexCount==0) return nullptr; // reset redirect list uint32_t* redirects = new uint32_t[vertexCount]; uint32_t maxRedirect = 0; uint8_t* epicData = (uint8_t*)_IRR_ALIGNED_MALLOC(vertexSize*vertexCount,_IRR_SIMD_ALIGNMENT); for (size_t i=0; i < vertexCount; i++) { uint8_t* currentVertexPtr = epicData+i*vertexSize; for (size_t k=0; kgetMappedBufferStride((E_VERTEX_ATTRIBUTE_ID)k); uint8_t* sourcePtr = inbuffer->getAttribPointer((E_VERTEX_ATTRIBUTE_ID)k)+i*stride; memcpy(currentVertexPtr,sourcePtr,vertexAttrSize[k]); currentVertexPtr += vertexAttrSize[k]; } } for (size_t i=0; imaxRedirect) maxRedirect = redir; } _IRR_ALIGNED_FREE(epicData); void* oldIndices = inbuffer->getIndices(); core::smart_refctd_ptr clone; if (makeNewMesh) clone = createMeshBufferDuplicate(inbuffer); else { if (!oldDesc->getIndexBuffer()) { oldDesc->setIndexBuffer(core::make_smart_refctd_ptr((maxRedirect >= 0x10000u ? sizeof(uint32_t) : sizeof(uint16_t)) * inbuffer->getIndexCount())); inbuffer->setIndexType(maxRedirect>=0x10000u ? EIT_32BIT:EIT_16BIT); } } if (oldIndexType==EIT_16BIT) { uint16_t* indicesIn = reinterpret_cast(oldIndices); if ((makeNewMesh ? clone.get():inbuffer)->getIndexType()==EIT_32BIT) { uint32_t* indicesOut = reinterpret_cast((makeNewMesh ? clone.get():inbuffer)->getIndices()); for (size_t i=0; igetIndexCount(); i++) indicesOut[i] = redirects[indicesIn[i]]; } else if ((makeNewMesh ? clone.get():inbuffer)->getIndexType()==EIT_16BIT) { uint16_t* indicesOut = reinterpret_cast((makeNewMesh ? clone.get():inbuffer)->getIndices()); for (size_t i=0; igetIndexCount(); i++) indicesOut[i] = redirects[indicesIn[i]]; } } else if (oldIndexType==EIT_32BIT) { uint32_t* indicesIn = reinterpret_cast(oldIndices); if ((makeNewMesh ? clone.get():inbuffer)->getIndexType()==EIT_32BIT) { uint32_t* indicesOut = reinterpret_cast((makeNewMesh ? clone.get():inbuffer)->getIndices()); for (size_t i=0; igetIndexCount(); i++) indicesOut[i] = redirects[indicesIn[i]]; } else if ((makeNewMesh ? clone.get():inbuffer)->getIndexType()==EIT_16BIT) { uint16_t* indicesOut = reinterpret_cast((makeNewMesh ? clone.get():inbuffer)->getIndices()); for (size_t i=0; igetIndexCount(); i++) indicesOut[i] = redirects[indicesIn[i]]; } } else if ((makeNewMesh ? clone.get():inbuffer)->getIndexType()==EIT_32BIT) { uint32_t* indicesOut = reinterpret_cast((makeNewMesh ? clone.get():inbuffer)->getIndices()); for (size_t i=0; igetIndexCount(); i++) indicesOut[i] = redirects[i]; } else if ((makeNewMesh ? clone.get():inbuffer)->getIndexType()==EIT_16BIT) { uint16_t* indicesOut = reinterpret_cast((makeNewMesh ? clone.get():inbuffer)->getIndices()); for (size_t i=0; igetIndexCount(); i++) indicesOut[i] = redirects[i]; } delete [] redirects; if (makeNewMesh) return clone; else return core::smart_refctd_ptr(inbuffer); #else return nullptr; #endif } core::smart_refctd_ptr IMeshManipulator::createOptimizedMeshBuffer(const ICPUMeshBuffer* _inbuffer, const SErrorMetric* _errMetric) { #ifndef NEW_SHADERS if (!_inbuffer) return nullptr; auto outbuffer = createMeshBufferDuplicate(_inbuffer); if (!outbuffer->getMeshDataAndFormat()) return outbuffer; // Find vertex count size_t vertexCount = outbuffer->calcVertexCount(); // make index buffer 0,1,2,3,4,... if nothing's mapped if (!outbuffer->getIndices()) { auto ib = core::make_smart_refctd_ptr(sizeof(uint32_t)*vertexCount); IMeshDataFormatDesc* newDesc = outbuffer->getMeshDataAndFormat(); uint32_t* indices = (uint32_t*)ib->getPointer(); for (uint32_t i = 0; i < vertexCount; ++i) indices[i] = i; newDesc->setIndexBuffer(std::move(ib)); outbuffer->setIndexCount(vertexCount); outbuffer->setIndexType(EIT_32BIT); } // make 32bit index buffer if 16bit one is present if (outbuffer->getIndexType() == EIT_16BIT) { IMeshDataFormatDesc* newDesc = outbuffer->getMeshDataAndFormat(); newDesc->setIndexBuffer(CMeshManipulator::create32BitFrom16BitIdxBufferSubrange(reinterpret_cast(outbuffer->getIndices()), outbuffer->getIndexCount())); // no need to set index buffer offset to 0 because it already is outbuffer->setIndexType(EIT_32BIT); } // convert index buffer for triangle primitives if (outbuffer->getPrimitiveType() == EPT_TRIANGLE_FAN) { IMeshDataFormatDesc* newDesc = outbuffer->getMeshDataAndFormat(); const ICPUBuffer* ib = newDesc->getIndexBuffer(); outbuffer->setPrimitiveType(EPT_TRIANGLES); auto newIb = idxBufferFromTrianglesFanToTriangles(outbuffer->getIndices(), outbuffer->getIndexCount(), EIT_32BIT); outbuffer->setIndexCount(newIb->getSize() / sizeof(uint32_t)); newDesc->setIndexBuffer(std::move(newIb)); } else if (outbuffer->getPrimitiveType() == EPT_TRIANGLE_STRIP) { IMeshDataFormatDesc* newDesc = outbuffer->getMeshDataAndFormat(); outbuffer->setPrimitiveType(EPT_TRIANGLES); auto newIb = idxBufferFromTriangleStripsToTriangles(outbuffer->getIndices(), outbuffer->getIndexCount(), EIT_32BIT); outbuffer->setIndexCount(newIb->getSize() / sizeof(uint32_t)); newDesc->setIndexBuffer(std::move(newIb)); } else if (outbuffer->getPrimitiveType() != EPT_TRIANGLES) return nullptr; // STEP: weld createMeshBufferWelded(outbuffer.get(), _errMetric, false, false); // STEP: filter invalid triangles filterInvalidTriangles(outbuffer.get()); // STEP: overdraw optimization COverdrawMeshOptimizer::createOptimized(outbuffer.get(), false); // STEP: Forsyth { uint32_t* indices = reinterpret_cast(outbuffer->getIndices()); CForsythVertexCacheOptimizer forsyth; forsyth.optimizeTriangleOrdering(vertexCount, outbuffer->getIndexCount(), indices, indices); } // STEP: prefetch optimization outbuffer = CMeshManipulator::createMeshBufferFetchOptimized(outbuffer.get()); // here we also get interleaved attributes (single vertex buffer) // STEP: requantization requantizeMeshBuffer(outbuffer.get(), _errMetric); // STEP: reduce index buffer to 16bit or completely get rid of it { const void* const indices = outbuffer->getIndices(); uint32_t* indicesCopy = (uint32_t*)_IRR_ALIGNED_MALLOC(outbuffer->getIndexCount()*4,_IRR_SIMD_ALIGNMENT); memcpy(indicesCopy, indices, outbuffer->getIndexCount()*4); std::sort(indicesCopy, indicesCopy + outbuffer->getIndexCount()); bool continuous = true; // indices are i.e. 0,1,2,3,4,5,... (also implies indices being unique) bool unique = true; // indices are unique (but not necessarily continuos) for (size_t i = 0; i < outbuffer->getIndexCount(); ++i) { uint32_t idx = indicesCopy[i], prevIdx = 0xffffffffu; if (i) { prevIdx = indicesCopy[i-1]; if (idx == prevIdx) { unique = false; continuous = false; break; } if (idx != prevIdx + 1) continuous = false; } } const uint32_t minIdx = indicesCopy[0]; const uint32_t maxIdx = indicesCopy[outbuffer->getIndexCount() - 1]; _IRR_ALIGNED_FREE(indicesCopy); core::smart_refctd_ptr newIdxBuffer; bool verticesMustBeReordered = false; E_INDEX_TYPE newIdxType = EIT_UNKNOWN; if (!continuous) { if (unique) { // no index buffer // vertices have to be reordered verticesMustBeReordered = true; } else { if (maxIdx - minIdx <= USHRT_MAX) newIdxType = EIT_16BIT; else newIdxType = EIT_32BIT; outbuffer->setBaseVertex(outbuffer->getBaseVertex() + minIdx); if (newIdxType == EIT_16BIT) { newIdxBuffer = core::make_smart_refctd_ptr(sizeof(uint16_t)*outbuffer->getIndexCount()); // no need to change index buffer offset because it's always 0 (after duplicating original mesh) for (size_t i = 0; i < outbuffer->getIndexCount(); ++i) reinterpret_cast(newIdxBuffer->getPointer())[i] = reinterpret_cast(indices)[i] - minIdx; } } } else { outbuffer->setBaseVertex(outbuffer->getBaseVertex()+minIdx); } outbuffer->setIndexType(newIdxType); outbuffer->getMeshDataAndFormat()->setIndexBuffer(std::move(newIdxBuffer)); if (verticesMustBeReordered) { // reorder vertices according to index buffer #define _ACCESS_IDX(n) ((newIdxType == EIT_32BIT) ? *(reinterpret_cast(indices)+(n)) : *(reinterpret_cast(indices)+(n))) const size_t vertexSize = outbuffer->getMeshDataAndFormat()->getMappedBufferStride(outbuffer->getPositionAttributeIx()); uint8_t* const v = (uint8_t*)(outbuffer->getMeshDataAndFormat()->getMappedBuffer(outbuffer->getPositionAttributeIx())->getPointer()); // after prefetch optim. we have guarantee of single vertex buffer so we can do like this uint8_t* const vCopy = (uint8_t*)_IRR_ALIGNED_MALLOC(outbuffer->getMeshDataAndFormat()->getMappedBuffer(outbuffer->getPositionAttributeIx())->getSize(),_IRR_SIMD_ALIGNMENT); memcpy(vCopy, v, outbuffer->getMeshDataAndFormat()->getMappedBuffer(outbuffer->getPositionAttributeIx())->getSize()); size_t baseVtx = outbuffer->getBaseVertex(); for (size_t i = 0; i < outbuffer->getIndexCount(); ++i) { const uint32_t idx = _ACCESS_IDX(i+baseVtx); if (idx != i+baseVtx) memcpy(v + (vertexSize*(i + baseVtx)), vCopy + (vertexSize*idx), vertexSize); } #undef _ACCESS_IDX _IRR_ALIGNED_FREE(vCopy); } } return outbuffer; #else return nullptr; #endif } void IMeshManipulator::requantizeMeshBuffer(ICPUMeshBuffer* _meshbuffer, const SErrorMetric* _errMetric) { #ifndef NEW_SHADERS CMeshManipulator::SAttrib newAttribs[EVAI_COUNT]; for (size_t i = 0u; i < EVAI_COUNT; ++i) newAttribs[i].vaid = (E_VERTEX_ATTRIBUTE_ID)i; core::unordered_map> attribsI; core::unordered_map> attribsF; for (size_t vaid = EVAI_ATTR0; vaid < (size_t)EVAI_COUNT; ++vaid) { const E_FORMAT type = _meshbuffer->getMeshDataAndFormat()->getAttribFormat((E_VERTEX_ATTRIBUTE_ID)vaid); if (_meshbuffer->getMeshDataAndFormat()->getMappedBuffer((E_VERTEX_ATTRIBUTE_ID)vaid)) { if (!isNormalizedFormat(type) && isIntegerFormat(type)) attribsI[(E_VERTEX_ATTRIBUTE_ID)vaid] = CMeshManipulator::findBetterFormatI(&newAttribs[vaid].type, &newAttribs[vaid].size, &newAttribs[vaid].prevType, _meshbuffer, (E_VERTEX_ATTRIBUTE_ID)vaid, _errMetric[vaid]); else attribsF[(E_VERTEX_ATTRIBUTE_ID)vaid] = CMeshManipulator::findBetterFormatF(&newAttribs[vaid].type, &newAttribs[vaid].size, &newAttribs[vaid].prevType, _meshbuffer, (E_VERTEX_ATTRIBUTE_ID)vaid, _errMetric[vaid]); } } const size_t activeAttributeCount = attribsI.size() + attribsF.size(); #ifdef _IRR_DEBUG { core::unordered_set sizesSet; for (core::unordered_map>::iterator it = attribsI.begin(); it != attribsI.end(); ++it) sizesSet.insert(it->second.size()); for (core::unordered_map>::iterator it = attribsF.begin(); it != attribsF.end(); ++it) sizesSet.insert(it->second.size()); _IRR_DEBUG_BREAK_IF(sizesSet.size() != 1); } #endif const size_t vertexCnt = (!attribsI.empty() ? attribsI.begin()->second.size() : (!attribsF.empty() ? attribsF.begin()->second.size() : 0)); std::sort(newAttribs, newAttribs + EVAI_COUNT, std::greater()); // sort decreasing by size for (size_t i = 0u; i < activeAttributeCount; ++i) { const uint32_t typeSz = getTexelOrBlockBytesize(newAttribs[i].type); const size_t alignment = (typeSz / getFormatChannelCount(newAttribs[i].type) == 8u) ? 8ull : 4ull; // if format 64bit per channel, than align to 8 newAttribs[i].offset = (i ? newAttribs[i - 1].offset + newAttribs[i - 1].size : 0u); const size_t mod = newAttribs[i].offset % alignment; newAttribs[i].offset += mod; } const size_t vertexSize = newAttribs[activeAttributeCount - 1].offset + newAttribs[activeAttributeCount - 1].size; IMeshDataFormatDesc* desc = _meshbuffer->getMeshDataAndFormat(); auto newVertexBuffer = core::make_smart_refctd_ptr(vertexCnt * vertexSize); for (size_t i = 0u; i < activeAttributeCount; ++i) { desc->setVertexAttrBuffer(core::smart_refctd_ptr(newVertexBuffer), newAttribs[i].vaid, newAttribs[i].type, vertexSize, newAttribs[i].offset); core::unordered_map>::iterator iti = attribsI.find(newAttribs[i].vaid); if (iti != attribsI.end()) { const core::vector& attrVec = iti->second; for (size_t ai = 0u; ai < attrVec.size(); ++ai) { const bool check = _meshbuffer->setAttribute(attrVec[ai].pointer, newAttribs[i].vaid, ai); _IRR_DEBUG_BREAK_IF(!check) } continue; } core::unordered_map>::iterator itf = attribsF.find(newAttribs[i].vaid); if (itf != attribsF.end()) { const core::vector& attrVec = itf->second; for (size_t ai = 0u; ai < attrVec.size(); ++ai) { const bool check = _meshbuffer->setAttribute(attrVec[ai], newAttribs[i].vaid, ai); _IRR_DEBUG_BREAK_IF(!check) } } } #endif } template<> void CMeshManipulator::copyMeshBufferMemberVars(ICPUMeshBuffer* _dst, const ICPUMeshBuffer* _src) { _dst->setBoundingBox( _src->getBoundingBox() ); for (uint32_t i = 0u; i < ICPUMeshBuffer::MAX_ATTR_BUF_BINDING_COUNT; i++) _dst->setVertexBufferBinding( SBufferBinding(_src->getVertexBufferBindings()[i]), i ); _dst->setIndexBufferBinding( SBufferBinding(_src->getIndexBufferBinding()) );/* _dst->setAttachedDescriptorSet( core::smart_refctd_ptr(_src->getAttachedDescriptorSet()) ); _dst->setPipeline( core::smart_refctd_ptr(_src->getPipeline()) );*/ _dst->setIndexType( _src->getIndexType() ); _dst->setBaseVertex( _src->getBaseVertex() ); memcpy(_dst->getPushConstantsDataPtr(),_src->getPushConstantsDataPtr(),ICPUMeshBuffer::MAX_PUSH_CONSTANT_BYTESIZE); _dst->setIndexCount( _src->getIndexCount() ); _dst->setInstanceCount( _src->getInstanceCount() ); _dst->setBaseInstance( _src->getBaseInstance() ); _dst->setPositionAttributeIx( _src->getPositionAttributeIx() ); _dst->setNormalnAttributeIx( _src->getNormalAttributeIx() ); //_dst->getMaterial() = _src->getMaterial(); } template<> void CMeshManipulator::copyMeshBufferMemberVars(ICPUSkinnedMeshBuffer* _dst, const ICPUSkinnedMeshBuffer* _src) { copyMeshBufferMemberVars(_dst, _src); _dst->setIndexRange( _src->getIndexMinBound(), _src->getIndexMaxBound() ); _dst->setMaxVertexBoneInfluences( _src->getMaxVertexBoneInfluences() ); } core::smart_refctd_ptr IMeshManipulator::createMeshBufferDuplicate(const ICPUMeshBuffer* _src) { #ifndef NEW_SHADERS if (!_src) return nullptr; core::smart_refctd_ptr dst; if (_src->getMeshBufferType() == asset::EMT_ANIMATED_SKINNED) { dst = core::make_smart_refctd_ptr(); CMeshManipulator::copyMeshBufferMemberVars(static_cast(dst.get()), static_cast(_src)); } else { dst = core::make_smart_refctd_ptr(); CMeshManipulator::copyMeshBufferMemberVars(dst.get(), _src); } if (!_src->getMeshDataAndFormat()) return dst; core::smart_refctd_ptr idxBuffer; if (_src->getIndices()) { idxBuffer = core::make_smart_refctd_ptr((_src->getIndexType() == EIT_16BIT ? 2 : 4) * _src->getIndexCount()); memcpy(idxBuffer->getPointer(), _src->getIndices(), idxBuffer->getSize()); dst->setIndexBufferOffset(0); } auto newDesc = core::make_smart_refctd_ptr(); const IMeshDataFormatDesc* oldDesc = _src->getMeshDataAndFormat(); core::unordered_map oldBuffers; for (size_t i = 0; i < EVAI_COUNT; ++i) { const ICPUBuffer* oldBuf = oldDesc->getMappedBuffer((E_VERTEX_ATTRIBUTE_ID)i); if (!oldBuf) continue; core::smart_refctd_ptr newBuf; core::unordered_map::iterator itr = oldBuffers.find(oldBuf); if (itr == oldBuffers.end()) { oldBuffers[oldBuf] = (E_VERTEX_ATTRIBUTE_ID)i; newBuf = core::make_smart_refctd_ptr(oldBuf->getSize()); memcpy(newBuf->getPointer(), oldBuf->getPointer(), newBuf->getSize()); } else { const ICPUBuffer* dupBuff = const_cast(newDesc.get())->getMappedBuffer(itr->second); newBuf = core::smart_refctd_ptr(const_cast(dupBuff)); } newDesc->setVertexAttrBuffer(std::move(newBuf), (E_VERTEX_ATTRIBUTE_ID)i, oldDesc->getAttribFormat((E_VERTEX_ATTRIBUTE_ID)i), oldDesc->getMappedBufferStride((E_VERTEX_ATTRIBUTE_ID)i), oldDesc->getMappedBufferOffset((E_VERTEX_ATTRIBUTE_ID)i), oldDesc->getAttribDivisor((E_VERTEX_ATTRIBUTE_ID)i)); } if (idxBuffer) newDesc->setIndexBuffer(std::move(idxBuffer)); dst->setMeshDataAndFormat(std::move(newDesc)); return dst; #else return nullptr; #endif } void IMeshManipulator::filterInvalidTriangles(ICPUMeshBuffer* _input) { if (!_input || !_input->getPipeline() || !_input->getIndices()) return; switch (_input->getIndexType()) { case EIT_16BIT: return CMeshManipulator::_filterInvalidTriangles(_input); case EIT_32BIT: return CMeshManipulator::_filterInvalidTriangles(_input); default: return; } } template void CMeshManipulator::_filterInvalidTriangles(ICPUMeshBuffer* _input) { const size_t size = _input->getIndexCount() * sizeof(IdxT); void* const copy = _IRR_ALIGNED_MALLOC(size,_IRR_SIMD_ALIGNMENT); memcpy(copy, _input->getIndices(), size); struct Triangle { IdxT i[3]; } *const begin = (Triangle*)copy, *const end = (Triangle*)((uint8_t*)copy + size); Triangle* const newEnd = std::remove_if(begin, end, [&_input](const Triangle& _t) { core::vectorSIMDf p0, p1, p2; const uint32_t pvaid = _input->getPositionAttributeIx(); _input->getAttribute(p0, pvaid, _t.i[0]); _input->getAttribute(p1, pvaid, _t.i[1]); _input->getAttribute(p2, pvaid, _t.i[2]); return core::length(core::cross(p1 - p0, p2 - p0)).x<=1.0e-19F; }); const size_t newSize = std::distance(begin, newEnd) * sizeof(Triangle); auto newBuf = core::make_smart_refctd_ptr(newSize); memcpy(newBuf->getPointer(), copy, newSize); _IRR_ALIGNED_FREE(copy); SBufferBinding idxBufBinding; idxBufBinding.offset = 0ull; idxBufBinding.buffer = std::move(newBuf); _input->setIndexBufferBinding(std::move(idxBufBinding)); _input->setIndexCount(newSize/sizeof(IdxT)); } template void CMeshManipulator::_filterInvalidTriangles(ICPUMeshBuffer* _input); template void CMeshManipulator::_filterInvalidTriangles(ICPUMeshBuffer* _input); core::vector CMeshManipulator::findBetterFormatF(E_FORMAT* _outType, size_t* _outSize, E_FORMAT* _outPrevType, const ICPUMeshBuffer* _meshbuffer, uint32_t _attrId, const SErrorMetric& _errMetric, CQuantNormalCache& _cache) { if (!_meshbuffer->getPipeline()) return {}; const E_FORMAT thisType = _meshbuffer->getAttribFormat(_attrId); if (!isFloatingPointFormat(thisType) && !isNormalizedFormat(thisType) && !isScaledFormat(thisType)) return {}; core::vector attribs; const uint32_t cpa = getFormatChannelCount(thisType); float min[4]{ FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX }; float max[4]{ -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX }; core::vectorSIMDf attr; const size_t cnt = _meshbuffer->calcVertexCount(); for (size_t idx = 0u; idx < cnt; ++idx) { _meshbuffer->getAttribute(attr, _attrId, idx); attribs.push_back(attr); for (uint32_t i = 0; i < cpa ; ++i) { if (attr.pointer[i] < min[i]) min[i] = attr.pointer[i]; if (attr.pointer[i] > max[i]) max[i] = attr.pointer[i]; } } core::vector possibleTypes = findTypesOfProperRangeF(thisType, getTexelOrBlockBytesize(thisType), min, max, _errMetric); std::sort(possibleTypes.begin(), possibleTypes.end(), [](const SAttribTypeChoice& t1, const SAttribTypeChoice& t2) { return getTexelOrBlockBytesize(t1.type) < getTexelOrBlockBytesize(t2.type); }); *_outPrevType = thisType; *_outType = thisType; *_outSize = getTexelOrBlockBytesize(*_outType); for (const SAttribTypeChoice& t : possibleTypes) { if (calcMaxQuantizationError({ thisType }, t, attribs, _errMetric, _cache)) { if (getTexelOrBlockBytesize(t.type) < getTexelOrBlockBytesize(thisType)) { *_outType = t.type; *_outSize = getTexelOrBlockBytesize(*_outType); } return attribs; } } return attribs; } core::vector CMeshManipulator::findBetterFormatI(E_FORMAT* _outType, size_t* _outSize, E_FORMAT* _outPrevType, const ICPUMeshBuffer* _meshbuffer, uint32_t _attrId, const SErrorMetric& _errMetric) { if (!_meshbuffer->getPipeline()) return {}; const E_FORMAT thisType = _meshbuffer->getAttribFormat(_attrId); if (!isIntegerFormat(thisType)) return {}; if (isBGRALayoutFormat(thisType)) return {}; // BGRA is supported only by a few normalized types (this is function for integer types) core::vector attribs; const uint32_t cpa = getFormatChannelCount(thisType); uint32_t min[4]; uint32_t max[4]; if (!isSignedFormat(thisType)) for (size_t i = 0; i < 4; ++i) min[i] = UINT_MAX; else for (size_t i = 0; i < 4; ++i) min[i] = INT_MAX; if (!isSignedFormat(thisType)) for (size_t i = 0; i < 4; ++i) max[i] = 0; else for (size_t i = 0; i < 4; ++i) max[i] = INT_MIN; SIntegerAttr attr; const size_t cnt = _meshbuffer->calcVertexCount(); for (size_t idx = 0u; idx < cnt; ++idx) { _meshbuffer->getAttribute(attr.pointer, _attrId, idx); attribs.push_back(attr); for (size_t i = 0; i < cpa; ++i) { if (!isSignedFormat(thisType)) { if (attr.pointer[i] < min[i]) min[i] = attr.pointer[i]; if (attr.pointer[i] > max[i]) max[i] = attr.pointer[i]; } else { if (((int32_t*)attr.pointer + i)[0] < ((int32_t*)min + i)[0]) min[i] = attr.pointer[i]; if (((int32_t*)attr.pointer + i)[0] > ((int32_t*)max + i)[0]) max[i] = attr.pointer[i]; } } } *_outPrevType = *_outType = thisType; *_outSize = getTexelOrBlockBytesize(thisType); *_outPrevType = thisType; if (_errMetric.method == EEM_ANGLES) // native integers normals does not change return attribs; *_outType = getBestTypeI(thisType, _outSize, min, max); if (getTexelOrBlockBytesize(*_outType) >= getTexelOrBlockBytesize(thisType)) { *_outType = thisType; *_outSize = getTexelOrBlockBytesize(thisType); } return attribs; } E_FORMAT CMeshManipulator::getBestTypeI(E_FORMAT _originalType, size_t* _outSize, const uint32_t* _min, const uint32_t* _max) { using namespace video; const bool isNativeInteger = isIntegerFormat(_originalType); const bool isUnsigned = !isSignedFormat(_originalType); const uint32_t originalCpa = getFormatChannelCount(_originalType); core::vector nativeInts{ EF_R8G8_UINT, EF_R8G8_SINT, EF_R8G8B8_UINT, EF_R8G8B8_SINT, EF_R8G8B8A8_UINT, EF_R8G8B8A8_SINT, EF_A2B10G10R10_UINT_PACK32, EF_A2B10G10R10_SINT_PACK32, EF_R16_UINT, EF_R16_SINT, EF_R16G16_UINT, EF_R16G16_SINT, EF_R16G16B16_UINT, EF_R16G16B16_SINT, EF_R16G16B16A16_UINT, EF_R16G16B16A16_SINT, EF_R32_UINT, EF_R32_SINT, EF_R32G32_UINT, EF_R32G32_SINT, EF_R32G32B32_UINT, EF_R32G32B32_SINT, EF_R32G32B32A32_UINT, EF_R32G32B32A32_SINT }; core::vector scaledInts{ EF_R8G8_USCALED, EF_R8G8_SSCALED, EF_R8G8B8_USCALED, EF_R8G8B8_SSCALED, EF_R8G8B8A8_USCALED, EF_R8G8B8A8_SSCALED, EF_A2B10G10R10_USCALED_PACK32, EF_A2B10G10R10_SSCALED_PACK32, EF_R16_USCALED, EF_R16_SSCALED, EF_R16G16_USCALED, EF_R16G16_SSCALED, EF_R16G16B16_USCALED, EF_R16G16B16_SSCALED, EF_R16G16B16A16_USCALED, EF_R16G16B16A16_SSCALED }; core::vector& all = isNativeInteger ? nativeInts : scaledInts; if (originalCpa > 1u) { all.erase( std::remove_if(all.begin(), all.end(), [originalCpa](E_FORMAT fmt) { return getFormatChannelCount(fmt) < originalCpa; } ), all.end() ); } auto minValueOfTypeINT = [](E_FORMAT _fmt, uint32_t _cmpntNum) -> int32_t { if (!isSignedFormat(_fmt)) return 0; switch (_fmt) { case EF_A2R10G10B10_SSCALED_PACK32: case EF_A2R10G10B10_SINT_PACK32: case EF_A2B10G10R10_SSCALED_PACK32: case EF_A2B10G10R10_SINT_PACK32: if (_cmpntNum < 3u) return -512; else return -2; break; default: { const uint32_t bitsPerCh = getTexelOrBlockBytesize(_fmt)*8u/getFormatChannelCount(_fmt); return int32_t(-uint64_t(1ull<<(bitsPerCh-1u))); } } }; auto maxValueOfTypeINT = [](E_FORMAT _fmt, uint32_t _cmpntNum) -> uint32_t { switch (_fmt) { case EF_A2R10G10B10_USCALED_PACK32: case EF_A2R10G10B10_UINT_PACK32: case EF_A2B10G10R10_USCALED_PACK32: case EF_A2B10G10R10_UINT_PACK32: if (_cmpntNum < 3u) return 1023u; else return 3u; break; case EF_A2R10G10B10_SSCALED_PACK32: case EF_A2R10G10B10_SINT_PACK32: case EF_A2B10G10R10_SSCALED_PACK32: case EF_A2B10G10R10_SINT_PACK32: if (_cmpntNum < 3u) return 511u; else return 1u; break; default: { const uint32_t bitsPerCh = getTexelOrBlockBytesize(_fmt)*8u/getFormatChannelCount(_fmt); const uint64_t r = (1ull<>1); } } }; E_FORMAT bestType = _originalType; for (auto it = all.begin(); it != all.end(); ++it) { bool ok = true; for (uint32_t cmpntNum = 0; cmpntNum < originalCpa; ++cmpntNum) // check only `_cpa` components because even if (chosenCpa > _cpa), we don't care about extra components { if (isUnsigned) { if (!(_min[cmpntNum] >= minValueOfTypeINT(*it, cmpntNum) && _max[cmpntNum] <= maxValueOfTypeINT(*it, cmpntNum))) //! TODO: FIX signed vs. unsigned comparison { ok = false; break; } } else { if (!(((int32_t*)(_min + cmpntNum))[0] >= minValueOfTypeINT(*it, cmpntNum) && ((int32_t*)(_max + cmpntNum))[0] <= maxValueOfTypeINT(*it, cmpntNum))) //! TODO: FIX signed vs. unsigned comparison { ok = false; break; } } } if (ok && getTexelOrBlockBytesize(*it) < getTexelOrBlockBytesize(bestType)) // vertexAttrSize array defined in IMeshBuffer.h { bestType = *it; *_outSize = getTexelOrBlockBytesize(bestType); } } return bestType; } core::vector CMeshManipulator::findTypesOfProperRangeF(E_FORMAT _type, size_t _sizeThreshold, const float * _min, const float * _max, const SErrorMetric& _errMetric) { using namespace video; core::vector all{ EF_B10G11R11_UFLOAT_PACK32, EF_R16_SFLOAT, EF_R16G16_SFLOAT, EF_R16G16B16_SFLOAT, EF_R16G16B16A16_SFLOAT, EF_R32_SFLOAT, EF_R32G32_SFLOAT, EF_R32G32B32_SFLOAT, EF_R32G32B32A32_SFLOAT, EF_R8G8_UNORM, EF_R8G8_SNORM, EF_R8G8B8_UNORM, EF_R8G8B8_SNORM, EF_B8G8R8A8_UNORM, //bgra EF_R8G8B8A8_UNORM, EF_R8G8B8A8_SNORM, EF_A2B10G10R10_UNORM_PACK32, EF_A2B10G10R10_SNORM_PACK32, EF_A2R10G10B10_UNORM_PACK32, //bgra EF_A2R10G10B10_SNORM_PACK32, //bgra EF_R16_UNORM, EF_R16_SNORM, EF_R16G16_UNORM, EF_R16G16_SNORM, EF_R16G16B16_UNORM, EF_R16G16B16_SNORM, EF_R16G16B16A16_UNORM, EF_R16G16B16A16_SNORM }; core::vector normalized{ EF_B8G8R8A8_UNORM, //bgra EF_R8G8B8A8_UNORM, EF_R8G8B8A8_SNORM, EF_A2B10G10R10_UNORM_PACK32, EF_A2B10G10R10_SNORM_PACK32, EF_A2R10G10B10_UNORM_PACK32, //bgra EF_A2R10G10B10_SNORM_PACK32, //bgra EF_R16_UNORM, EF_R16_SNORM, EF_R16G16_UNORM, EF_R16G16_SNORM, EF_R16G16B16_UNORM, EF_R16G16B16_SNORM, EF_R16G16B16A16_UNORM, EF_R16G16B16A16_SNORM }; core::vector bgra{ EF_B8G8R8A8_UNORM, //bgra EF_A2R10G10B10_UNORM_PACK32, //bgra EF_A2R10G10B10_SNORM_PACK32, //bgra }; core::vector normals{ EF_R8_SNORM, EF_R8G8_SNORM, EF_R8G8B8_SNORM, EF_R8G8B8A8_SNORM, EF_R16_SNORM, EF_R16G16_SNORM, EF_R16G16B16_SNORM, EF_R16G16B16A16_SNORM, EF_A2B10G10R10_SNORM_PACK32, EF_A2R10G10B10_SNORM_PACK32, //bgra EF_R16_SFLOAT, EF_R16G16_SFLOAT, EF_R16G16B16_SFLOAT, EF_R16G16B16A16_SFLOAT }; auto minValueOfTypeFP = [](E_FORMAT _fmt, uint32_t _cmpntNum) -> float { if (isNormalizedFormat(_fmt)) { return isSignedFormat(_fmt) ? -1.f : 0.f; } switch (_fmt) { case EF_R16_SFLOAT: case EF_R16G16_SFLOAT: case EF_R16G16B16_SFLOAT: case EF_R16G16B16A16_SFLOAT: return -65504.f; case EF_R32_SFLOAT: case EF_R32G32_SFLOAT: case EF_R32G32B32_SFLOAT: case EF_R32G32B32A32_SFLOAT: return -FLT_MAX; case EF_B10G11R11_UFLOAT_PACK32: return 0.f; default: return 1.f; } }; auto maxValueOfTypeFP = [](E_FORMAT _fmt, uint32_t _cmpntNum) -> float { if (isNormalizedFormat(_fmt)) { return 1.f; } switch (_fmt) { case EF_R16_SFLOAT: case EF_R16G16_SFLOAT: case EF_R16G16B16_SFLOAT: case EF_R16G16B16A16_SFLOAT: return 65504.f; case EF_R32_SFLOAT: case EF_R32G32_SFLOAT: case EF_R32G32B32_SFLOAT: case EF_R32G32B32A32_SFLOAT: return FLT_MAX; case EF_B10G11R11_UFLOAT_PACK32: if (_cmpntNum < 2u) return 65024.f; else return 64512.f; default: return 0.f; } }; if (isNormalizedFormat(_type) || _errMetric.method == EEM_ANGLES) { if (_errMetric.method == EEM_ANGLES) { if (isBGRALayoutFormat(_type)) { all = core::vector(1u, EF_A2R10G10B10_SNORM_PACK32); } else all = std::move(normals); } else if (isBGRALayoutFormat(_type)) all = std::move(bgra); else all = std::move(normalized); } if (isNormalizedFormat(_type) && !isSignedFormat(_type)) all.erase(std::remove_if(all.begin(), all.end(), [](E_FORMAT _t) { return isSignedFormat(_t); }), all.end()); else if (isNormalizedFormat(_type) && isSignedFormat(_type)) all.erase(std::remove_if(all.begin(), all.end(), [](E_FORMAT _t) { return !isSignedFormat(_t); }), all.end()); const uint32_t originalCpa = getFormatChannelCount(_type); all.erase( std::remove_if(all.begin(), all.end(), [originalCpa](E_FORMAT fmt) { return getFormatChannelCount(fmt) < originalCpa; } ), all.end() ); core::vector possibleTypes; core::vectorSIMDf min(_min), max(_max); for (auto it = all.begin(); it != all.end(); ++it) { bool ok = true; for (uint32_t cmpntNum = 0; cmpntNum < originalCpa; ++cmpntNum) // check only `_cpa` components because even if (chosenCpa > _cpa), we don't care about extra components { if (!(min.pointer[cmpntNum] >= minValueOfTypeFP(*it, cmpntNum) && max.pointer[cmpntNum] <= maxValueOfTypeFP(*it, cmpntNum))) { ok = false; break; // break loop comparing (*it)'s range component by component } } if (ok && getTexelOrBlockBytesize(*it) <= _sizeThreshold) possibleTypes.push_back({*it}); } return possibleTypes; } bool CMeshManipulator::calcMaxQuantizationError(const SAttribTypeChoice& _srcType, const SAttribTypeChoice& _dstType, const core::vector& _srcData, const SErrorMetric& _errMetric, CQuantNormalCache& _cache) { using namespace video; using QuantF_t = core::vectorSIMDf(*)(const core::vectorSIMDf&, E_FORMAT, E_FORMAT, CQuantNormalCache & _cache); QuantF_t quantFunc = nullptr; if (_errMetric.method == EEM_ANGLES) { switch (_dstType.type) { case EF_R8_SNORM: case EF_R8G8_SNORM: case EF_R8G8B8_SNORM: case EF_R8G8B8A8_SNORM: quantFunc = [](const core::vectorSIMDf& _in, E_FORMAT, E_FORMAT, CQuantNormalCache& _cache) -> core::vectorSIMDf { uint8_t buf[32]; ((uint32_t*)buf)[0] = _cache.quantizeNormal(_in); core::vectorSIMDf retval; ICPUMeshBuffer::getAttribute(retval, buf, EF_R8G8B8A8_SNORM); retval.w = 1.f; return retval; }; break; case EF_A2R10G10B10_SNORM_PACK32: case EF_A2B10G10R10_SNORM_PACK32: // bgra quantFunc = [](const core::vectorSIMDf& _in, E_FORMAT, E_FORMAT, CQuantNormalCache& _cache) -> core::vectorSIMDf { uint8_t buf[32]; ((uint32_t*)buf)[0] = _cache.quantizeNormal(_in); core::vectorSIMDf retval; ICPUMeshBuffer::getAttribute(retval, buf, EF_A2R10G10B10_SNORM_PACK32); retval.w = 1.f; return retval; }; break; case EF_R16_SNORM: case EF_R16G16_SNORM: case EF_R16G16B16_SNORM: case EF_R16G16B16A16_SNORM: quantFunc = [](const core::vectorSIMDf& _in, E_FORMAT, E_FORMAT, CQuantNormalCache& _cache) -> core::vectorSIMDf { uint8_t buf[32]; ((uint64_t*)buf)[0] = _cache.quantizeNormal(_in); core::vectorSIMDf retval; ICPUMeshBuffer::getAttribute(retval, buf, EF_R16G16B16A16_SNORM); retval.w = 1.f; return retval; }; break; default: quantFunc = nullptr; break; } } else { quantFunc = [](const core::vectorSIMDf& _in, E_FORMAT _inType, E_FORMAT _outType, CQuantNormalCache& _cache) -> core::vectorSIMDf { uint8_t buf[32]; ICPUMeshBuffer::setAttribute(_in, buf, _outType); core::vectorSIMDf out(0.f, 0.f, 0.f, 1.f); ICPUMeshBuffer::getAttribute(out, buf, _outType); return out; }; } _IRR_DEBUG_BREAK_IF(!quantFunc) if (!quantFunc) return false; for (const core::vectorSIMDf& d : _srcData) { const core::vectorSIMDf quantized = quantFunc(d, _srcType.type, _dstType.type, _cache); if (!compareFloatingPointAttribute(d, quantized, getFormatChannelCount(_srcType.type), _errMetric)) return false; } return true; } core::smart_refctd_ptr IMeshManipulator::idxBufferFromTriangleStripsToTriangles(const void* _input, size_t _idxCount, E_INDEX_TYPE _idxType) { if (_idxType == EIT_16BIT) return CMeshManipulator::triangleStripsToTriangles(_input, _idxCount); else if (_idxType == EIT_32BIT) return CMeshManipulator::triangleStripsToTriangles(_input, _idxCount); return nullptr; } core::smart_refctd_ptr IMeshManipulator::idxBufferFromTrianglesFanToTriangles(const void* _input, size_t _idxCount, E_INDEX_TYPE _idxType) { if (_idxType == EIT_16BIT) return CMeshManipulator::trianglesFanToTriangles(_input, _idxCount); else if (_idxType == EIT_32BIT) return CMeshManipulator::trianglesFanToTriangles(_input, _idxCount); return nullptr; } } // end namespace scene } // end namespace irr ",16153,True,2700.877210489844,median "/// \\copyright Tobias Hienzsch 2019-2021 /// Distributed under the Boost Software License, Version 1.0. /// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt #ifndef TETL_STRING_BASIC_STATIC_STRING_HPP #define TETL_STRING_BASIC_STATIC_STRING_HPP #include ""etl/_algorithm/copy.hpp"" #include ""etl/_algorithm/fill.hpp"" #include ""etl/_algorithm/max.hpp"" #include ""etl/_algorithm/remove.hpp"" #include ""etl/_algorithm/rotate.hpp"" #include ""etl/_container/smallest_size_t.hpp"" #include ""etl/_cstring/memset.hpp"" #include ""etl/_iterator/begin.hpp"" #include ""etl/_iterator/data.hpp"" #include ""etl/_iterator/distance.hpp"" #include ""etl/_iterator/end.hpp"" #include ""etl/_iterator/rbegin.hpp"" #include ""etl/_iterator/rend.hpp"" #include ""etl/_iterator/size.hpp"" #include ""etl/_limits/numeric_limits.hpp"" #include ""etl/_string/char_traits.hpp"" #include ""etl/_string/str_find_first_not_of.hpp"" #include ""etl/_string/str_replace.hpp"" #include ""etl/_string/str_rfind.hpp"" #include ""etl/_string_view/string_view.hpp"" #include ""etl/_type_traits/is_convertible.hpp"" #include ""etl/_warning/ignore_unused.hpp"" namespace etl { /// \\brief basic_static_string class with fixed size capacity. /// \\tparam CharT Build in type for character size (mostly 'char') /// \\tparam Capacity Capacity for basic_static_string /// \\include string.cpp /// \\module Strings template > struct basic_static_string { // clang-format off template constexpr static bool view_and_not_char_ptr = is_convertible_v> && !is_convertible_v; // clang-format on using internal_size_t = etl::smallest_size_t; public: /// The character type used using value_type = CharT; /// The size type used using size_type = etl::size_t; /// The size type used using difference_type = etl::ptrdiff_t; /// The character traits type used using traits_type = Traits; /// Pointer to the character type using pointer = CharT*; /// Const pointer to the character type using const_pointer = CharT const*; /// Reference to the character type using reference = CharT&; /// Const reference to the character type using const_reference = CharT const&; /// Iterator to the character type using iterator = CharT*; /// Const iterator to the character type using const_iterator = CharT const*; /// The reverse iterator type used using reverse_iterator = etl::reverse_iterator; /// The const reverse iterator type used using const_reverse_iterator = etl::reverse_iterator; /// Default constructor. constexpr basic_static_string() = default; /// \\brief Character pointer constructor. /// /// \\details Fails silently if input len is greater then capacity. constexpr basic_static_string( const_pointer str, size_type const len) noexcept { TETL_ASSERT(len + 1 <= Capacity); if (str != nullptr && len + 1 < Capacity) { clear_storage(); unsafe_set_size(len); traits_type::copy(&data_[0], str, len); } } /// \\brief Character pointer constructor. Calls traits_type::length. /// /// \\details Fails silently if input length is greater then capacity. constexpr basic_static_string(const_pointer str) noexcept : basic_static_string(str, traits_type::length(str)) { } constexpr basic_static_string(nullptr_t /*null*/) = delete; /// Constructs the string with count copies of character ch. /// /// \\details Fails silently if input length is greater then capacity. constexpr basic_static_string(size_type count, value_type ch) noexcept { TETL_ASSERT(count + 1 <= Capacity); if (count + 1 <= Capacity) { clear_storage(); fill(begin(), begin() + count, ch); unsafe_set_size(count); } } /// Constructs the string with the contents of the range [ first, /// last). Fails silently if input length is greater then capacity. template , bool> = true> constexpr basic_static_string(InputIt first, InputIt last) noexcept : basic_static_string( first, static_cast(distance(first, last))) { } /// Constructs the string with a substring [pos, pos+count) of other. constexpr basic_static_string( basic_static_string const& other, size_type pos, size_type count) : basic_static_string { other.substr(pos, count) } { } /// Constructs the string with a substring [pos, other.size()). constexpr basic_static_string( basic_static_string const& other, size_type pos) : basic_static_string { other.substr(pos, other.size()) } { } /// Implicitly converts t to a string view sv, then initializes the /// string with the contents of sv. template , bool> = true> explicit constexpr basic_static_string(T const& t) noexcept { basic_string_view const sv = t; assign(sv.begin(), sv.end()); } /// Implicitly converts t to a string view sv, then initializes the /// string with the subrange [ pos, pos + n ) of sv. template , bool> = true> explicit constexpr basic_static_string( T const& t, size_type pos, size_type n) : basic_static_string { basic_string_view { t }.substr(pos, n) } { } /// Defaulted copy constructor. constexpr basic_static_string( basic_static_string const& /*str*/) noexcept = default; /// Defaulted move constructor. constexpr basic_static_string( basic_static_string&& /*str*/) noexcept = default; /// Defaulted copy assignment. constexpr auto operator =(basic_static_string const& /*str*/) noexcept -> basic_static_string& = default; /// Defaulted move assignment. constexpr auto operator =(basic_static_string&& /*str*/) noexcept -> basic_static_string& = default; /// Replaces the contents with those of null-terminated character /// string pointed to by s. constexpr auto operator=(const_pointer s) noexcept -> basic_static_string& { assign(s, traits_type::length(s)); return *this; } constexpr auto operator=(nullptr_t /*0*/) -> basic_static_string& = delete; /// Replaces the contents with character ch. constexpr auto operator=(value_type ch) noexcept -> basic_static_string& { assign(&ch, 1); return *this; } /// Implicitly converts t to a string view sv, then replaces the /// contents with those of the sv. template constexpr auto operator=(T const& t) noexcept -> enable_if_t, basic_static_string&> { assign(t); return *this; } /// Replaces the contents with count copies of character ch. constexpr auto assign(size_type count, value_type ch) noexcept -> basic_static_string& { (*this) = basic_static_string { count, ch }; return *this; } /// Replaces the contents with a copy of str. constexpr auto assign(basic_static_string const& str) noexcept -> basic_static_string& { *this = str; return *this; } /// Replaces the contents with a substring [ pos, pos + count ) /// of str. constexpr auto assign(basic_static_string const& str, size_type pos, size_type count = npos) noexcept -> basic_static_string& { *this = str.substr(pos, count); return *this; } /// Replaces the contents with those of str using move semantics. constexpr auto assign(basic_static_string&& str) noexcept -> basic_static_string& { *this = etl::move(str); return *this; } /// Replaces the contents with copies of the characters in the range /// [ s, s + count ). This range can contain null characters. constexpr auto assign(const_pointer s, size_type count) noexcept -> basic_static_string& { *this = basic_static_string { s, count }; return *this; } /// \\brief Replaces the contents with those of null-terminated character /// string pointed to by s. constexpr auto assign(const_pointer s) noexcept -> basic_static_string& { *this = basic_static_string { s, traits_type::length(s) }; return *this; } /// \\brief Replaces the contents with copies of the characters in the /// range [ first , last ). template constexpr auto assign(InputIt first, InputIt last) noexcept -> enable_if_t, basic_static_string&> { *this = basic_static_string { first, last }; return *this; } /// \\brief Implicitly converts t to a string view sv, then replaces the /// contents with the characters from sv. template constexpr auto assign(T const& t) noexcept -> enable_if_t, basic_static_string&> { auto tmp = basic_static_string { basic_static_string { t } }; *this = tmp; return *this; } /// \\brief Implicitly converts t to a string view sv, then replaces the /// contents with the characters from the subview [ pos, pos + count ) of /// sv. template constexpr auto assign( T const& t, size_type pos, size_type count = npos) noexcept -> enable_if_t, basic_static_string&> { auto tmp = basic_static_string { basic_static_string { t, pos, count } }; *this = tmp; return *this; } /// \\brief Trivial defaulted destructor ~basic_static_string() noexcept = default; /// \\brief Accesses the specified character without bounds checking. constexpr auto operator[](size_type index) noexcept -> reference { return unsafe_at(index); } /// \\brief Accesses the specified character without bounds checking. constexpr auto operator[](size_type index) const noexcept -> const_reference { return unsafe_at(index); } /// \\brief Returns an iterator to the beginning. constexpr auto begin() noexcept -> iterator { return data(); } /// \\brief Returns an const iterator to the beginning. [[nodiscard]] constexpr auto begin() const noexcept -> const_iterator { return data(); } /// \\brief Returns an const iterator to the beginning. [[nodiscard]] constexpr auto cbegin() const noexcept -> const_iterator { return begin(); } /// \\brief Returns an iterator to the end. constexpr auto end() noexcept -> iterator { return begin() + size(); } /// \\brief Returns an const iterator to the end. [[nodiscard]] constexpr auto end() const noexcept -> const_iterator { return begin() + size(); } /// \\brief Returns an const iterator to the end. [[nodiscard]] constexpr auto cend() const noexcept -> const_iterator { return end(); } /// \\brief Returns a reverse iterator to the first character of the reversed /// string. It corresponds to the last character of the non-reversed string. [[nodiscard]] constexpr auto rbegin() noexcept -> reverse_iterator { return reverse_iterator(end()); } /// \\brief Returns a reverse iterator to the first character of the reversed /// string. It corresponds to the last character of the non-reversed string. [[nodiscard]] constexpr auto rbegin() const noexcept -> const_reverse_iterator { return const_reverse_iterator(end()); } /// \\brief Returns a reverse iterator to the first character of the reversed /// string. It corresponds to the last character of the non-reversed string. [[nodiscard]] constexpr auto crbegin() const noexcept -> const_reverse_iterator { return rbegin(); } /// \\brief Returns a reverse iterator to the first character of the reversed /// string. It corresponds to the last character of the non-reversed string. [[nodiscard]] constexpr auto rend() noexcept -> reverse_iterator { return reverse_iterator(begin()); } /// \\brief Returns a reverse iterator to the first character of the reversed /// string. It corresponds to the last character of the non-reversed string. [[nodiscard]] constexpr auto rend() const noexcept -> const_reverse_iterator { return const_reverse_iterator(begin()); } /// \\brief Returns a reverse iterator to the first character of the reversed /// string. It corresponds to the last character of the non-reversed string. [[nodiscard]] constexpr auto crend() const noexcept -> const_reverse_iterator { return rend(); } /// \\brief Accesses the first character. [[nodiscard]] constexpr auto front() noexcept -> reference { return unsafe_at(0); } /// \\brief Accesses the first character. [[nodiscard]] constexpr auto front() const noexcept -> const_reference { return unsafe_at(0); } /// \\brief Accesses the last character. [[nodiscard]] constexpr auto back() noexcept -> reference { return unsafe_at(size() - 1); } /// \\brief Accesses the last character. [[nodiscard]] constexpr auto back() const noexcept -> const_reference { return unsafe_at(size() - 1); } /// \\brief Checks whether the string is empty. [[nodiscard]] constexpr auto empty() const noexcept -> bool { return size() == 0; } /// \\brief Checks whether the string is full. Equals to capacity - 1, for /// the null termination character. [[nodiscard]] constexpr auto full() const noexcept -> bool { return size() == capacity() - 1; } /// \\brief Returns the number of characters. [[nodiscard]] constexpr auto size() const noexcept -> size_type { return length(); } /// \\brief Returns the number of characters. [[nodiscard]] constexpr auto length() const noexcept -> size_type { return size_; } /// \\brief Returns the number of characters that can be held in allocated /// storage, including the space for the null terminator. [[nodiscard]] constexpr auto capacity() const noexcept -> size_type { return Capacity; } /// \\brief Returns the number of characters that can be held in allocated /// storage, including the space for the null terminator. [[nodiscard]] constexpr auto max_size() const noexcept -> size_type { return Capacity; } /// \\brief Reserve is deleted, since the capacity is fixed. constexpr auto reserve(size_type newCap) -> void = delete; /// \\brief Shrink to fit is deleted, since the capacity is fixed. constexpr auto shrink_to_fit() -> void = delete; /// \\brief Returns a pointer to the underlying array serving as character /// storage. The pointer is such that the range [data(); data() + size()) is /// valid and the values in it correspond to the values stored in the /// string. /// /// \\details Always null-terminated. [[nodiscard]] constexpr auto data() noexcept -> pointer { return &data_[0]; } /// \\brief Returns a pointer to the underlying array serving as character /// storage. The pointer is such that the range [data(); data() + size()) is /// valid and the values in it correspond to the values stored in the /// string. /// /// \\details Always null-terminated. [[nodiscard]] constexpr auto data() const noexcept -> const_pointer { return c_str(); } /// \\brief Returns a pointer to a null-terminated character array. /// /// The data is equivalent to those stored in the string. The pointer is /// such that the range [c_str(); c_str() + size()] is valid and the values /// in it correspond to the values stored in the string with an additional /// null character after the last position. [[nodiscard]] constexpr auto c_str() const noexcept -> const_pointer { return &data_[0]; } /// \\brief Returns a etl::basic_string_view. [[nodiscard]] constexpr operator basic_string_view() const noexcept { return basic_string_view(data(), size()); } /// \\brief Removes all characters from the string. Sets size to 0 and /// overrides the buffer with zeros. constexpr auto clear() noexcept -> void { clear_storage(); unsafe_set_size(0); } /// \\brief Removes min(count, size() - index) characters starting at index. /// /// \\returns *this constexpr auto erase(size_type index = 0, size_type count = npos) noexcept -> basic_static_string& { auto safeCount = etl::min(count, size() - index); erase(begin() + index, begin() + index + safeCount); return *this; } /// \\brief Removes the character at position. /// /// \\returns iterator pointing to the character immediately following the /// character erased, or end() if no such character exists. constexpr auto erase(const_iterator position) noexcept -> iterator { return erase(position, position + 1); } /// \\brief Removes the characters in the range [first, last). /// /// \\returns iterator pointing to the character last pointed to before the /// erase, or end() if no such character exists. constexpr auto erase(const_iterator first, const_iterator last) noexcept -> iterator { auto const start = static_cast(etl::distance(cbegin(), first)); auto const distance = static_cast(etl::distance(first, last)); TETL_ASSERT(size() > distance); etl::rotate(begin() + start, begin() + start + distance, end()); unsafe_set_size(size() - distance); return begin() + start; } /// \\brief Appends the given character ch to the end of the string. Does /// nothing if the string is full. constexpr auto push_back(value_type ch) noexcept -> void { TETL_ASSERT(size() < capacity()); if (size() < capacity()) { append(1, ch); } } /// \\brief Removes the last character from the string. Does nothing if the /// string is empty. constexpr auto pop_back() noexcept -> void { if (!empty()) { unsafe_set_size(size() - 1); } } /// \\brief Appends count copies of character s. constexpr auto append(size_type const count, value_type const s) noexcept -> basic_static_string& { auto const safeCount = etl::min(count, capacity() - size() - 1); for (size_type i = 0; i < safeCount; i++) { data_[size() + i] = s; } unsafe_set_size(size() + safeCount); return *this; } /// \\brief Appends the null-terminated character string pointed to by s. The /// length of the string is determined by the first null character using constexpr auto append(const_pointer s) noexcept -> basic_static_string& { auto const len = traits_type::length(s); return append(s, len); } /// \\brief Appends characters in the range [ s, s + count ). This range can /// contain null characters. constexpr auto append(const_pointer s, size_type count) noexcept -> basic_static_string& { auto const safeCount = etl::min(count, capacity() - size() - 1); for (size_type i = 0; i < safeCount; i++) { data_[size() + i] = s[i]; } unsafe_set_size(size() + safeCount); return *this; } /// \\brief Appends characters in the range [ first , last ). template constexpr auto append(InputIter first, InputIter last) noexcept -> enable_if_t, basic_static_string&> { TETL_ASSERT(capacity() - size() > static_cast(etl::distance(first, last))); for (; first != last; ++first) { push_back(*first); } return *this; } /// \\brief Appends string str. constexpr auto append(basic_static_string const& str) noexcept -> basic_static_string& { return append(str.begin(), str.end()); } /// \\brief Appends a substring [ pos, pos + count ) of str. constexpr auto append(basic_static_string const& str, size_type pos, size_type count = npos) noexcept -> basic_static_string& { return append(str.substr(pos, count)); } /// \\brief Implicitly converts t to a string_view sv, then appends all /// characters from sv. template constexpr auto append(T const& t) -> enable_if_t, basic_static_string&> { etl::basic_string_view sv = t; return append(sv.data(), sv.size()); } /// \\brief Implicitly converts t to a string_view sv then appends the /// characters from the subview [ pos, pos + count ) of sv. template constexpr auto append(T const& t, size_type pos, size_type count = npos) -> enable_if_t, basic_static_string&> { etl::basic_string_view sv = t; return append(sv.substr(pos, count)); } /// \\brief Appends string str. constexpr auto operator+=(basic_static_string const& str) noexcept -> basic_static_string& { return append(str); } /// \\brief Appends character ch. constexpr auto operator+=(value_type ch) noexcept -> basic_static_string& { return append(1, ch); } /// \\brief Appends the null-terminated character string pointed to by s. constexpr auto operator+=(const_pointer s) noexcept -> basic_static_string& { return append(s); } /// \\brief Implicitly converts t to a string view sv, then appends /// characters in the string view sv. template constexpr auto operator+=(T const& t) noexcept -> enable_if_t, basic_static_string&> { return append(t); } /// \\brief Inserts count copies of character ch at the position index. constexpr auto insert(size_type const index, size_type const count, value_type const ch) noexcept -> basic_static_string& { for (size_type i = 0; i < count; ++i) { insert_impl(begin() + index, &ch, 1); } return *this; } /// \\brief Inserts null-terminated character string pointed to by s at the /// position index. constexpr auto insert(size_type const index, const_pointer s) noexcept -> basic_static_string& { insert_impl(begin() + index, s, traits_type::length(s)); return *this; } /// \\brief Inserts the characters in the range [s, s+count) at the position /// index. The range can contain null characters. constexpr auto insert(size_type const index, const_pointer s, size_type const count) noexcept -> basic_static_string& { insert_impl(begin() + index, s, count); return *this; } /// \\brief Inserts string str at the position index. constexpr auto insert(size_type const index, basic_static_string const& str) noexcept -> basic_static_string& { insert_impl(begin() + index, str.data(), str.size()); return *this; } /// \\brief Inserts a string, obtained by str.substr(index_str, count) at the /// position index. constexpr auto insert(size_type const index, basic_static_string const& str, size_type const indexStr, size_type const count = npos) noexcept -> basic_static_string& { using view_type = basic_string_view; auto sv = view_type(str).substr(indexStr, count); insert_impl(begin() + index, sv.data(), sv.size()); return *this; } // // * \\brief Inserts character ch before the character pointed by pos. // constexpr auto insert(const_iterator pos, value_type const ch) noexcept // -> iterator // { // } // // * \\brief Inserts count copies of character ch before the element (if // any) pointed by // * pos. // constexpr auto insert(const_iterator pos, size_type count, // value_type const ch) noexcept -> iterator // { // } // // * \\brief Inserts characters from the range [first, last) before the // element (if any) // * pointed by pos. // template )> // constexpr auto insert(const_iterator pos, InputIter first, InputIter // last) noexcept // -> iterator // { // } /// \\brief Implicitly converts t to a string view sv, then inserts the /// elements from sv before the element (if any) pointed by pos. template constexpr auto insert(size_type const pos, T const& t) noexcept -> enable_if_t, basic_static_string&> { basic_string_view sv = t; insert_impl(begin() + pos, sv.data(), sv.size()); return *this; } /// \\brief Implicitly converts t to a string view sv, then inserts, before /// the element (if any) pointed by pos, the characters from the subview /// [index_str, index_str+count) of sv. template constexpr auto insert(size_type const index, T const& t, size_type const indexStr, size_type const count = npos) noexcept -> enable_if_t, basic_static_string&> { basic_string_view sv = t; auto sub = sv.substr(indexStr, count); insert_impl(begin() + index, sub.data(), sub.size()); return *this; } /// \\brief Compares this string to str. [[nodiscard]] constexpr auto compare( basic_static_string const& str) const noexcept -> int { return compare_impl(data(), size(), str.data(), str.size()); } /// \\brief Compares this string to str with other capacity. template [[nodiscard]] constexpr auto compare( basic_static_string const& str) const noexcept -> int { return compare_impl(data(), size(), str.data(), str.size()); } /// \\brief Compares a [pos, pos+count) substring of this string to str. If /// count > size() - pos the substring is [pos, size()). [[nodiscard]] constexpr auto compare(size_type const pos, size_type const count, basic_static_string const& str) const -> int { auto const sz = count > size() - pos ? size() : count; auto const sub = string_view(*this).substr(pos, sz); return sub.compare(str); } /// \\brief Compares a [pos1, pos1+count1) substring of this string to a /// substring [pos2, pos2+count2) of str. If count1 > size() - pos1 the /// first substring is [pos1, size()). Likewise, count2 > str.size() - pos2 /// the second substring is [pos2, str.size()). [[nodiscard]] constexpr auto compare(size_type const pos1, size_type const count1, basic_static_string const& str, size_type const pos2, size_type const count2 = npos) const -> int { auto const sz1 = count1 > size() - pos1 ? size() : count1; auto const sub1 = string_view(*this).substr(pos1, sz1); auto const sz2 = count2 > str.size() - pos2 ? size() : count2; auto const sub2 = string_view(str).substr(pos2, sz2); return sub1.compare(sub2); } /// \\brief Compares this string to the null-terminated character sequence /// beginning at the character pointed to by s with length /// traits_type::length(s). [[nodiscard]] constexpr auto compare(const_pointer s) const -> int { return compare_impl(data(), size(), s, traits_type::length(s)); } /// \\brief Compares a [pos1, pos1+count1) substring of this string to the /// null-terminated character sequence beginning at the character pointed to /// by s with length traits_type::length(s). If count1 > size() - pos1 the /// substring is [pos1, size()). [[nodiscard]] constexpr auto compare(size_type const pos, size_type const count, const_pointer s) const -> int { auto const sz = count > size() - pos ? size() : count; auto const sub = string_view(*this).substr(pos, sz); return compare_impl(sub.data(), sub.size(), s, traits_type::length(s)); } /// \\brief Compares a [pos1, pos1+count1) substring of this string to the /// characters in the range [s, s + count2). If count1 > size() - pos1 the /// substring is [pos1, size()). (Note: the characters in the range [s, s + /// count2) may include null characters.) [[nodiscard]] constexpr auto compare(size_type const pos1, size_type const count1, const_pointer s, size_type const count2) const -> int { auto const sz = count1 > size() - pos1 ? size() : count1; auto const sub = string_view(*this).substr(pos1, sz); return compare_impl(sub.data(), sub.size(), s, count2); } /// \\brief Implicitly converts t to a string view sv, then compares the /// content of this string to sv. template [[nodiscard]] constexpr auto compare(T const& t) const noexcept -> enable_if_t, int> { using view_type = basic_string_view; view_type const sv = t; return view_type(*this).compare(sv); } /// \\brief Implicitly converts t to a string view sv, then compares a [pos1, /// pos1+count1) substring of this string to sv. template [[nodiscard]] constexpr auto compare(size_type pos1, size_type count1, T const& t) const noexcept -> enable_if_t, int> { using view_type = basic_string_view; view_type const sv = t; return view_type(*this).substr(pos1, count1).compare(sv); } /// \\brief Implicitly converts t to a string view sv, then compares a [pos1, /// pos1+count1) substring of this string to a substring [pos2, pos2+count2) /// of sv. template [[nodiscard]] constexpr auto compare(size_type pos1, size_type count1, T const& t, size_type pos2, size_type count2 = npos) const noexcept -> enable_if_t, int> { using view_type = basic_string_view; view_type const sv = t; return view_type(*this) .substr(pos1, count1) .compare(sv.substr(pos2, count2)); } /// \\brief Checks if the string begins with the given prefix. [[nodiscard]] constexpr auto starts_with( basic_string_view sv) const noexcept -> bool { return basic_string_view(data(), size()).starts_with(sv); } /// \\brief Checks if the string begins with the given prefix. [[nodiscard]] constexpr auto starts_with(value_type c) const noexcept -> bool { return basic_string_view(data(), size()).starts_with(c); } /// \\brief Checks if the string begins with the given prefix. [[nodiscard]] constexpr auto starts_with(const_pointer s) const -> bool { return basic_string_view(data(), size()).starts_with(s); } /// \\brief Checks if the string ends with the given prefix. [[nodiscard]] constexpr auto ends_with( basic_string_view sv) const noexcept -> bool { return basic_string_view(data(), size()).ends_with(sv); } /// \\brief Checks if the string ends with the given prefix. [[nodiscard]] constexpr auto ends_with(value_type c) const noexcept -> bool { return basic_string_view(data(), size()).ends_with(c); } /// \\brief Checks if the string ends with the given prefix. [[nodiscard]] constexpr auto ends_with(const_pointer str) const -> bool { return basic_string_view(data(), size()).ends_with(str); } /// \\brief Replaces the part of the string indicated [pos, pos + count) with /// a new string. constexpr auto replace(size_type pos, size_type count, const basic_static_string& str) -> basic_static_string& { TETL_ASSERT(pos < size()); TETL_ASSERT(pos + count < size()); auto* f = data() + pos; auto* l = data() + pos + count; detail::str_replace(f, l, str.begin(), str.end()); return *this; } /// \\brief Replaces the part of the string indicated [first, last) with a /// new string. constexpr auto replace(const_iterator first, const_iterator last, basic_static_string const& str) -> basic_static_string& { auto* f = const_cast(first); auto* l = const_cast(last); detail::str_replace(f, l, str.begin(), str.end()); return *this; } constexpr auto replace(size_type pos, size_type count, basic_static_string const& str, size_type pos2, size_type count2 = npos) -> basic_static_string& { TETL_ASSERT(pos < size()); TETL_ASSERT(pos + count < size()); TETL_ASSERT(pos2 < str.size()); TETL_ASSERT(pos2 + count2 < str.size()); auto* f = data() + min(pos, size()); auto* l = data() + min(pos + count, size()); auto const* sf = next(begin(str), min(pos2, str.size())); auto const* sl = next(begin(str), min(pos2 + count2, str.size())); detail::str_replace(f, l, sf, sl); return *this; } constexpr auto replace(size_type pos, size_type count, CharT const* str, size_type count2) -> basic_static_string& { TETL_ASSERT(pos < size()); TETL_ASSERT(pos + count < size()); auto* f = next(data(), min(pos, size())); auto* l = next(data(), min(pos + count, size())); detail::str_replace(f, l, str, next(str, count2)); return *this; } constexpr auto replace(const_iterator first, const_iterator last, CharT const* str, size_type count2) -> basic_static_string& { auto* f = const_cast(first); auto* l = const_cast(last); detail::str_replace(f, l, str, next(str, count2)); return *this; } constexpr auto replace(size_type pos, size_type count, CharT const* str) -> basic_static_string& { TETL_ASSERT(pos < size()); TETL_ASSERT(pos + count < size()); auto* f = next(data(), min(pos, size())); auto* l = next(data(), min(pos + count, size())); detail::str_replace(f, l, str, next(str, strlen(str))); return *this; } constexpr auto replace(const_iterator first, const_iterator last, CharT const* str) -> basic_static_string& { auto* f = const_cast(first); auto* l = const_cast(last); detail::str_replace(f, l, str, next(str, strlen(str))); return *this; } // constexpr auto replace(size_type pos, size_type count, size_type count2, // CharT ch) -> basic_static_string& //{ // TETL_ASSERT(pos < size()); // TETL_ASSERT(pos + count < size()); // // auto* f = next(data(), min(pos, size())); // auto* l = next(data(), min(pos + count, size())); // detail::str_replace(f, l, ch); // return *this; //} constexpr auto replace(const_iterator first, const_iterator last, size_type count2, CharT ch) -> basic_static_string& { auto* f = const_cast(first); auto* l = min(const_cast(last), f + count2); detail::str_replace(f, l, ch); return *this; } /// \\brief Returns a substring [pos, pos+count). If the requested substring /// extends past the end of the string, or if count == npos, the returned /// substring is [pos, size()). /// /// If pos is greater then size(), an empty string will be returned. [[nodiscard]] constexpr auto substr( size_type pos = 0, size_type count = npos) const -> basic_static_string { if (pos > size()) { return {}; } return basic_static_string(data() + pos, etl::min(count, size() - pos)); } /// \\brief Copies a substring [pos, pos+count) to character string pointed /// to by dest. If the requested substring lasts past the end of the string, /// or if count == npos, the copied substring is [pos, size()). The /// resulting character string is not null-terminated. /// /// If pos is greater then size(), nothing will be copied. /// /// \\returns Number of characters copied. constexpr auto copy(pointer destination, size_type count, size_type pos = 0) const -> size_type { if (pos > size()) { return 0; } auto const* first = data() + pos; auto const* last = first + etl::min(count, size() - pos); auto const* dest = destination; auto const* res = etl::copy(first, last, destination); return static_cast(res - dest); } /// \\brief Resizes the string to contain count characters. /// /// \\details If the current size is less than count, additional characters /// are appended, maximum up to it's capacity. If the current size is /// greater than count, the string is reduced to its first count elements. constexpr auto resize(size_type count, value_type ch) noexcept -> void { if (size() > count) { unsafe_set_size(count); } if (size() < count) { append(count, ch); } } /// \\brief Resizes the string to contain count characters. /// /// \\details If the current size is less than count, additional characters /// are appended, maximum up to it's capacity. If the current size is /// greater than count, the string is reduced to its first count elements. constexpr auto resize(size_type count) noexcept -> void { resize(count, value_type()); } /// \\brief Exchanges the contents of the string with those of other. All /// iterators and references may be invalidated. constexpr auto swap(basic_static_string& other) noexcept -> void { using etl::move; auto temp(move(other)); other = move(*this); *this = move(temp); } /// \\brief Finds the first substring equal to the given character sequence. /// Search begins at pos, i.e. the found substring must not begin in a /// position preceding pos. /// /// https://en.cppreference.com/w/cpp/string/basic_string/find /// /// \\returns Position of the first character of the found substring or npos /// if no such substring is found. [[nodiscard]] constexpr auto find(basic_static_string const& str, size_type pos = 0) const noexcept -> size_type { return find(str.c_str(), pos, str.size()); } /// \\brief Finds the first substring equal to the given character sequence. /// Search begins at pos, i.e. the found substring must not begin in a /// position preceding pos. /// /// https://en.cppreference.com/w/cpp/string/basic_string/find /// /// \\returns Position of the first character of the found substring or npos /// if no such substring is found. [[nodiscard]] constexpr auto find(const_pointer s, size_type pos, size_type count) const noexcept -> size_type { // an empty substring is found at pos if and only if pos <= size() if (count == 0 && pos <= size()) { return pos; } if (pos <= size() - count) { auto view = static_cast>(*this); return view.find(s, pos, count); } return npos; } /// \\brief Finds the first substring equal to the given character sequence. /// Search begins at pos, i.e. the found substring must not begin in a /// position preceding pos. /// /// https://en.cppreference.com/w/cpp/string/basic_string/find /// /// \\returns Position of the first character of the found substring or npos /// if no such substring is found. [[nodiscard]] constexpr auto find( const_pointer s, size_type pos = 0) const noexcept -> size_type { return find(s, pos, traits_type::length(s)); } /// \\brief Finds the first substring equal to the given character sequence. /// Search begins at pos, i.e. the found substring must not begin in a /// position preceding pos. /// /// https://en.cppreference.com/w/cpp/string/basic_string/find /// /// \\returns Position of the first character of the found substring or npos /// if no such substring is found. [[nodiscard]] constexpr auto find( value_type ch, size_type pos = 0) const noexcept -> size_type { return find(&ch, pos, 1); } /// \\brief Finds the last substring equal to the given character sequence. /// Search begins at pos, i.e. the found substring must not begin in a /// position following pos. If npos or any value not smaller than size()-1 /// is passed as pos, whole string will be searched. /// /// https://en.cppreference.com/w/cpp/string/basic_string/rfind /// /// \\returns Position of the first character of the found substring or npos /// if no such substring is found. Note that this is an offset from the /// start of the string, not the end. [[nodiscard]] constexpr auto rfind(basic_static_string const& str, size_type pos = 0) const noexcept -> size_type { return detail::str_rfind( begin(), size(), str.begin(), pos, str.size()); } /// \\brief Finds the last substring equal to the given character sequence. /// Search begins at pos, i.e. the found substring must not begin in a /// position following pos. If npos or any value not smaller than size()-1 /// is passed as pos, whole string will be searched. /// /// https://en.cppreference.com/w/cpp/string/basic_string/rfind /// /// \\returns Position of the first character of the found substring or npos /// if no such substring is found. Note that this is an offset from the /// start of the string, not the end. /// /// \\bug See tests. [[nodiscard]] constexpr auto rfind(const_pointer s, size_type pos, size_type count) const noexcept -> size_type { return detail::str_rfind( begin(), size(), s, pos, count); } /// \\brief Finds the last substring equal to the given character sequence. /// Search begins at pos, i.e. the found substring must not begin in a /// position following pos. If npos or any value not smaller than size()-1 /// is passed as pos, whole string will be searched. /// /// https://en.cppreference.com/w/cpp/string/basic_string/rfind /// /// \\returns Position of the first character of the found substring or npos /// if no such substring is found. Note that this is an offset from the /// start of the string, not the end. [[nodiscard]] constexpr auto rfind( const_pointer s, size_type pos = 0) const noexcept -> size_type { return detail::str_rfind( begin(), size(), s, pos, traits_type::length(s)); } /// \\brief Finds the last substring equal to the given character sequence. /// Search begins at pos, i.e. the found substring must not begin in a /// position following pos. If npos or any value not smaller than size()-1 /// is passed as pos, whole string will be searched. /// /// https://en.cppreference.com/w/cpp/string/basic_string/rfind /// /// \\returns Position of the first character of the found substring or npos /// if no such substring is found. Note that this is an offset from the /// start of the string, not the end. [[nodiscard]] constexpr auto rfind( value_type ch, size_type pos = 0) const noexcept -> size_type { return detail::str_rfind( begin(), size(), ch, pos); } /// \\brief Finds the first character equal to one of the characters in the /// given character sequence. The search considers only the interval [pos, /// size()). If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_first_of(basic_static_string const& str, size_type pos = 0) const noexcept -> size_type { return find_first_of(str.c_str(), pos, str.size()); } /// \\brief Finds the first character equal to one of the characters in the /// given character sequence. The search considers only the interval [pos, /// size()). If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_first_of( const_pointer s, size_type pos, size_type count) const -> size_type { if (pos < size()) { auto view = static_cast>(*this); return view.find_first_of(s, pos, count); } return npos; } /// \\brief Finds the first character equal to one of the characters in the /// given character sequence. The search considers only the interval [pos, /// size()). If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_first_of( const_pointer s, size_type pos = 0) const -> size_type { return find_first_of(s, pos, traits_type::length(s)); } /// \\brief Finds the first character equal to one of the characters in the /// given character sequence. The search considers only the interval [pos, /// size()). If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_first_of( value_type ch, size_type pos = 0) const noexcept -> size_type { return find_first_of(&ch, pos, 1); } /// \\brief Finds the first character equal to one of the characters in the /// given character sequence. The search considers only the interval [pos, /// size()). If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_first_of( basic_string_view str, size_type pos = 0) const noexcept -> size_type { return find_first_of(str.data(), pos, str.size()); } /// \\brief Finds the first character not equal to any of the characters in /// the given character sequence. /// /// \\return Position of the first character not equal to any of the /// characters in the given string, or npos if no such character is found. [[nodiscard]] constexpr auto find_first_not_of( basic_static_string const& str, size_type pos = 0) const noexcept -> size_type { TETL_ASSERT(pos < size()); return detail::str_find_first_not_of(begin(), size(), str.begin(), pos, str.size()); } /// \\brief Finds the first character not equal to any of the characters in /// the given character sequence. /// /// \\return Position of the first character not equal to any of the /// characters in the given string, or npos if no such character is found. [[nodiscard]] constexpr auto find_first_not_of( value_type ch, size_type pos = 0) const noexcept -> size_type { TETL_ASSERT(pos < size()); return detail::str_find_first_not_of(begin(), size(), ch, pos); } /// \\brief Finds the first character not equal to any of the characters in /// the given character sequence. /// /// \\return Position of the first character not equal to any of the /// characters in the given string, or npos if no such character is found. [[nodiscard]] constexpr auto find_first_not_of( value_type const* s, size_type pos) const -> size_type { TETL_ASSERT(pos < size()); return detail::str_find_first_not_of(begin(), size(), s, pos, traits_type::length(s)); } /// \\brief Finds the first character not equal to any of the characters in /// the given character sequence. /// /// \\return Position of the first character not equal to any of the /// characters in the given string, or npos if no such character is found. [[nodiscard]] constexpr auto find_first_not_of( value_type const* s, size_type pos, size_type count) const -> size_type { TETL_ASSERT(pos < size()); return detail::str_find_first_not_of(begin(), size(), s, pos, count); } /// \\brief Finds the last character equal to one of characters in the given /// character sequence. The exact search algorithm is not specified. The /// search considers only the interval [0, pos]. If the character is not /// present in the interval, npos will be returned. [[nodiscard]] constexpr auto find_last_of(basic_static_string const& str, size_type pos = 0) const noexcept -> size_type { auto view = basic_string_view { *this }; return view.find_last_of(str, pos); } /// \\brief Finds the last character equal to one of characters in the given /// character sequence. The exact search algorithm is not specified. The /// search considers only the interval [0, pos]. If the character is not /// present in the interval, npos will be returned. [[nodiscard]] constexpr auto find_last_of( value_type c, size_type pos = 0) const noexcept -> size_type { auto view = basic_string_view { *this }; return view.find_last_of(c, pos); } /// \\brief Finds the last character equal to one of characters in the given /// character sequence. The exact search algorithm is not specified. The /// search considers only the interval [0, pos]. If the character is not /// present in the interval, npos will be returned. [[nodiscard]] constexpr auto find_last_of( value_type const* s, size_type pos, size_type count) const -> size_type { auto view = basic_string_view { *this }; return view.find_last_of(s, pos, count); } /// \\brief Finds the last character equal to one of characters in the given /// character sequence. The exact search algorithm is not specified. The /// search considers only the interval [0, pos]. If the character is not /// present in the interval, npos will be returned. [[nodiscard]] constexpr auto find_last_of( value_type const* s, size_type pos = 0) const -> size_type { auto view = basic_string_view { *this }; return view.find_last_of(s, pos); } /// \\brief Finds the last character equal to none of the characters in the /// given character sequence. The search considers only the interval [0, /// pos]. If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_last_not_of( basic_static_string const& str, size_type pos = 0) const noexcept -> size_type { auto view = basic_string_view { *this }; return view.find_last_not_of(str, pos); } /// \\brief Finds the last character equal to none of the characters in the /// given character sequence. The search considers only the interval [0, /// pos]. If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_last_not_of( value_type c, size_type pos = 0) const noexcept -> size_type { auto view = basic_string_view { *this }; return view.find_last_not_of(c, pos); } /// \\brief Finds the last character equal to none of the characters in the /// given character sequence. The search considers only the interval [0, /// pos]. If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_last_not_of( value_type const* s, size_type pos, size_type count) const -> size_type { auto view = basic_string_view { *this }; return view.find_last_not_of(s, pos, count); } /// \\brief Finds the last character equal to none of the characters in the /// given character sequence. The search considers only the interval [0, /// pos]. If the character is not present in the interval, npos will be /// returned. [[nodiscard]] constexpr auto find_last_not_of( value_type const* s, size_type pos = 0) const -> size_type { auto view = basic_string_view { *this }; return view.find_last_not_of(s, pos); } /// \\brief Checks if the string contains the given substring. [[nodiscard]] constexpr auto contains( etl::basic_string_view sv) const noexcept -> bool { auto view = basic_string_view { *this }; return view.find_last_not_of(sv); } /// \\brief Checks if the string contains the given substring. [[nodiscard]] constexpr auto contains(CharT c) const noexcept -> bool { auto view = basic_string_view { *this }; return view.find_last_not_of(c); } /// \\brief Checks if the string contains the given substring. [[nodiscard]] constexpr auto contains(CharT const* s) const -> bool { auto view = basic_string_view { *this }; return view.find_last_not_of(s); } /// \\brief This is a special value equal to the maximum value representable /// by the type size_type. The exact meaning depends on context, but it is /// generally used either as end of string indicator by the functions that /// expect a string index or as the error indicator by the functions that /// return a string index. constexpr static size_type npos = static_cast(-1); private: constexpr auto unsafe_set_size(size_type const newSize) noexcept -> void { TETL_ASSERT(newSize <= Capacity - 1); size_ = static_cast(newSize); data_[size_] = '\\0'; } [[nodiscard]] constexpr auto unsafe_at(size_type const index) noexcept -> reference { TETL_ASSERT(index < size_); return data_[index]; } [[nodiscard]] constexpr auto unsafe_at(size_type const index) const noexcept -> const_reference { TETL_ASSERT(index < size_); return data_[index]; } constexpr auto insert_impl( iterator pos, const_pointer text, size_type count) -> void { // Insert text at end. auto* currentEnd = end(); append(text, count); // Rotate to correct position etl::rotate(pos, currentEnd, end()); } [[nodiscard]] constexpr auto compare_impl(const_pointer lhs, size_type lhsSize, const_pointer rhs, size_type rhsSize) const noexcept -> int { auto const minSize = etl::min(lhsSize, rhsSize); auto const result = traits_type::compare(lhs, rhs, minSize); if (result != 0) { return result; } if (lhsSize < rhsSize) { return -1; } if (lhsSize > rhsSize) { return 1; } return 0; } constexpr auto clear_storage() noexcept -> void { etl::fill(begin(), end(), CharT(0)); } internal_size_t size_ = 0; value_type data_[Capacity] = {}; }; /// \\brief Returns a string containing characters from lhs followed by the /// characters from rhs. template [[nodiscard]] constexpr auto operator+( basic_static_string const& lhs, basic_static_string const& rhs) noexcept -> basic_static_string { auto str = basic_static_string { lhs }; str.append(rhs); return str; } /// \\brief Returns a string containing characters from lhs followed by the /// characters from rhs. template [[nodiscard]] constexpr auto operator+( basic_static_string const& lhs, CharT const* rhs) noexcept -> basic_static_string { auto str = basic_static_string { lhs }; str.append(rhs); return str; } /// \\brief Returns a string containing characters from lhs followed by the /// characters from rhs. template [[nodiscard]] constexpr auto operator+( basic_static_string const& lhs, CharT rhs) noexcept -> basic_static_string { auto str = basic_static_string { lhs }; str.append(1, rhs); return str; } /// \\brief Returns a string containing characters from lhs followed by the /// characters from rhs. template [[nodiscard]] constexpr auto operator+(CharT const* lhs, basic_static_string const& rhs) noexcept -> basic_static_string { auto str = basic_static_string { lhs }; str.append(rhs); return str; } /// \\brief Returns a string containing characters from lhs followed by the /// characters from rhs. template [[nodiscard]] constexpr auto operator+( CharT lhs, basic_static_string const& rhs) noexcept -> basic_static_string { auto str = basic_static_string { 1, lhs }; str.append(rhs); return str; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details Two strings are equal if both the size of lhs and rhs are equal and /// each character in lhs has equivalent character in rhs at the same position. template [[nodiscard]] constexpr auto operator==( etl::basic_static_string const& lhs, etl::basic_static_string const& rhs) noexcept -> bool { return lhs.compare(rhs) == 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details Two strings are equal if both the size of lhs and rhs are equal and /// each character in lhs has equivalent character in rhs at the same position. template [[nodiscard]] constexpr auto operator==( etl::basic_static_string const& lhs, CharT const* rhs) noexcept -> bool { return lhs.compare(rhs) == 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details Two strings are equal if both the size of lhs and rhs are equal and /// each character in lhs has equivalent character in rhs at the same position. template [[nodiscard]] constexpr auto operator==(CharT const* lhs, etl::basic_static_string const& rhs) noexcept -> bool { return rhs.compare(lhs) == 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details Two strings are equal if both the size of lhs and rhs are equal and /// each character in lhs has equivalent character in rhs at the same position. template [[nodiscard]] constexpr auto operator!=( etl::basic_static_string const& lhs, etl::basic_static_string const& rhs) noexcept -> bool { return lhs.compare(rhs) != 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details Two strings are equal if both the size of lhs and rhs are equal and /// each character in lhs has equivalent character in rhs at the same position. template [[nodiscard]] constexpr auto operator!=( etl::basic_static_string const& lhs, CharT const* rhs) noexcept -> bool { return lhs.compare(rhs) != 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details Two strings are equal if both the size of lhs and rhs are equal and /// each character in lhs has equivalent character in rhs at the same position. template [[nodiscard]] constexpr auto operator!=(CharT const* lhs, etl::basic_static_string const& rhs) noexcept -> bool { return rhs.compare(lhs) != 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator<( etl::basic_static_string const& lhs, etl::basic_static_string const& rhs) noexcept { return lhs.compare(rhs) < 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator<( etl::basic_static_string const& lhs, CharT const* rhs) noexcept -> bool { return lhs.compare(rhs) < 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator<(CharT const* lhs, etl::basic_static_string const& rhs) noexcept -> bool { return rhs.compare(lhs) > 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator<=( etl::basic_static_string const& lhs, etl::basic_static_string const& rhs) noexcept { return lhs.compare(rhs) <= 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator<=( etl::basic_static_string const& lhs, CharT const* rhs) noexcept -> bool { return lhs.compare(rhs) <= 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator<=(CharT const* lhs, etl::basic_static_string const& rhs) noexcept -> bool { return rhs.compare(lhs) >= 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator>( etl::basic_static_string const& lhs, etl::basic_static_string const& rhs) noexcept { return lhs.compare(rhs) > 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator>( etl::basic_static_string const& lhs, CharT const* rhs) noexcept -> bool { return lhs.compare(rhs) > 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator>(CharT const* lhs, etl::basic_static_string const& rhs) noexcept -> bool { return rhs.compare(lhs) < 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator>=( etl::basic_static_string const& lhs, etl::basic_static_string const& rhs) noexcept { return lhs.compare(rhs) >= 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator>=( etl::basic_static_string const& lhs, CharT const* rhs) noexcept -> bool { return lhs.compare(rhs) >= 0; } /// \\brief Compares the contents of a string with another string or a /// null-terminated array of CharT. /// /// \\details The ordering comparisons are done lexicographically. template [[nodiscard]] constexpr auto operator>=(CharT const* lhs, etl::basic_static_string const& rhs) noexcept -> bool { return rhs.compare(lhs) <= 0; } /// \\brief Specializes the etl::swap algorithm for etl::basic_static_string. /// Swaps the contents of lhs and rhs. Equivalent to lhs.swap(rhs). template constexpr auto swap(etl::basic_static_string& lhs, etl::basic_static_string& rhs) noexcept(noexcept(lhs.swap(rhs))) -> void { lhs.swap(rhs); } /// \\brief Erases all elements that compare equal to value from the container. template constexpr auto erase( basic_static_string& c, U const& value) noexcept -> typename basic_static_string::size_type { using return_type = typename basic_static_string::size_type; auto it = etl::remove(begin(c), end(c), value); auto r = etl::distance(it, end(c)); c.erase(it, end(c)); return static_cast(r); } /// \\brief Erases all elements that satisfy the predicate pred from the /// container. template constexpr auto erase_if( basic_static_string& c, Predicate pred) noexcept -> typename basic_static_string::size_type { using return_type = typename basic_static_string::size_type; auto it = etl::remove_if(begin(c), end(c), pred); auto r = etl::distance(it, end(c)); c.erase(it, end(c)); return static_cast(r); } } // namespace etl #endif // TETL_STRING_BASIC_STATIC_STRING_HPP",16323,True,3325.729281480714,median "/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace fsp = folly::portability::sockets; namespace quic { using PacketDropReason = QuicTransportStatsCallback::PacketDropReason; QuicClientTransport::QuicClientTransport( folly::EventBase* evb, std::unique_ptr socket, std::shared_ptr handshakeFactory, size_t connectionIdSize, PacketNum startingPacketNum, bool useSplitConnectionCallbacks) : QuicClientTransport( evb, std::move(socket), std::move(handshakeFactory), connectionIdSize, useSplitConnectionCallbacks) { conn_->ackStates = AckStates(startingPacketNum); } QuicClientTransport::QuicClientTransport( folly::EventBase* evb, std::unique_ptr socket, std::shared_ptr handshakeFactory, size_t connectionIdSize, bool useSplitConnectionCallbacks) : QuicTransportBase(evb, std::move(socket), useSplitConnectionCallbacks), happyEyeballsConnAttemptDelayTimeout_(this) { DCHECK(handshakeFactory); auto tempConn = std::make_unique(std::move(handshakeFactory)); clientConn_ = tempConn.get(); conn_.reset(tempConn.release()); conn_->observers = observers_; auto srcConnId = connectionIdSize > 0 ? ConnectionId::createRandom(connectionIdSize) : ConnectionId(std::vector()); conn_->clientConnectionId = srcConnId; conn_->readCodec = std::make_unique(QuicNodeType::Client); conn_->readCodec->setClientConnectionId(srcConnId); conn_->selfConnectionIds.emplace_back(srcConnId, kInitialSequenceNumber); clientConn_->initialDestinationConnectionId = ConnectionId::createRandom(kMinInitialDestinationConnIdLength); clientConn_->originalDestinationConnectionId = clientConn_->initialDestinationConnectionId; conn_->clientChosenDestConnectionId = clientConn_->initialDestinationConnectionId; VLOG(4) << ""initial dcid: "" << clientConn_->initialDestinationConnectionId->hex(); if (conn_->qLogger) { conn_->qLogger->setDcid(conn_->clientChosenDestConnectionId); } conn_->readCodec->setCodecParameters(CodecParameters( conn_->peerAckDelayExponent, conn_->originalVersion.value())); VLOG(10) << ""client created "" << *conn_; } QuicClientTransport::~QuicClientTransport() { VLOG(10) << ""Destroyed connection to server="" << conn_->peerAddress; // The caller probably doesn't need the conn callback after destroying the // transport. resetConnectionCallbacks(); // Close without draining. closeImpl( std::make_pair( QuicErrorCode(LocalErrorCode::SHUTTING_DOWN), std::string(""Closing from client destructor"")), false); if (clientConn_->happyEyeballsState.secondSocket) { auto sock = std::move(clientConn_->happyEyeballsState.secondSocket); sock->pauseRead(); sock->close(); } } void QuicClientTransport::processUDPData( const folly::SocketAddress& peer, NetworkDataSingle&& networkData) { BufQueue udpData; udpData.append(std::move(networkData.data)); if (!conn_->version) { // We only check for version negotiation packets before the version // is negotiated. auto versionNegotiation = conn_->readCodec->tryParsingVersionNegotiation(udpData); if (versionNegotiation) { VLOG(4) << ""Got version negotiation packet from peer="" << peer << "" versions="" << std::hex << versionNegotiation->versions << "" "" << *this; throw QuicInternalException( ""Received version negotiation packet"", LocalErrorCode::CONNECTION_ABANDONED); } } for (uint16_t processedPackets = 0; !udpData.empty() && processedPackets < kMaxNumCoalescedPackets; processedPackets++) { processPacketData(peer, networkData.receiveTimePoint, udpData); } VLOG_IF(4, !udpData.empty()) << ""Leaving "" << udpData.chainLength() << "" bytes unprocessed after attempting to process "" << kMaxNumCoalescedPackets << "" packets.""; // Process any pending 1RTT and handshake packets if we have keys. if (conn_->readCodec->getOneRttReadCipher() && !clientConn_->pendingOneRttData.empty()) { BufQueue pendingPacket; for (auto& pendingData : clientConn_->pendingOneRttData) { pendingPacket.append(std::move(pendingData.networkData.data)); processPacketData( pendingData.peer, pendingData.networkData.receiveTimePoint, pendingPacket); pendingPacket.move(); } clientConn_->pendingOneRttData.clear(); } if (conn_->readCodec->getHandshakeReadCipher() && !clientConn_->pendingHandshakeData.empty()) { BufQueue pendingPacket; for (auto& pendingData : clientConn_->pendingHandshakeData) { pendingPacket.append(std::move(pendingData.networkData.data)); processPacketData( pendingData.peer, pendingData.networkData.receiveTimePoint, pendingPacket); pendingPacket.move(); } clientConn_->pendingHandshakeData.clear(); } } void QuicClientTransport::processPacketData( const folly::SocketAddress& peer, TimePoint receiveTimePoint, BufQueue& packetQueue) { auto packetSize = packetQueue.chainLength(); if (packetSize == 0) { return; } auto parsedPacket = conn_->readCodec->parsePacket( packetQueue, conn_->ackStates, conn_->clientConnectionId->size()); StatelessReset* statelessReset = parsedPacket.statelessReset(); if (statelessReset) { const auto& token = clientConn_->statelessResetToken; if (statelessReset->token == token) { VLOG(4) << ""Received Stateless Reset "" << *this; conn_->peerConnectionError = std::make_pair( QuicErrorCode(LocalErrorCode::CONNECTION_RESET), toString(LocalErrorCode::CONNECTION_RESET).str()); throw QuicInternalException(""Peer reset"", LocalErrorCode::NO_ERROR); } VLOG(4) << ""Drop StatelessReset for bad connId or token "" << *this; } RetryPacket* retryPacket = parsedPacket.retryPacket(); if (retryPacket) { if (conn_->qLogger) { conn_->qLogger->addPacket(*retryPacket, packetSize, true); } if (!clientConn_->retryToken.empty()) { VLOG(4) << ""Server sent more than one retry packet""; return; } const ConnectionId* originalDstConnId = &(*clientConn_->originalDestinationConnectionId); if (!clientConn_->clientHandshakeLayer->verifyRetryIntegrityTag( *originalDstConnId, *retryPacket)) { VLOG(4) << ""The integrity tag in the retry packet was invalid. "" << ""Dropping bad retry packet.""; return; } if (happyEyeballsEnabled_) { happyEyeballsOnDataReceived( *clientConn_, happyEyeballsConnAttemptDelayTimeout_, socket_, peer); } // Set the destination connection ID to be the value from the source // connection id of the retry packet clientConn_->initialDestinationConnectionId = retryPacket->header.getSourceConnId(); auto released = static_cast(conn_.release()); std::unique_ptr uniqueClient(released); auto tempConn = undoAllClientStateForRetry(std::move(uniqueClient)); clientConn_ = tempConn.get(); conn_.reset(tempConn.release()); clientConn_->retryToken = retryPacket->header.getToken(); // TODO (amsharma): add a ""RetryPacket"" QLog event, and log it here. // TODO (amsharma): verify the ""original_connection_id"" parameter // upon receiving a subsequent initial from the server. startCryptoHandshake(); return; } auto cipherUnavailable = parsedPacket.cipherUnavailable(); if (cipherUnavailable && cipherUnavailable->packet && !cipherUnavailable->packet->empty() && (cipherUnavailable->protectionType == ProtectionType::KeyPhaseZero || cipherUnavailable->protectionType == ProtectionType::Handshake) && clientConn_->pendingOneRttData.size() + clientConn_->pendingHandshakeData.size() < clientConn_->transportSettings.maxPacketsToBuffer) { auto& pendingData = cipherUnavailable->protectionType == ProtectionType::KeyPhaseZero ? clientConn_->pendingOneRttData : clientConn_->pendingHandshakeData; pendingData.emplace_back( NetworkDataSingle( std::move(cipherUnavailable->packet), receiveTimePoint), peer); if (conn_->qLogger) { conn_->qLogger->addPacketBuffered( cipherUnavailable->protectionType, packetSize); } return; } RegularQuicPacket* regularOptional = parsedPacket.regularPacket(); if (!regularOptional) { QUIC_STATS(statsCallback_, onPacketDropped, PacketDropReason::PARSE_ERROR); if (conn_->qLogger) { conn_->qLogger->addPacketDrop(packetSize, kParse); } return; } if (regularOptional->frames.empty()) { // This is either a packet that has no data (long-header parsed but no data // found) or a regular packet with a short header and no frames. Both are // protocol violations. QUIC_STATS( conn_->statsCallback, onPacketDropped, PacketDropReason::PROTOCOL_VIOLATION); if (conn_->qLogger) { conn_->qLogger->addPacketDrop( packetSize, QuicTransportStatsCallback::toString( PacketDropReason::PROTOCOL_VIOLATION)); } throw QuicTransportException( ""Packet has no frames"", TransportErrorCode::PROTOCOL_VIOLATION); } if (happyEyeballsEnabled_) { CHECK(socket_); happyEyeballsOnDataReceived( *clientConn_, happyEyeballsConnAttemptDelayTimeout_, socket_, peer); } LongHeader* longHeader = regularOptional->header.asLong(); ShortHeader* shortHeader = regularOptional->header.asShort(); auto protectionLevel = regularOptional->header.getProtectionType(); auto encryptionLevel = protectionTypeToEncryptionLevel(protectionLevel); auto packetNum = regularOptional->header.getPacketSequenceNum(); auto pnSpace = regularOptional->header.getPacketNumberSpace(); bool isProtectedPacket = protectionLevel == ProtectionType::KeyPhaseZero || protectionLevel == ProtectionType::KeyPhaseOne; auto& regularPacket = *regularOptional; if (conn_->qLogger) { conn_->qLogger->addPacket(regularPacket, packetSize); } if (!isProtectedPacket) { for (auto& quicFrame : regularPacket.frames) { auto isPadding = quicFrame.asPaddingFrame(); auto isAck = quicFrame.asReadAckFrame(); auto isClose = quicFrame.asConnectionCloseFrame(); auto isCrypto = quicFrame.asReadCryptoFrame(); auto isPing = quicFrame.asPingFrame(); // TODO: add path challenge and response if (!isPadding && !isAck && !isClose && !isCrypto && !isPing) { throw QuicTransportException( ""Invalid frame"", TransportErrorCode::PROTOCOL_VIOLATION); } } } // We got a packet that was not the version negotiation packet, that means // that the version is now bound to the new packet. if (!conn_->version) { conn_->version = conn_->originalVersion; } if (!conn_->serverConnectionId && longHeader) { conn_->serverConnectionId = longHeader->getSourceConnId(); conn_->peerConnectionIds.emplace_back( longHeader->getSourceConnId(), kInitialSequenceNumber); conn_->readCodec->setServerConnectionId(*conn_->serverConnectionId); } // Error out if the connection id on the packet is not the one that is // expected. bool connidMatched = true; if ((longHeader && longHeader->getDestinationConnId() != *conn_->clientConnectionId) || (shortHeader && shortHeader->getConnectionId() != *conn_->clientConnectionId)) { connidMatched = false; } if (!connidMatched) { throw QuicTransportException( ""Invalid connection id"", TransportErrorCode::PROTOCOL_VIOLATION); } auto& ackState = getAckState(*conn_, pnSpace); bool outOfOrder = updateLargestReceivedPacketNum(ackState, packetNum, receiveTimePoint); if (outOfOrder) { QUIC_STATS(conn_->statsCallback, onOutOfOrderPacketReceived); } bool pktHasRetransmittableData = false; bool pktHasCryptoData = false; for (auto& quicFrame : regularPacket.frames) { switch (quicFrame.type()) { case QuicFrame::Type::ReadAckFrame: { VLOG(10) << ""Client received ack frame in packet="" << packetNum << "" "" << *this; ReadAckFrame& ackFrame = *quicFrame.asReadAckFrame(); processAckFrame( *conn_, pnSpace, ackFrame, [&](const OutstandingPacket& outstandingPacket, const QuicWriteFrame& packetFrame, const ReadAckFrame&) { auto outstandingProtectionType = outstandingPacket.packet.header.getProtectionType(); if (outstandingProtectionType == ProtectionType::KeyPhaseZero) { // If we received an ack for data that we sent in 1-rtt from // the server, we can assume that the server had successfully // derived the 1-rtt keys and hence received the client // finished message. We can mark the handshake as confirmed and // drop the handshake cipher and outstanding packets after the // processing loop. conn_->handshakeLayer->handshakeConfirmed(); } switch (packetFrame.type()) { case QuicWriteFrame::Type::WriteAckFrame: { const WriteAckFrame& frame = *packetFrame.asWriteAckFrame(); DCHECK(!frame.ackBlocks.empty()); VLOG(4) << ""Client received ack for largestAcked="" << frame.ackBlocks.front().end << "" "" << *this; commonAckVisitorForAckFrame(ackState, frame); break; } case QuicWriteFrame::Type::RstStreamFrame: { const RstStreamFrame& frame = *packetFrame.asRstStreamFrame(); VLOG(4) << ""Client received ack for reset frame stream="" << frame.streamId << "" "" << *this; auto stream = conn_->streamManager->getStream(frame.streamId); if (stream) { sendRstAckSMHandler(*stream); } break; } case QuicWriteFrame::Type::WriteStreamFrame: { const WriteStreamFrame& frame = *packetFrame.asWriteStreamFrame(); auto ackedStream = conn_->streamManager->getStream(frame.streamId); VLOG(4) << ""Client got ack for stream="" << frame.streamId << "" offset="" << frame.offset << "" fin="" << frame.fin << "" data="" << frame.len << "" closed="" << (ackedStream == nullptr) << "" "" << *this; if (ackedStream) { sendAckSMHandler(*ackedStream, frame); } break; } case QuicWriteFrame::Type::WriteCryptoFrame: { const WriteCryptoFrame& frame = *packetFrame.asWriteCryptoFrame(); auto cryptoStream = getCryptoStream( *conn_->cryptoState, protectionTypeToEncryptionLevel( outstandingProtectionType)); processCryptoStreamAck( *cryptoStream, frame.offset, frame.len); break; } case QuicWriteFrame::Type::PingFrame: conn_->pendingEvents.cancelPingTimeout = true; break; case QuicWriteFrame::Type::QuicSimpleFrame: default: // ignore other frames. break; } }, markPacketLoss, receiveTimePoint); break; } case QuicFrame::Type::RstStreamFrame: { RstStreamFrame& frame = *quicFrame.asRstStreamFrame(); VLOG(10) << ""Client received reset stream="" << frame.streamId << "" "" << *this; pktHasRetransmittableData = true; auto streamId = frame.streamId; auto stream = conn_->streamManager->getStream(streamId); if (!stream) { break; } receiveRstStreamSMHandler(*stream, frame); break; } case QuicFrame::Type::ReadCryptoFrame: { pktHasRetransmittableData = true; pktHasCryptoData = true; ReadCryptoFrame& cryptoFrame = *quicFrame.asReadCryptoFrame(); VLOG(10) << ""Client received crypto data offset="" << cryptoFrame.offset << "" len="" << cryptoFrame.data->computeChainDataLength() << "" packetNum="" << packetNum << "" "" << *this; appendDataToReadBuffer( *getCryptoStream(*conn_->cryptoState, encryptionLevel), StreamBuffer( std::move(cryptoFrame.data), cryptoFrame.offset, false)); break; } case QuicFrame::Type::ReadStreamFrame: { ReadStreamFrame& frame = *quicFrame.asReadStreamFrame(); VLOG(10) << ""Client received stream data for stream="" << frame.streamId << "" offset="" << frame.offset << "" len="" << frame.data->computeChainDataLength() << "" fin="" << frame.fin << "" packetNum="" << packetNum << "" "" << *this; auto stream = conn_->streamManager->getStream(frame.streamId); pktHasRetransmittableData = true; if (!stream) { VLOG(10) << ""Could not find stream="" << frame.streamId << "" "" << *conn_; break; } receiveReadStreamFrameSMHandler(*stream, std::move(frame)); break; } case QuicFrame::Type::MaxDataFrame: { MaxDataFrame& connWindowUpdate = *quicFrame.asMaxDataFrame(); VLOG(10) << ""Client received max data offset="" << connWindowUpdate.maximumData << "" "" << *this; pktHasRetransmittableData = true; handleConnWindowUpdate(*conn_, connWindowUpdate, packetNum); break; } case QuicFrame::Type::MaxStreamDataFrame: { MaxStreamDataFrame& streamWindowUpdate = *quicFrame.asMaxStreamDataFrame(); VLOG(10) << ""Client received max stream data stream="" << streamWindowUpdate.streamId << "" offset="" << streamWindowUpdate.maximumData << "" "" << *this; if (isReceivingStream(conn_->nodeType, streamWindowUpdate.streamId)) { throw QuicTransportException( ""Received MaxStreamDataFrame for receiving stream."", TransportErrorCode::STREAM_STATE_ERROR); } pktHasRetransmittableData = true; auto stream = conn_->streamManager->getStream(streamWindowUpdate.streamId); if (stream) { handleStreamWindowUpdate( *stream, streamWindowUpdate.maximumData, packetNum); } break; } case QuicFrame::Type::DataBlockedFrame: { VLOG(10) << ""Client received blocked "" << *this; pktHasRetransmittableData = true; handleConnBlocked(*conn_); break; } case QuicFrame::Type::StreamDataBlockedFrame: { // peer wishes to send data, but is unable to due to stream-level flow // control StreamDataBlockedFrame& blocked = *quicFrame.asStreamDataBlockedFrame(); VLOG(10) << ""Client received blocked stream="" << blocked.streamId << "" "" << *this; pktHasRetransmittableData = true; auto stream = conn_->streamManager->getStream(blocked.streamId); if (stream) { handleStreamBlocked(*stream); } break; } case QuicFrame::Type::StreamsBlockedFrame: { // peer wishes to open a stream, but is unable to due to the maximum // stream limit set by us StreamsBlockedFrame& blocked = *quicFrame.asStreamsBlockedFrame(); VLOG(10) << ""Client received stream blocked limit="" << blocked.streamLimit << "" "" << *this; // TODO implement handler for it break; } case QuicFrame::Type::ConnectionCloseFrame: { ConnectionCloseFrame& connFrame = *quicFrame.asConnectionCloseFrame(); auto errMsg = folly::to( ""Client closed by peer reason="", connFrame.reasonPhrase); VLOG(4) << errMsg << "" "" << *this; // we want to deliver app callbacks with the peer supplied error, // but send a NO_ERROR to the peer. if (conn_->qLogger) { conn_->qLogger->addTransportStateUpdate(getPeerClose(errMsg)); } conn_->peerConnectionError = std::make_pair( QuicErrorCode(connFrame.errorCode), std::move(errMsg)); throw QuicTransportException( ""Peer closed"", TransportErrorCode::NO_ERROR); break; } case QuicFrame::Type::PingFrame: // Ping isn't retransmittable. But we would like to ack them early. // So, make Ping frames count towards ack policy pktHasRetransmittableData = true; break; case QuicFrame::Type::PaddingFrame: break; case QuicFrame::Type::QuicSimpleFrame: { QuicSimpleFrame& simpleFrame = *quicFrame.asQuicSimpleFrame(); pktHasRetransmittableData = true; updateSimpleFrameOnPacketReceived( *conn_, simpleFrame, packetNum, false); break; } case QuicFrame::Type::DatagramFrame: { DatagramFrame& frame = *quicFrame.asDatagramFrame(); VLOG(10) << ""Client received datagram data: "" << ""len="" << frame.length << "" "" << *this; // Datagram isn't retransmittable. But we would like to ack them early. // So, make Datagram frames count towards ack policy pktHasRetransmittableData = true; handleDatagram(*conn_, frame); break; } default: break; } } auto handshakeLayer = clientConn_->clientHandshakeLayer; if (handshakeLayer->getPhase() == ClientHandshake::Phase::Established && hasInitialOrHandshakeCiphers(*conn_)) { handshakeConfirmed(*conn_); } // Try reading bytes off of crypto, and performing a handshake. auto cryptoData = readDataFromCryptoStream( *getCryptoStream(*conn_->cryptoState, encryptionLevel)); if (cryptoData) { bool hadOneRttKey = conn_->oneRttWriteCipher != nullptr; handshakeLayer->doHandshake(std::move(cryptoData), encryptionLevel); bool oneRttKeyDerivationTriggered = false; if (!hadOneRttKey && conn_->oneRttWriteCipher) { oneRttKeyDerivationTriggered = true; updatePacingOnKeyEstablished(*conn_); } if (conn_->oneRttWriteCipher && conn_->readCodec->getOneRttReadCipher()) { clientConn_->zeroRttWriteCipher.reset(); clientConn_->zeroRttWriteHeaderCipher.reset(); } auto zeroRttRejected = handshakeLayer->getZeroRttRejected(); if (zeroRttRejected.has_value() && *zeroRttRejected) { if (conn_->qLogger) { conn_->qLogger->addTransportStateUpdate(kZeroRttRejected); } handshakeLayer->removePsk(hostname_); } else if (zeroRttRejected.has_value()) { if (conn_->qLogger) { conn_->qLogger->addTransportStateUpdate(kZeroRttAccepted); } conn_->usedZeroRtt = true; } // We should get transport parameters if we've derived 1-rtt keys and 0-rtt // was rejected, or we have derived 1-rtt keys and 0-rtt was never // attempted. if (oneRttKeyDerivationTriggered) { auto serverParams = handshakeLayer->getServerTransportParams(); if (!serverParams) { throw QuicTransportException( ""No server transport params"", TransportErrorCode::TRANSPORT_PARAMETER_ERROR); } if ((zeroRttRejected.has_value() && *zeroRttRejected) || !zeroRttRejected.has_value()) { auto originalPeerMaxOffset = conn_->flowControlState.peerAdvertisedMaxOffset; auto originalPeerInitialStreamOffsetBidiLocal = conn_->flowControlState .peerAdvertisedInitialMaxStreamOffsetBidiLocal; auto originalPeerInitialStreamOffsetBidiRemote = conn_->flowControlState .peerAdvertisedInitialMaxStreamOffsetBidiRemote; auto originalPeerInitialStreamOffsetUni = conn_->flowControlState.peerAdvertisedInitialMaxStreamOffsetUni; VLOG(10) << ""Client negotiated transport params "" << *this; auto maxStreamsBidi = getIntegerParameter( TransportParameterId::initial_max_streams_bidi, serverParams->parameters); auto maxStreamsUni = getIntegerParameter( TransportParameterId::initial_max_streams_uni, serverParams->parameters); processServerInitialParams( *clientConn_, std::move(*serverParams), packetNum); cacheServerInitialParams( *clientConn_, conn_->flowControlState.peerAdvertisedMaxOffset, conn_->flowControlState .peerAdvertisedInitialMaxStreamOffsetBidiLocal, conn_->flowControlState .peerAdvertisedInitialMaxStreamOffsetBidiRemote, conn_->flowControlState.peerAdvertisedInitialMaxStreamOffsetUni, maxStreamsBidi.value_or(0), maxStreamsUni.value_or(0)); if (zeroRttRejected.has_value() && *zeroRttRejected) { // verify that the new flow control parameters are >= the original // transport parameters that were use. This is the easy case. If the // flow control decreases then we are just screwed and we need to have // the app retry the connection. The other parameters can be updated. // TODO: implement undo transport state on retry. if (originalPeerMaxOffset > conn_->flowControlState.peerAdvertisedMaxOffset || originalPeerInitialStreamOffsetBidiLocal > conn_->flowControlState .peerAdvertisedInitialMaxStreamOffsetBidiLocal || originalPeerInitialStreamOffsetBidiRemote > conn_->flowControlState .peerAdvertisedInitialMaxStreamOffsetBidiRemote || originalPeerInitialStreamOffsetUni > conn_->flowControlState .peerAdvertisedInitialMaxStreamOffsetUni) { throw QuicTransportException( ""Rejection of zero rtt parameters unsupported"", TransportErrorCode::TRANSPORT_PARAMETER_ERROR); } } } // TODO This sucks, but manually update the max packet size until we fix // 0-rtt transport parameters. if (conn_->transportSettings.canIgnorePathMTU && zeroRttRejected.has_value() && !*zeroRttRejected) { auto updatedPacketSize = getIntegerParameter( TransportParameterId::max_packet_size, serverParams->parameters); updatedPacketSize = std::max( updatedPacketSize.value_or(kDefaultUDPSendPacketLen), kDefaultUDPSendPacketLen); updatedPacketSize = std::min(*updatedPacketSize, kDefaultMaxUDPPayload); conn_->udpSendPacketLen = *updatedPacketSize; } // TODO this is another bandaid. Explicitly set the stateless reset token // or else conns that use 0-RTT won't be able to parse stateless resets. if (!clientConn_->statelessResetToken) { clientConn_->statelessResetToken = getStatelessResetTokenParameter(serverParams->parameters); } if (clientConn_->statelessResetToken) { conn_->readCodec->setStatelessResetToken( clientConn_->statelessResetToken.value()); } } if (zeroRttRejected.has_value() && *zeroRttRejected) { // TODO: Make sure the alpn is the same, if not then do a full undo of the // state. clientConn_->zeroRttWriteCipher.reset(); clientConn_->zeroRttWriteHeaderCipher.reset(); markZeroRttPacketsLost(*conn_, markPacketLoss); } } updateAckSendStateOnRecvPacket( *conn_, ackState, outOfOrder, pktHasRetransmittableData, pktHasCryptoData); if (encryptionLevel == EncryptionLevel::Handshake && conn_->initialWriteCipher) { conn_->initialWriteCipher.reset(); conn_->initialHeaderCipher.reset(); conn_->readCodec->setInitialReadCipher(nullptr); conn_->readCodec->setInitialHeaderCipher(nullptr); implicitAckCryptoStream(*conn_, EncryptionLevel::Initial); } } void QuicClientTransport::onReadData( const folly::SocketAddress& peer, NetworkDataSingle&& networkData) { if (closeState_ == CloseState::CLOSED) { // If we are closed, then we shoudn't process new network data. QUIC_STATS( statsCallback_, onPacketDropped, PacketDropReason::CLIENT_STATE_CLOSED); if (conn_->qLogger) { conn_->qLogger->addPacketDrop(0, kAlreadyClosed); } return; } bool waitingForFirstPacket = !hasReceivedPackets(*conn_); processUDPData(peer, std::move(networkData)); if (connCallback_ && waitingForFirstPacket && hasReceivedPackets(*conn_)) { connCallback_->onFirstPeerPacketProcessed(); } if (!transportReadyNotified_ && hasWriteCipher()) { transportReadyNotified_ = true; connCallback_->onTransportReady(); } // Checking connCallback_ because application will start to write data // in onTransportReady, if the write fails, QuicSocket can be closed // and connCallback_ is set nullptr. if (connCallback_ && !replaySafeNotified_ && conn_->oneRttWriteCipher) { // If there is 0RTT data still outstanding, opportunistically retransmit // it rather than waiting for the loss recovery. if (conn_->transportSettings.earlyRetransmit0Rtt) { markZeroRttPacketsLost(*conn_, markPacketLoss); } replaySafeNotified_ = true; // We don't need this any more. Also unset it so that we don't allow random // middleboxes to shutdown our connection once we have crypto keys. socket_->setErrMessageCallback(nullptr); connCallback_->onReplaySafe(); } maybeSendTransportKnobs(); } void QuicClientTransport::writeData() { QuicVersion version = conn_->version.value_or(*conn_->originalVersion); const ConnectionId& srcConnId = *conn_->clientConnectionId; const ConnectionId* destConnId = &(*clientConn_->initialDestinationConnectionId); if (conn_->serverConnectionId) { destConnId = &(*conn_->serverConnectionId); } if (closeState_ == CloseState::CLOSED) { auto rtt = clientConn_->lossState.srtt == 0us ? clientConn_->transportSettings.initialRtt : clientConn_->lossState.srtt; if (clientConn_->lastCloseSentTime && Clock::now() - *clientConn_->lastCloseSentTime < rtt) { return; } clientConn_->lastCloseSentTime = Clock::now(); if (clientConn_->clientHandshakeLayer->getPhase() == ClientHandshake::Phase::Established && conn_->oneRttWriteCipher) { CHECK(conn_->oneRttWriteHeaderCipher); writeShortClose( *socket_, *conn_, *destConnId, conn_->localConnectionError, *conn_->oneRttWriteCipher, *conn_->oneRttWriteHeaderCipher); } if (conn_->handshakeWriteCipher) { CHECK(conn_->handshakeWriteHeaderCipher); writeLongClose( *socket_, *conn_, srcConnId, *destConnId, LongHeader::Types::Handshake, conn_->localConnectionError, *conn_->handshakeWriteCipher, *conn_->handshakeWriteHeaderCipher, version); } if (conn_->initialWriteCipher) { CHECK(conn_->initialHeaderCipher); writeLongClose( *socket_, *conn_, srcConnId, *destConnId, LongHeader::Types::Initial, conn_->localConnectionError, *conn_->initialWriteCipher, *conn_->initialHeaderCipher, version); } return; } uint64_t packetLimit = (isConnectionPaced(*conn_) ? conn_->pacer->updateAndGetWriteBatchSize(Clock::now()) : conn_->transportSettings.writeConnectionDataPacketsLimit); // At the end of this function, clear out any probe packets credit we didn't // use. SCOPE_EXIT { conn_->pendingEvents.numProbePackets = {}; }; if (conn_->initialWriteCipher) { auto& initialCryptoStream = *getCryptoStream(*conn_->cryptoState, EncryptionLevel::Initial); CryptoStreamScheduler initialScheduler(*conn_, initialCryptoStream); auto& numProbePackets = conn_->pendingEvents.numProbePackets[PacketNumberSpace::Initial]; if ((initialCryptoStream.retransmissionBuffer.size() && conn_->outstandings.packetCount[PacketNumberSpace::Initial] && numProbePackets) || initialScheduler.hasData() || (conn_->ackStates.initialAckState.needsToSendAckImmediately && hasAcksToSchedule(conn_->ackStates.initialAckState))) { CHECK(conn_->initialHeaderCipher); packetLimit -= writeCryptoAndAckDataToSocket( *socket_, *conn_, srcConnId /* src */, *destConnId /* dst */, LongHeader::Types::Initial, *conn_->initialWriteCipher, *conn_->initialHeaderCipher, version, packetLimit, clientConn_->retryToken) .packetsWritten; } if (!packetLimit && !conn_->pendingEvents.anyProbePackets()) { return; } } if (conn_->handshakeWriteCipher) { auto& handshakeCryptoStream = *getCryptoStream(*conn_->cryptoState, EncryptionLevel::Handshake); CryptoStreamScheduler handshakeScheduler(*conn_, handshakeCryptoStream); auto& numProbePackets = conn_->pendingEvents.numProbePackets[PacketNumberSpace::Handshake]; if ((conn_->outstandings.packetCount[PacketNumberSpace::Handshake] && handshakeCryptoStream.retransmissionBuffer.size() && numProbePackets) || handshakeScheduler.hasData() || (conn_->ackStates.handshakeAckState.needsToSendAckImmediately && hasAcksToSchedule(conn_->ackStates.handshakeAckState))) { CHECK(conn_->handshakeWriteHeaderCipher); packetLimit -= writeCryptoAndAckDataToSocket( *socket_, *conn_, srcConnId /* src */, *destConnId /* dst */, LongHeader::Types::Handshake, *conn_->handshakeWriteCipher, *conn_->handshakeWriteHeaderCipher, version, packetLimit) .packetsWritten; } if (!packetLimit && !conn_->pendingEvents.anyProbePackets()) { return; } } if (clientConn_->zeroRttWriteCipher && !conn_->oneRttWriteCipher) { CHECK(clientConn_->zeroRttWriteHeaderCipher); packetLimit -= writeZeroRttDataToSocket( *socket_, *conn_, srcConnId /* src */, *destConnId /* dst */, *clientConn_->zeroRttWriteCipher, *clientConn_->zeroRttWriteHeaderCipher, version, packetLimit); } if (!packetLimit && !conn_->pendingEvents.anyProbePackets()) { return; } if (conn_->oneRttWriteCipher) { CHECK(clientConn_->oneRttWriteHeaderCipher); writeQuicDataExceptCryptoStreamToSocket( *socket_, *conn_, srcConnId, *destConnId, *conn_->oneRttWriteCipher, *conn_->oneRttWriteHeaderCipher, version, packetLimit); } } void QuicClientTransport::startCryptoHandshake() { auto self = this->shared_from_this(); setIdleTimer(); // We need to update the flow control settings every time we start a crypto // handshake. This is so that we can reset the flow control settings when // we go through version negotiation as well. updateFlowControlStateWithSettings( conn_->flowControlState, conn_->transportSettings); auto handshakeLayer = clientConn_->clientHandshakeLayer; auto& cryptoFactory = handshakeLayer->getCryptoFactory(); auto version = conn_->originalVersion.value(); conn_->initialWriteCipher = cryptoFactory.getClientInitialCipher( *clientConn_->initialDestinationConnectionId, version); conn_->readCodec->setInitialReadCipher(cryptoFactory.getServerInitialCipher( *clientConn_->initialDestinationConnectionId, version)); conn_->readCodec->setInitialHeaderCipher( cryptoFactory.makeServerInitialHeaderCipher( *clientConn_->initialDestinationConnectionId, version)); conn_->initialHeaderCipher = cryptoFactory.makeClientInitialHeaderCipher( *clientConn_->initialDestinationConnectionId, version); setD6DBasePMTUTransportParameter(); setD6DRaiseTimeoutTransportParameter(); setD6DProbeTimeoutTransportParameter(); setSupportedExtensionTransportParameters(); auto paramsExtension = std::make_shared( conn_->originalVersion.value(), conn_->transportSettings.advertisedInitialConnectionWindowSize, conn_->transportSettings.advertisedInitialBidiLocalStreamWindowSize, conn_->transportSettings.advertisedInitialBidiRemoteStreamWindowSize, conn_->transportSettings.advertisedInitialUniStreamWindowSize, conn_->transportSettings.advertisedInitialMaxStreamsBidi, conn_->transportSettings.advertisedInitialMaxStreamsUni, conn_->transportSettings.idleTimeout, conn_->transportSettings.ackDelayExponent, conn_->transportSettings.maxRecvPacketSize, conn_->transportSettings.selfActiveConnectionIdLimit, conn_->clientConnectionId.value(), customTransportParameters_); conn_->transportParametersEncoded = true; handshakeLayer->connect(hostname_, std::move(paramsExtension)); writeSocketData(); if (!transportReadyNotified_ && clientConn_->zeroRttWriteCipher) { transportReadyNotified_ = true; runOnEvbAsync([](auto self) { auto clientPtr = static_cast(self.get()); if (clientPtr->connCallback_) { clientPtr->connCallback_->onTransportReady(); } }); } } bool QuicClientTransport::hasWriteCipher() const { return clientConn_->oneRttWriteCipher || clientConn_->zeroRttWriteCipher; } std::shared_ptr QuicClientTransport::sharedGuard() { return shared_from_this(); } bool QuicClientTransport::isTLSResumed() const { return clientConn_->clientHandshakeLayer->isTLSResumed(); } void QuicClientTransport::errMessage( FOLLY_MAYBE_UNUSED const cmsghdr& cmsg) noexcept { #ifdef FOLLY_HAVE_MSG_ERRQUEUE if ((cmsg.cmsg_level == SOL_IP && cmsg.cmsg_type == IP_RECVERR) || (cmsg.cmsg_level == SOL_IPV6 && cmsg.cmsg_type == IPV6_RECVERR)) { // Time to make some assumptions. We assume the first socket == IPv6, if it // exists, and the second socket is IPv4. Then we basically do the same // thing we would have done if we'd gotten a write error on that socket. // If both sockets are not functional we close the connection. auto& happyEyeballsState = clientConn_->happyEyeballsState; if (!happyEyeballsState.finished) { if (cmsg.cmsg_level == SOL_IPV6 && happyEyeballsState.shouldWriteToFirstSocket) { happyEyeballsState.shouldWriteToFirstSocket = false; socket_->pauseRead(); if (happyEyeballsState.connAttemptDelayTimeout && happyEyeballsState.connAttemptDelayTimeout->isScheduled()) { happyEyeballsState.connAttemptDelayTimeout->timeoutExpired(); happyEyeballsState.connAttemptDelayTimeout->cancelTimeout(); } } else if ( cmsg.cmsg_level == SOL_IP && happyEyeballsState.shouldWriteToSecondSocket) { happyEyeballsState.shouldWriteToSecondSocket = false; happyEyeballsState.secondSocket->pauseRead(); } } const struct sock_extended_err* serr = reinterpret_cast(CMSG_DATA(&cmsg)); auto errStr = folly::errnoStr(serr->ee_errno); if (!happyEyeballsState.shouldWriteToFirstSocket && !happyEyeballsState.shouldWriteToSecondSocket) { runOnEvbAsync([errString = std::move(errStr)](auto self) { auto quicError = std::make_pair( QuicErrorCode(LocalErrorCode::CONNECT_FAILED), errString); auto clientPtr = static_cast(self.get()); clientPtr->closeImpl(std::move(quicError), false, false); }); } } #endif } void QuicClientTransport::onReadError( const folly::AsyncSocketException& ex) noexcept { if (closeState_ == CloseState::OPEN) { // closeNow will skip draining the socket. onReadError doesn't gets // triggered by retriable errors. If we are here, there is no point of // draining the socket. runOnEvbAsync([ex](auto self) { auto clientPtr = static_cast(self.get()); clientPtr->closeNow(std::make_pair( QuicErrorCode(LocalErrorCode::CONNECTION_ABANDONED), std::string(ex.what()))); }); } } void QuicClientTransport::getReadBuffer(void** buf, size_t* len) noexcept { DCHECK(conn_) << ""trying to receive packets without a connection""; auto readBufferSize = conn_->transportSettings.maxRecvPacketSize * numGROBuffers_; readBuffer_ = folly::IOBuf::create(readBufferSize); *buf = readBuffer_->writableData(); *len = readBufferSize; } void QuicClientTransport::onDataAvailable( const folly::SocketAddress& server, size_t len, bool truncated, OnDataAvailableParams params) noexcept { VLOG(10) << ""Got data from socket peer="" << server << "" len="" << len; auto packetReceiveTime = Clock::now(); Buf data = std::move(readBuffer_); if (params.gro <= 0) { if (truncated) { // This is an error, drop the packet. QUIC_STATS( statsCallback_, onPacketDropped, PacketDropReason::UDP_TRUNCATED); if (conn_->qLogger) { conn_->qLogger->addPacketDrop(len, kUdpTruncated); } if (conn_->loopDetectorCallback) { conn_->readDebugState.noReadReason = NoReadReason::TRUNCATED; conn_->loopDetectorCallback->onSuspiciousReadLoops( ++conn_->readDebugState.loopCount, conn_->readDebugState.noReadReason); } return; } data->append(len); trackDatagramReceived(len); NetworkData networkData(std::move(data), packetReceiveTime); onNetworkData(server, std::move(networkData)); } else { // if we receive a truncated packet // we still need to consider the prev valid ones // AsyncUDPSocket::handleRead() sets the len to be the // buffer size in case the data is truncated if (truncated) { auto delta = len % params.gro; len -= delta; QUIC_STATS( statsCallback_, onPacketDropped, PacketDropReason::UDP_TRUNCATED); if (conn_->qLogger) { conn_->qLogger->addPacketDrop(delta, kUdpTruncated); } } data->append(len); trackDatagramReceived(len); NetworkData networkData; networkData.receiveTimePoint = packetReceiveTime; networkData.packets.reserve((len + params.gro - 1) / params.gro); size_t remaining = len; size_t offset = 0; while (remaining) { if (static_cast(remaining) > params.gro) { auto tmp = data->cloneOne(); // start at offset tmp->trimStart(offset); // the actual len is len - offset now // leave params.gro bytes tmp->trimEnd(len - offset - params.gro); DCHECK_EQ(tmp->length(), params.gro); offset += params.gro; remaining -= params.gro; networkData.packets.emplace_back(std::move(tmp)); } else { // do not clone the last packet // start at offset, use all the remaining data data->trimStart(offset); DCHECK_EQ(data->length(), remaining); remaining = 0; networkData.packets.emplace_back(std::move(data)); } } onNetworkData(server, std::move(networkData)); } } bool QuicClientTransport::shouldOnlyNotify() { return conn_->transportSettings.shouldRecvBatch; } void QuicClientTransport::recvMsg( folly::AsyncUDPSocket& sock, uint64_t readBufferSize, int numPackets, NetworkData& networkData, folly::Optional& server, size_t& totalData) { for (int packetNum = 0; packetNum < numPackets; ++packetNum) { // We create 1 buffer per packet so that it is not shared, this enables // us to decrypt in place. If the fizz decrypt api could decrypt in-place // even if shared, then we could allocate one giant IOBuf here. Buf readBuffer = folly::IOBuf::create(readBufferSize); struct iovec vec {}; vec.iov_base = readBuffer->writableData(); vec.iov_len = readBufferSize; sockaddr* rawAddr{nullptr}; struct sockaddr_storage addrStorage {}; socklen_t addrLen{sizeof(addrStorage)}; if (!server) { rawAddr = reinterpret_cast(&addrStorage); rawAddr->sa_family = sock.address().getFamily(); } int flags = 0; folly::AsyncUDPSocket::ReadCallback::OnDataAvailableParams params; struct msghdr msg {}; msg.msg_name = rawAddr; msg.msg_namelen = size_t(addrLen); msg.msg_iov = &vec; msg.msg_iovlen = 1; #ifdef FOLLY_HAVE_MSG_ERRQUEUE bool useGRO = sock.getGRO() > 0; bool useTS = sock.getTimestamping() > 0; char control[folly::AsyncUDPSocket::ReadCallback::OnDataAvailableParams:: kCmsgSpace] = {}; if (useGRO || useTS) { msg.msg_control = control; msg.msg_controllen = sizeof(control); // we need to consider MSG_TRUNC too flags |= MSG_TRUNC; } #endif ssize_t ret = sock.recvmsg(&msg, flags); if (ret < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // If we got a retriable error, let us continue. if (conn_->loopDetectorCallback) { conn_->readDebugState.noReadReason = NoReadReason::RETRIABLE_ERROR; } break; } // If we got a non-retriable error, we might have received // a packet that we could process, however let's just quit early. sock.pauseRead(); if (conn_->loopDetectorCallback) { conn_->readDebugState.noReadReason = NoReadReason::NONRETRIABLE_ERROR; } return onReadError(folly::AsyncSocketException( folly::AsyncSocketException::INTERNAL_ERROR, ""::recvmsg() failed"", errno)); } else if (ret == 0) { break; } #ifdef FOLLY_HAVE_MSG_ERRQUEUE if (useGRO) { folly::AsyncUDPSocket::fromMsg(params, msg); // truncated if ((size_t)ret > readBufferSize) { ret = readBufferSize; if (params.gro > 0) { ret = ret - ret % params.gro; } } } #endif size_t bytesRead = size_t(ret); totalData += bytesRead; if (!server) { server = folly::SocketAddress(); server->setFromSockaddr(rawAddr, addrLen); } VLOG(10) << ""Got data from socket peer="" << *server << "" len="" << bytesRead; readBuffer->append(bytesRead); if (params.gro > 0) { size_t len = bytesRead; size_t remaining = len; size_t offset = 0; size_t totalNumPackets = networkData.packets.size() + ((len + params.gro - 1) / params.gro); networkData.packets.reserve(totalNumPackets); while (remaining) { if (static_cast(remaining) > params.gro) { auto tmp = readBuffer->cloneOne(); // start at offset tmp->trimStart(offset); // the actual len is len - offset now // leave gro bytes tmp->trimEnd(len - offset - params.gro); DCHECK_EQ(tmp->length(), params.gro); offset += params.gro; remaining -= params.gro; networkData.packets.emplace_back(std::move(tmp)); } else { // do not clone the last packet // start at offset, use all the remaining data readBuffer->trimStart(offset); DCHECK_EQ(readBuffer->length(), remaining); remaining = 0; networkData.packets.emplace_back(std::move(readBuffer)); } } } else { networkData.packets.emplace_back(std::move(readBuffer)); } trackDatagramReceived(bytesRead); } } void QuicClientTransport::recvMmsg( folly::AsyncUDPSocket& sock, uint64_t readBufferSize, int numPackets, NetworkData& networkData, folly::Optional& server, size_t& totalData) { const size_t addrLen = sizeof(struct sockaddr_storage); auto& msgs = recvmmsgStorage_.msgs; auto& addrs = recvmmsgStorage_.addrs; auto& readBuffers = recvmmsgStorage_.readBuffers; auto& iovecs = recvmmsgStorage_.iovecs; auto& freeBufs = recvmmsgStorage_.freeBufs; int flags = 0; #ifdef FOLLY_HAVE_MSG_ERRQUEUE bool useGRO = sock.getGRO() > 0; bool useTS = sock.getTimestamping() > 0; std::vector> controlVec(useGRO ? numPackets : 0); // we need to consider MSG_TRUNC too if (useGRO) { flags |= MSG_TRUNC; } #endif for (int i = 0; i < numPackets; ++i) { Buf readBuffer; if (freeBufs.empty()) { readBuffer = folly::IOBuf::create(readBufferSize); } else { readBuffer = std::move(freeBufs.back()); DCHECK(readBuffer != nullptr); freeBufs.pop_back(); } iovecs[i].iov_base = readBuffer->writableData(); iovecs[i].iov_len = readBufferSize; readBuffers[i] = std::move(readBuffer); auto* rawAddr = reinterpret_cast(&addrs[i]); rawAddr->sa_family = socket_->address().getFamily(); struct msghdr* msg = &msgs[i].msg_hdr; msg->msg_name = rawAddr; msg->msg_namelen = addrLen; msg->msg_iov = &iovecs[i]; msg->msg_iovlen = 1; #ifdef FOLLY_HAVE_MSG_ERRQUEUE if (useGRO || useTS) { ::memset(controlVec[i].data(), 0, controlVec[i].size()); msg->msg_control = controlVec[i].data(); msg->msg_controllen = controlVec[i].size(); } #endif } int numMsgsRecvd = sock.recvmmsg(msgs.data(), numPackets, flags, nullptr); if (numMsgsRecvd < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // Exit, socket will notify us again when socket is readable. if (conn_->loopDetectorCallback) { conn_->readDebugState.noReadReason = NoReadReason::RETRIABLE_ERROR; } return; } // If we got a non-retriable error, we might have received // a packet that we could process, however let's just quit early. sock.pauseRead(); if (conn_->loopDetectorCallback) { conn_->readDebugState.noReadReason = NoReadReason::NONRETRIABLE_ERROR; } return onReadError(folly::AsyncSocketException( folly::AsyncSocketException::INTERNAL_ERROR, ""::recvmmsg() failed"", errno)); } CHECK_LE(numMsgsRecvd, numPackets); // Need to save our position so we can recycle the unused buffers. int i; for (i = 0; i < numMsgsRecvd; ++i) { size_t bytesRead = msgs[i].msg_len; if (bytesRead == 0) { // Empty datagram, this is probably garbage matching our tuple, we should // ignore such datagrams. freeBufs.emplace_back(std::move(readBuffers[i])); continue; } folly::AsyncUDPSocket::ReadCallback::OnDataAvailableParams params; #ifdef FOLLY_HAVE_MSG_ERRQUEUE if (useGRO || useTS) { folly::AsyncUDPSocket::fromMsg(params, msgs[i].msg_hdr); // truncated if (bytesRead > readBufferSize) { bytesRead = readBufferSize; if (params.gro > 0) { bytesRead = bytesRead - bytesRead % params.gro; } } } #endif totalData += bytesRead; if (!server) { server = folly::SocketAddress(); auto* rawAddr = reinterpret_cast(&addrs[i]); server->setFromSockaddr(rawAddr, addrLen); } VLOG(10) << ""Got data from socket peer="" << *server << "" len="" << bytesRead; readBuffers[i]->append(bytesRead); if (params.gro > 0) { size_t len = bytesRead; size_t remaining = len; size_t offset = 0; size_t totalNumPackets = networkData.packets.size() + ((len + params.gro - 1) / params.gro); networkData.packets.reserve(totalNumPackets); while (remaining) { if (static_cast(remaining) > params.gro) { auto tmp = readBuffers[i]->cloneOne(); // start at offset tmp->trimStart(offset); // the actual len is len - offset now // leave gro bytes tmp->trimEnd(len - offset - params.gro); DCHECK_EQ(tmp->length(), params.gro); offset += params.gro; remaining -= params.gro; networkData.packets.emplace_back(std::move(tmp)); } else { // do not clone the last packet // start at offset, use all the remaining data readBuffers[i]->trimStart(offset); DCHECK_EQ(readBuffers[i]->length(), remaining); remaining = 0; networkData.packets.emplace_back(std::move(readBuffers[i])); } } } else { networkData.packets.emplace_back(std::move(readBuffers[i])); } trackDatagramReceived(bytesRead); } for (; i < numPackets; i++) { freeBufs.emplace_back(std::move(readBuffers[i])); DCHECK(freeBufs.back() != nullptr); } } void QuicClientTransport::onNotifyDataAvailable( folly::AsyncUDPSocket& sock) noexcept { DCHECK(conn_) << ""trying to receive packets without a connection""; auto readBufferSize = conn_->transportSettings.maxRecvPacketSize * numGROBuffers_; const int numPackets = conn_->transportSettings.maxRecvBatchSize; NetworkData networkData; networkData.packets.reserve(numPackets); size_t totalData = 0; folly::Optional server; if (conn_->transportSettings.shouldUseRecvmmsgForBatchRecv) { recvmmsgStorage_.resize(numPackets); recvMmsg(sock, readBufferSize, numPackets, networkData, server, totalData); } else { recvMsg(sock, readBufferSize, numPackets, networkData, server, totalData); } if (networkData.packets.empty()) { // recvMmsg and recvMsg might have already set the reason and counter if (conn_->loopDetectorCallback) { if (conn_->readDebugState.noReadReason == NoReadReason::READ_OK) { conn_->readDebugState.noReadReason = NoReadReason::EMPTY_DATA; } if (conn_->readDebugState.noReadReason != NoReadReason::READ_OK) { conn_->loopDetectorCallback->onSuspiciousReadLoops( ++conn_->readDebugState.loopCount, conn_->readDebugState.noReadReason); } } return; } DCHECK(server.has_value()); // TODO: we can get better receive time accuracy than this, with // SO_TIMESTAMP or SIOCGSTAMP. auto packetReceiveTime = Clock::now(); networkData.receiveTimePoint = packetReceiveTime; networkData.totalData = totalData; onNetworkData(*server, std::move(networkData)); } void QuicClientTransport:: happyEyeballsConnAttemptDelayTimeoutExpired() noexcept { // Declare 0-RTT data as lost so that they will be retransmitted over the // second socket. happyEyeballsStartSecondSocket(clientConn_->happyEyeballsState); // If this gets called from the write path then we haven't added the packets // to the outstanding packet list yet. runOnEvbAsync([&](auto) { markZeroRttPacketsLost(*conn_, markPacketLoss); }); } void QuicClientTransport::start(ConnectionCallback* cb) { startBase(cb, nullptr, nullptr); } void QuicClientTransport::start( ConnectionSetupCallback* connSetupCb, ConnectionCallbackNew* connCb) { startBase(nullptr, connSetupCb, connCb); } void QuicClientTransport::startBase( ConnectionCallback* cb, ConnectionSetupCallback* connSetupCb, ConnectionCallbackNew* connCb) { if (happyEyeballsEnabled_) { // TODO Supply v4 delay amount from somewhere when we want to tune this startHappyEyeballs( *clientConn_, evb_, happyEyeballsCachedFamily_, happyEyeballsConnAttemptDelayTimeout_, happyEyeballsCachedFamily_ == AF_UNSPEC ? kHappyEyeballsV4Delay : kHappyEyeballsConnAttemptDelayWithCache, this, this, socketOptions_); } CHECK(conn_->peerAddress.isInitialized()); if (conn_->qLogger) { conn_->qLogger->addTransportStateUpdate(kStart); } if (cb) { setConnectionCallback(cb); } else { setConnectionSetupCallback(connSetupCb); setConnectionCallbackNew(connCb); } clientConn_->pendingOneRttData.reserve( conn_->transportSettings.maxPacketsToBuffer); try { happyEyeballsSetUpSocket( *socket_, conn_->localAddress, conn_->peerAddress, conn_->transportSettings, this, this, socketOptions_); // adjust the GRO buffers adjustGROBuffers(); startCryptoHandshake(); } catch (const QuicTransportException& ex) { runOnEvbAsync([ex](auto self) { auto clientPtr = static_cast(self.get()); clientPtr->closeImpl(std::make_pair( QuicErrorCode(ex.errorCode()), std::string(ex.what()))); }); } catch (const QuicInternalException& ex) { runOnEvbAsync([ex](auto self) { auto clientPtr = static_cast(self.get()); clientPtr->closeImpl(std::make_pair( QuicErrorCode(ex.errorCode()), std::string(ex.what()))); }); } catch (const std::exception& ex) { LOG(ERROR) << ""Connect failed "" << ex.what(); runOnEvbAsync([ex](auto self) { auto clientPtr = static_cast(self.get()); clientPtr->closeImpl(std::make_pair( QuicErrorCode(TransportErrorCode::INTERNAL_ERROR), std::string(ex.what()))); }); } } void QuicClientTransport::addNewPeerAddress(folly::SocketAddress peerAddress) { CHECK(peerAddress.isInitialized()); if (happyEyeballsEnabled_) { conn_->udpSendPacketLen = std::min( conn_->udpSendPacketLen, (peerAddress.getFamily() == AF_INET6 ? kDefaultV6UDPSendPacketLen : kDefaultV4UDPSendPacketLen)); happyEyeballsAddPeerAddress(*clientConn_, peerAddress); return; } conn_->udpSendPacketLen = peerAddress.getFamily() == AF_INET6 ? kDefaultV6UDPSendPacketLen : kDefaultV4UDPSendPacketLen; conn_->originalPeerAddress = peerAddress; conn_->peerAddress = std::move(peerAddress); } void QuicClientTransport::setLocalAddress(folly::SocketAddress localAddress) { CHECK(localAddress.isInitialized()); conn_->localAddress = std::move(localAddress); } void QuicClientTransport::setHappyEyeballsEnabled(bool happyEyeballsEnabled) { happyEyeballsEnabled_ = happyEyeballsEnabled; } void QuicClientTransport::setHappyEyeballsCachedFamily( sa_family_t cachedFamily) { happyEyeballsCachedFamily_ = cachedFamily; } void QuicClientTransport::addNewSocket( std::unique_ptr socket) { happyEyeballsAddSocket(*clientConn_, std::move(socket)); } void QuicClientTransport::setHostname(const std::string& hostname) { hostname_ = hostname; } void QuicClientTransport::setSelfOwning() { selfOwning_ = shared_from_this(); } bool QuicClientTransport::setCustomTransportParameter( std::unique_ptr customParam) { // check that the parameter id is in the ""private parameter"" range, as // described by the spec. if (static_cast(customParam->getParameterId()) < kCustomTransportParameterThreshold) { LOG(ERROR) << ""invalid parameter id""; return false; } // check to see that we haven't already added in a parameter with the // specified parameter id auto it = std::find_if( customTransportParameters_.begin(), customTransportParameters_.end(), [&customParam](const TransportParameter& param) { return param.parameter == customParam->getParameterId(); }); // if a match has been found, we return failure if (it != customTransportParameters_.end()) { LOG(ERROR) << ""transport parameter already present""; return false; } customTransportParameters_.push_back(customParam->encode()); return true; } void QuicClientTransport::setD6DBasePMTUTransportParameter() { if (!conn_->transportSettings.d6dConfig.enabled) { return; } uint64_t basePMTUSetting = conn_->transportSettings.d6dConfig.advertisedBasePMTU; // Sanity check if (basePMTUSetting < kMinMaxUDPPayload || basePMTUSetting > kDefaultMaxUDPPayload) { LOG(ERROR) << ""insane base PMTU, skipping: "" << basePMTUSetting; return; } auto basePMTUCustomParam = std::make_unique( kD6DBasePMTUParameterId, basePMTUSetting); if (!setCustomTransportParameter(std::move(basePMTUCustomParam))) { LOG(ERROR) << ""failed to set D6D base PMTU transport parameter""; } } void QuicClientTransport::setD6DRaiseTimeoutTransportParameter() { if (!conn_->transportSettings.d6dConfig.enabled) { return; } std::chrono::seconds raiseTimeoutSetting = conn_->transportSettings.d6dConfig.advertisedRaiseTimeout; // Sanity check if (raiseTimeoutSetting < kMinD6DRaiseTimeout) { LOG(ERROR) << ""d6d raise timeout exceeding lower bound, skipping: "" << raiseTimeoutSetting.count(); } auto raiseTimeoutCustomParam = std::make_unique( kD6DRaiseTimeoutParameterId, raiseTimeoutSetting.count()); if (!setCustomTransportParameter(std::move(raiseTimeoutCustomParam))) { LOG(ERROR) << ""failed to set D6D raise timeout transport parameter""; } } void QuicClientTransport::setD6DProbeTimeoutTransportParameter() { if (!conn_->transportSettings.d6dConfig.enabled) { return; } std::chrono::seconds probeTimeoutSetting = conn_->transportSettings.d6dConfig.advertisedProbeTimeout; // Sanity check if (probeTimeoutSetting < kMinD6DProbeTimeout) { LOG(ERROR) << ""d6d probe timeout below lower bound, skipping: "" << probeTimeoutSetting.count(); } auto probeTimeoutCustomParam = std::make_unique( kD6DProbeTimeoutParameterId, probeTimeoutSetting.count()); if (!setCustomTransportParameter(std::move(probeTimeoutCustomParam))) { LOG(ERROR) << ""failed to set D6D probe timeout transport parameter""; } } void QuicClientTransport::setSupportedExtensionTransportParameters() { if (conn_->transportSettings.minAckDelay.hasValue()) { auto minAckDelayParam = std::make_unique( static_cast(TransportParameterId::min_ack_delay), conn_->transportSettings.minAckDelay.value().count()); customTransportParameters_.push_back(minAckDelayParam->encode()); } if (conn_->transportSettings.datagramConfig.enabled) { auto maxDatagramFrameSize = std::make_unique( static_cast( TransportParameterId::max_datagram_frame_size), conn_->datagramState.maxReadFrameSize); customTransportParameters_.push_back(maxDatagramFrameSize->encode()); } } void QuicClientTransport::adjustGROBuffers() { if (socket_ && conn_) { if (conn_->transportSettings.numGROBuffers_ > kDefaultNumGROBuffers) { socket_->setGRO(true); auto ret = socket_->getGRO(); if (ret > 0) { numGROBuffers_ = (conn_->transportSettings.numGROBuffers_ < kMaxNumGROBuffers) ? conn_->transportSettings.numGROBuffers_ : kMaxNumGROBuffers; } } } } void QuicClientTransport::closeTransport() { happyEyeballsConnAttemptDelayTimeout_.cancelTimeout(); } void QuicClientTransport::unbindConnection() { selfOwning_ = nullptr; } void QuicClientTransport::setSupportedVersions( const std::vector& versions) { auto version = versions.at(0); conn_->originalVersion = version; auto params = conn_->readCodec->getCodecParameters(); params.version = conn_->originalVersion.value(); conn_->readCodec->setCodecParameters(params); } void QuicClientTransport::onNetworkSwitch( std::unique_ptr newSock) { if (!conn_->oneRttWriteCipher) { return; } if (socket_ && newSock) { auto sock = std::move(socket_); socket_ = nullptr; sock->setErrMessageCallback(nullptr); sock->pauseRead(); sock->close(); socket_ = std::move(newSock); happyEyeballsSetUpSocket( *socket_, conn_->localAddress, conn_->peerAddress, conn_->transportSettings, this, this, socketOptions_); if (conn_->qLogger) { conn_->qLogger->addConnectionMigrationUpdate(true); } // adjust the GRO buffers adjustGROBuffers(); } } void QuicClientTransport::setTransportStatsCallback( std::shared_ptr statsCallback) noexcept { CHECK(conn_); statsCallback_ = std::move(statsCallback); if (statsCallback_) { conn_->statsCallback = statsCallback_.get(); } else { conn_->statsCallback = nullptr; } } void QuicClientTransport::trackDatagramReceived(size_t len) { if (conn_->qLogger) { conn_->qLogger->addDatagramReceived(len); } QUIC_STATS(statsCallback_, onPacketReceived); QUIC_STATS(statsCallback_, onRead, len); } void QuicClientTransport::maybeSendTransportKnobs() { if (!transportKnobsSent_ && hasWriteCipher()) { for (const auto& knob : conn_->transportSettings.knobs) { auto res = setKnob(knob.space, knob.id, folly::IOBuf::copyBuffer(knob.blob)); if (res.hasError()) { if (res.error() != LocalErrorCode::KNOB_FRAME_UNSUPPORTED) { LOG(ERROR) << ""Unexpected error while sending knob frames""; } // No point in keep trying if transport does not support knob frame break; } } transportKnobsSent_ = true; } } } // namespace quic ",16154,True,2754.703566356703,median "class ZCL_EXCEL_DRAWING definition public final create public . public section. *""* public components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! type-pools ABAP . constants C_GRAPH_PIE type ZEXCEL_GRAPH_TYPE value 1. ""#EC NOTEXT constants C_GRAPH_LINE type ZEXCEL_GRAPH_TYPE value 2. ""#EC NOTEXT constants C_GRAPH_BARS type ZEXCEL_GRAPH_TYPE value 0. ""#EC NOTEXT data GRAPH_TYPE type ZEXCEL_GRAPH_TYPE . data TITLE type STRING value 'image1.jpg'. ""#EC NOTEXT . . . . . . . . . . . . "" . data X_REFERENCES type CHAR1 . data Y_REFERENCES type CHAR1 . constants TYPE_IMAGE type ZEXCEL_DRAWING_TYPE value 'image'. ""#EC NOTEXT constants TYPE_CHART type ZEXCEL_DRAWING_TYPE value 'chart'. ""#EC NOTEXT constants ANCHOR_ABSOLUTE type ZEXCEL_DRAWING_ANCHOR value 'ABS'. ""#EC NOTEXT constants ANCHOR_ONE_CELL type ZEXCEL_DRAWING_ANCHOR value 'ONE'. ""#EC NOTEXT constants ANCHOR_TWO_CELL type ZEXCEL_DRAWING_ANCHOR value 'TWO'. ""#EC NOTEXT data GRAPH type ref to ZCL_EXCEL_GRAPH . constants C_MEDIA_TYPE_BMP type STRING value 'bmp'. ""#EC NOTEXT constants C_MEDIA_TYPE_XML type STRING value 'xml'. ""#EC NOTEXT constants C_MEDIA_TYPE_JPG type STRING value 'jpg'. ""#EC NOTEXT methods CONSTRUCTOR importing !IP_TYPE type ZEXCEL_DRAWING_TYPE default ZCL_EXCEL_DRAWING=>TYPE_IMAGE !IP_TITLE type CLIKE optional . methods CREATE_MEDIA_NAME importing !IP_INDEX type I . methods GET_FROM_COL returning value(R_FROM_COL) type ZEXCEL_CELL_COLUMN . methods GET_FROM_ROW returning value(R_FROM_ROW) type ZEXCEL_CELL_ROW . methods GET_GUID returning value(EP_GUID) type GUID_16 . methods GET_HEIGHT_EMU_STR returning value(R_HEIGHT) type STRING . methods GET_MEDIA returning value(R_MEDIA) type XSTRING . methods GET_MEDIA_NAME returning value(R_NAME) type STRING . methods GET_MEDIA_TYPE returning value(R_TYPE) type STRING . methods GET_NAME returning value(R_NAME) type STRING . methods GET_TO_COL returning value(R_TO_COL) type ZEXCEL_CELL_COLUMN . methods GET_TO_ROW returning value(R_TO_ROW) type ZEXCEL_CELL_ROW . methods GET_WIDTH_EMU_STR returning value(R_WIDTH) type STRING . class-methods PIXEL2EMU importing !IP_PIXEL type INT4 !IP_DPI type INT2 optional returning value(R_EMU) type STRING . class-methods EMU2PIXEL importing !IP_EMU type INT4 !IP_DPI type INT2 optional returning value(R_PIXEL) type INT4 . methods SET_MEDIA importing !IP_MEDIA type XSTRING optional !IP_MEDIA_TYPE type STRING !IP_WIDTH type INT4 default 0 !IP_HEIGHT type INT4 default 0 . methods SET_MEDIA_MIME importing !IP_IO type SKWF_IO !IP_WIDTH type INT4 !IP_HEIGHT type INT4 . methods SET_MEDIA_WWW importing !IP_KEY type WWWDATATAB !IP_WIDTH type INT4 !IP_HEIGHT type INT4 . methods SET_POSITION importing !IP_FROM_ROW type ZEXCEL_CELL_ROW !IP_FROM_COL type ZEXCEL_CELL_COLUMN_ALPHA !IP_ROWOFF type INT4 optional !IP_COLOFF type INT4 optional . methods SET_POSITION2 importing !IP_FROM type ZEXCEL_DRAWING_LOCATION !IP_TO type ZEXCEL_DRAWING_LOCATION !IP_ANCHOR type ZEXCEL_DRAWING_ANCHOR optional . methods GET_POSITION returning value(RP_POSITION) type ZEXCEL_DRAWING_POSITION . methods GET_TYPE returning value(RP_TYPE) type ZEXCEL_DRAWING_TYPE . methods GET_INDEX returning value(RP_INDEX) type STRING . methods LOAD_CHART_ATTRIBUTES importing value(IP_CHART) type ref to IF_IXML_DOCUMENT . *""* protected components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! *""* protected components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! protected section. private section. *""* private components of class ZCL_EXCEL_DRAWING *""* do not include other source files here!!! data TYPE type ZEXCEL_DRAWING_TYPE value TYPE_IMAGE. ""#EC NOTEXT . . . . . . . . . . . "" . data INDEX type STRING . data ANCHOR type ZEXCEL_DRAWING_ANCHOR value ANCHOR_ONE_CELL. ""#EC NOTEXT . . . . . . . . . . . "" . constants C_MEDIA_SOURCE_WWW type CHAR1 value 1. ""#EC NOTEXT constants C_MEDIA_SOURCE_XSTRING type CHAR1 value 0. ""#EC NOTEXT constants C_MEDIA_SOURCE_MIME type CHAR1 value 2. ""#EC NOTEXT data GUID type GUID_16 . data MEDIA type XSTRING . data MEDIA_KEY_WWW type WWWDATATAB . data MEDIA_NAME type STRING . data MEDIA_SOURCE type CHAR1 . data MEDIA_TYPE type STRING . data IO type SKWF_IO . data FROM_LOC type ZEXCEL_DRAWING_LOCATION . data TO_LOC type ZEXCEL_DRAWING_LOCATION . data SIZE type ZEXCEL_DRAWING_SIZE . ENDCLASS. CLASS ZCL_EXCEL_DRAWING IMPLEMENTATION. METHOD constructor. * CALL FUNCTION 'GUID_CREATE' "" del issue #379 - function is outdated in newer releases * IMPORTING * ev_guid_16 = me->guid. me->guid = zcl_excel_obsolete_func_wrap=>guid_create( ). "" ins issue #379 - replacement for outdated function call IF ip_title IS NOT INITIAL. title = ip_title. ELSE. title = me->guid. ENDIF. me->type = ip_type. * inizialize dimension range anchor = anchor_one_cell. from_loc-col = 1. from_loc-row = 1. ENDMETHOD. method CREATE_MEDIA_NAME. * if media name is initial, create unique name CHECK media_name IS INITIAL. index = ip_index. CONCATENATE me->type index INTO media_name. CONDENSE media_name NO-GAPS. endmethod. METHOD emu2pixel. * suppose 96 DPI IF ip_dpi IS SUPPLIED. * r_emu = ip_pixel * 914400 / ip_dpi. r_pixel = ip_emu * ip_dpi / 914400. ELSE. * suppose 96 DPI * r_emu = ip_pixel * 914400 / 96. r_pixel = ip_emu * 96 / 914400. ENDIF. ENDMETHOD. method GET_FROM_COL. r_from_col = me->from_loc-col. endmethod. method GET_FROM_ROW. r_from_row = me->from_loc-row. endmethod. method GET_GUID. ep_guid = me->guid. endmethod. method GET_HEIGHT_EMU_STR. r_height = pixel2emu( size-height ). CONDENSE r_height NO-GAPS. endmethod. method GET_INDEX. rp_index = me->index. endmethod. METHOD get_media. DATA: lv_language TYPE sylangu. DATA: lt_bin_mime TYPE sdokcntbins. DATA: lt_mime TYPE tsfmime, lv_filesize TYPE i, lv_filesizec(10). CASE media_source. WHEN c_media_source_xstring. r_media = media. WHEN c_media_source_www. CALL FUNCTION 'WWWDATA_IMPORT' EXPORTING key = media_key_www TABLES mime = lt_mime EXCEPTIONS OTHERS = 1. CALL FUNCTION 'WWWPARAMS_READ' EXPORTING relid = media_key_www-relid objid = media_key_www-objid name = 'filesize' IMPORTING value = lv_filesizec. lv_filesize = lv_filesizec. CALL FUNCTION 'SCMS_BINARY_TO_XSTRING' EXPORTING input_length = lv_filesize IMPORTING buffer = r_media TABLES binary_tab = lt_mime EXCEPTIONS failed = 1 OTHERS = 2. WHEN c_media_source_mime. lv_language = sy-langu. cl_wb_mime_repository=>load_mime( EXPORTING io = me->io IMPORTING filesize = lv_filesize bin_data = lt_bin_mime CHANGING language = lv_language ). CALL FUNCTION 'SCMS_BINARY_TO_XSTRING' EXPORTING input_length = lv_filesize IMPORTING buffer = r_media TABLES binary_tab = lt_bin_mime EXCEPTIONS failed = 1 OTHERS = 2. ENDCASE. ENDMETHOD. method GET_MEDIA_NAME. CONCATENATE media_name `.` media_type INTO r_name. endmethod. method GET_MEDIA_TYPE. r_type = media_type. endmethod. method GET_NAME. r_name = title. endmethod. method GET_POSITION. rp_position-anchor = anchor. rp_position-from = from_loc. rp_position-to = to_loc. rp_position-size = size. endmethod. method GET_TO_COL. r_to_col = me->to_loc-col. endmethod. method GET_TO_ROW. r_to_row = me->to_loc-row. endmethod. method GET_TYPE. rp_type = me->type. endmethod. method GET_WIDTH_EMU_STR. r_width = pixel2emu( size-width ). CONDENSE r_width NO-GAPS. endmethod. method LOAD_CHART_ATTRIBUTES. DATA: node TYPE REF TO if_ixml_element. DATA: node2 TYPE REF TO if_ixml_element. DATA: node3 TYPE REF TO if_ixml_element. DATA: node4 TYPE REF TO if_ixml_element. DATA lo_barchart TYPE REF TO zcl_excel_graph_bars. DATA lo_piechart TYPE REF TO zcl_excel_graph_pie. DATA lo_linechart TYPE REF TO zcl_excel_graph_line. TYPES: BEGIN OF t_prop, val TYPE string, rtl TYPE string, lang TYPE string, formatcode TYPE string, sourcelinked TYPE string, END OF t_prop. TYPES: BEGIN OF t_pagemargins, b TYPE string, l TYPE string, r TYPE string, t TYPE string, header TYPE string, footer TYPE string, END OF t_pagemargins. DATA ls_prop TYPE t_prop. DATA ls_pagemargins TYPE t_pagemargins. DATA lo_collection TYPE REF TO if_ixml_node_collection. DATA lo_node TYPE REF TO if_ixml_node. DATA lo_iterator TYPE REF TO if_ixml_node_iterator. DATA lv_idx TYPE i. DATA lv_order TYPE i. DATA lv_invertifnegative TYPE string. DATA lv_symbol TYPE string. DATA lv_smooth TYPE c. DATA lv_sername TYPE string. DATA lv_label TYPE string. DATA lv_value TYPE string. DATA lv_axid TYPE string. DATA lv_orientation TYPE string. DATA lv_delete TYPE string. DATA lv_axpos TYPE string. DATA lv_formatcode TYPE string. DATA lv_sourcelinked TYPE string. DATA lv_majortickmark TYPE string. DATA lv_minortickmark TYPE string. DATA lv_ticklblpos TYPE string. DATA lv_crossax TYPE string. DATA lv_crosses TYPE string. DATA lv_auto TYPE string. DATA lv_lblalgn TYPE string. DATA lv_lbloffset TYPE string. DATA lv_nomultilvllbl TYPE string. DATA lv_crossbetween TYPE string. node ?= ip_chart->if_ixml_node~get_first_child( ). CHECK node IS NOT INITIAL. CASE me->graph_type. WHEN c_graph_bars. CREATE OBJECT lo_barchart. me->graph = lo_barchart. WHEN c_graph_pie. CREATE OBJECT lo_piechart. me->graph = lo_piechart. WHEN c_graph_line. CREATE OBJECT lo_linechart. me->graph = lo_linechart. WHEN OTHERS. ENDCASE. ""Fill properties node2 ?= node->find_from_name( name = 'date1904' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_1904val = ls_prop-val. node2 ?= node->find_from_name( name = 'lang' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_langval = ls_prop-val. node2 ?= node->find_from_name( name = 'roundedCorners' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_roundedcornersval = ls_prop-val. ""style node2 ?= node->find_from_name( name = 'style' namespace = 'c14' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_c14styleval = ls_prop-val. node2 ?= node->find_from_name( name = 'style' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_styleval = ls_prop-val. ""---------------------------Read graph properties node2 ?= node->find_from_name( name = 'autoTitleDeleted' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_autotitledeletedval = ls_prop-val. ""plotArea CASE me->graph_type. WHEN c_graph_bars. node2 ?= node->find_from_name( name = 'barDir' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_bardirval = ls_prop-val. node2 ?= node->find_from_name( name = 'grouping' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_groupingval = ls_prop-val. node2 ?= node->find_from_name( name = 'varyColors' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_varycolorsval = ls_prop-val. ""Load series CALL METHOD node->get_elements_by_tag_name EXPORTING * depth = 0 name = 'ser' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. node3 ?= node2->find_from_name( name = 'idx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_idx = ls_prop-val. node3 ?= node2->find_from_name( name = 'order' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_order = ls_prop-val. node3 ?= node2->find_from_name( name = 'invertIfNegative' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_invertifnegative = ls_prop-val. node3 ?= node2->find_from_name( name = 'v' namespace = 'c' ). IF node3 IS BOUND. lv_sername = node3->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'strRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_label = node4->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'numRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_value = node4->get_value( ). ENDIF. CALL METHOD lo_barchart->create_serie EXPORTING ip_idx = lv_idx ip_order = lv_order ip_invertifnegative = lv_invertifnegative ip_lbl = lv_label ip_ref = lv_value ip_sername = lv_sername. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. ""note: numCache avoided node2 ?= node->find_from_name( name = 'showLegendKey' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showlegendkeyval = ls_prop-val. node2 ?= node->find_from_name( name = 'showVal' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showvalval = ls_prop-val. node2 ?= node->find_from_name( name = 'showCatName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showcatnameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showSerName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showsernameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showPercent' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showpercentval = ls_prop-val. node2 ?= node->find_from_name( name = 'showBubbleSize' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_showbubblesizeval = ls_prop-val. node2 ?= node->find_from_name( name = 'gapWidth' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_gapwidthval = ls_prop-val. ""Load axes node2 ?= node->find_from_name( name = 'barChart' namespace = 'c' ). CALL METHOD node2->get_elements_by_tag_name EXPORTING * depth = 0 name = 'axId' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lv_axid = ls_prop-val. IF sy-index EQ 1. ""catAx node2 ?= node->find_from_name( name = 'catAx' namespace = 'c' ). node3 ?= node2->find_from_name( name = 'orientation' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_orientation = ls_prop-val. node3 ?= node2->find_from_name( name = 'delete' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_delete = ls_prop-val. node3 ?= node2->find_from_name( name = 'axPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_axpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'numFmt' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_formatcode = ls_prop-formatcode. lv_sourcelinked = ls_prop-sourcelinked. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_majortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_minortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'tickLblPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_ticklblpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossAx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossax = ls_prop-val. node3 ?= node2->find_from_name( name = 'crosses' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crosses = ls_prop-val. node3 ?= node2->find_from_name( name = 'auto' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_auto = ls_prop-val. node3 ?= node2->find_from_name( name = 'lblAlgn' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_lblalgn = ls_prop-val. node3 ?= node2->find_from_name( name = 'lblOffset' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_lbloffset = ls_prop-val. node3 ?= node2->find_from_name( name = 'noMultiLvlLbl' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_nomultilvllbl = ls_prop-val. CALL METHOD lo_barchart->create_ax EXPORTING ip_axid = lv_axid ip_type = zcl_excel_graph_bars=>c_catax ip_orientation = lv_orientation ip_delete = lv_delete ip_axpos = lv_axpos ip_formatcode = lv_formatcode ip_sourcelinked = lv_sourcelinked ip_majortickmark = lv_majortickmark ip_minortickmark = lv_minortickmark ip_ticklblpos = lv_ticklblpos ip_crossax = lv_crossax ip_crosses = lv_crosses ip_auto = lv_auto ip_lblalgn = lv_lblalgn ip_lbloffset = lv_lbloffset ip_nomultilvllbl = lv_nomultilvllbl. ELSEIF sy-index EQ 2. ""valAx node2 ?= node->find_from_name( name = 'valAx' namespace = 'c' ). node3 ?= node2->find_from_name( name = 'orientation' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_orientation = ls_prop-val. node3 ?= node2->find_from_name( name = 'delete' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_delete = ls_prop-val. node3 ?= node2->find_from_name( name = 'axPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_axpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'numFmt' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_formatcode = ls_prop-formatcode. lv_sourcelinked = ls_prop-sourcelinked. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_majortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_minortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'tickLblPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_ticklblpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossAx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossax = ls_prop-val. node3 ?= node2->find_from_name( name = 'crosses' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crosses = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossBetween' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossbetween = ls_prop-val. CALL METHOD lo_barchart->create_ax EXPORTING ip_axid = lv_axid ip_type = zcl_excel_graph_bars=>c_valax ip_orientation = lv_orientation ip_delete = lv_delete ip_axpos = lv_axpos ip_formatcode = lv_formatcode ip_sourcelinked = lv_sourcelinked ip_majortickmark = lv_majortickmark ip_minortickmark = lv_minortickmark ip_ticklblpos = lv_ticklblpos ip_crossax = lv_crossax ip_crosses = lv_crosses ip_crossbetween = lv_crossbetween. ENDIF. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. WHEN c_graph_pie. node2 ?= node->find_from_name( name = 'varyColors' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_varycolorsval = ls_prop-val. ""Load series CALL METHOD node->get_elements_by_tag_name EXPORTING * depth = 0 name = 'ser' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. node3 ?= node2->find_from_name( name = 'idx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_idx = ls_prop-val. node3 ?= node2->find_from_name( name = 'order' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_order = ls_prop-val. node3 ?= node2->find_from_name( name = 'v' namespace = 'c' ). IF node3 IS BOUND. lv_sername = node3->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'strRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_label = node4->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'numRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_value = node4->get_value( ). ENDIF. CALL METHOD lo_piechart->create_serie EXPORTING ip_idx = lv_idx ip_order = lv_order ip_lbl = lv_label ip_ref = lv_value ip_sername = lv_sername. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. ""note: numCache avoided node2 ?= node->find_from_name( name = 'showLegendKey' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showlegendkeyval = ls_prop-val. node2 ?= node->find_from_name( name = 'showVal' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showvalval = ls_prop-val. node2 ?= node->find_from_name( name = 'showCatName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showcatnameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showSerName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showsernameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showPercent' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showpercentval = ls_prop-val. node2 ?= node->find_from_name( name = 'showBubbleSize' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showbubblesizeval = ls_prop-val. node2 ?= node->find_from_name( name = 'showLeaderLines' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_showleaderlinesval = ls_prop-val. node2 ?= node->find_from_name( name = 'firstSliceAng' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_firstsliceangval = ls_prop-val. WHEN c_graph_line. node2 ?= node->find_from_name( name = 'grouping' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_groupingval = ls_prop-val. node2 ?= node->find_from_name( name = 'varyColors' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_varycolorsval = ls_prop-val. ""Load series CALL METHOD node->get_elements_by_tag_name EXPORTING * depth = 0 name = 'ser' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. node3 ?= node2->find_from_name( name = 'idx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_idx = ls_prop-val. node3 ?= node2->find_from_name( name = 'order' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_order = ls_prop-val. node3 ?= node2->find_from_name( name = 'symbol' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_symbol = ls_prop-val. node3 ?= node2->find_from_name( name = 'smooth' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_smooth = ls_prop-val. node3 ?= node2->find_from_name( name = 'v' namespace = 'c' ). IF node3 IS BOUND. lv_sername = node3->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'strRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_label = node4->get_value( ). ENDIF. node3 ?= node2->find_from_name( name = 'numRef' namespace = 'c' ). IF node3 IS BOUND. node4 ?= node3->find_from_name( name = 'f' namespace = 'c' ). lv_value = node4->get_value( ). ENDIF. CALL METHOD lo_linechart->create_serie EXPORTING ip_idx = lv_idx ip_order = lv_order ip_symbol = lv_symbol ip_smooth = lv_smooth ip_lbl = lv_label ip_ref = lv_value ip_sername = lv_sername. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. ""note: numCache avoided node2 ?= node->find_from_name( name = 'showLegendKey' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showlegendkeyval = ls_prop-val. node2 ?= node->find_from_name( name = 'showVal' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showvalval = ls_prop-val. node2 ?= node->find_from_name( name = 'showCatName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showcatnameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showSerName' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showsernameval = ls_prop-val. node2 ?= node->find_from_name( name = 'showPercent' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showpercentval = ls_prop-val. node2 ?= node->find_from_name( name = 'showBubbleSize' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_showbubblesizeval = ls_prop-val. node ?= node->find_from_name( name = 'lineChart' namespace = 'c' ). node2 ?= node->find_from_name( name = 'marker' namespace = 'c' DEPTH = '1' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->NS_MARKERVAL = ls_prop-val. node2 ?= node->find_from_name( name = 'smooth' namespace = 'c' DEPTH = '1' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->NS_SMOOTHVAL = ls_prop-val. node ?= ip_chart->if_ixml_node~get_first_child( ). CHECK node IS NOT INITIAL. ""Load axes node2 ?= node->find_from_name( name = 'lineChart' namespace = 'c' ). CALL METHOD node2->get_elements_by_tag_name EXPORTING * depth = 0 name = 'axId' * namespace = '' RECEIVING rval = lo_collection. CALL METHOD lo_collection->create_iterator RECEIVING rval = lo_iterator. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. WHILE lo_node IS BOUND. zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lv_axid = ls_prop-val. IF sy-index EQ 1. ""catAx node2 ?= node->find_from_name( name = 'catAx' namespace = 'c' ). node3 ?= node2->find_from_name( name = 'orientation' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_orientation = ls_prop-val. node3 ?= node2->find_from_name( name = 'delete' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_delete = ls_prop-val. node3 ?= node2->find_from_name( name = 'axPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_axpos = ls_prop-val. * node3 ?= node2->find_from_name( name = 'numFmt' namespace = 'c' ). * zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). * lv_formatcode = ls_prop-formatcode. * lv_sourcelinked = ls_prop-sourcelinked. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_majortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_minortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'tickLblPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_ticklblpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossAx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossax = ls_prop-val. node3 ?= node2->find_from_name( name = 'crosses' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crosses = ls_prop-val. node3 ?= node2->find_from_name( name = 'auto' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_auto = ls_prop-val. node3 ?= node2->find_from_name( name = 'lblAlgn' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_lblalgn = ls_prop-val. node3 ?= node2->find_from_name( name = 'lblOffset' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_lbloffset = ls_prop-val. node3 ?= node2->find_from_name( name = 'noMultiLvlLbl' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_nomultilvllbl = ls_prop-val. CALL METHOD lo_linechart->create_ax EXPORTING ip_axid = lv_axid ip_type = zcl_excel_graph_line=>c_catax ip_orientation = lv_orientation ip_delete = lv_delete ip_axpos = lv_axpos ip_formatcode = lv_formatcode ip_sourcelinked = lv_sourcelinked ip_majortickmark = lv_majortickmark ip_minortickmark = lv_minortickmark ip_ticklblpos = lv_ticklblpos ip_crossax = lv_crossax ip_crosses = lv_crosses ip_auto = lv_auto ip_lblalgn = lv_lblalgn ip_lbloffset = lv_lbloffset ip_nomultilvllbl = lv_nomultilvllbl. ELSEIF sy-index EQ 2. ""valAx node2 ?= node->find_from_name( name = 'valAx' namespace = 'c' ). node3 ?= node2->find_from_name( name = 'orientation' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_orientation = ls_prop-val. node3 ?= node2->find_from_name( name = 'delete' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_delete = ls_prop-val. node3 ?= node2->find_from_name( name = 'axPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_axpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'numFmt' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_formatcode = ls_prop-formatcode. lv_sourcelinked = ls_prop-sourcelinked. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_majortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'majorTickMark' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_minortickmark = ls_prop-val. node3 ?= node2->find_from_name( name = 'tickLblPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_ticklblpos = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossAx' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossax = ls_prop-val. node3 ?= node2->find_from_name( name = 'crosses' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crosses = ls_prop-val. node3 ?= node2->find_from_name( name = 'crossBetween' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node3 CHANGING cp_structure = ls_prop ). lv_crossbetween = ls_prop-val. CALL METHOD lo_linechart->create_ax EXPORTING ip_axid = lv_axid ip_type = zcl_excel_graph_line=>c_valax ip_orientation = lv_orientation ip_delete = lv_delete ip_axpos = lv_axpos ip_formatcode = lv_formatcode ip_sourcelinked = lv_sourcelinked ip_majortickmark = lv_majortickmark ip_minortickmark = lv_minortickmark ip_ticklblpos = lv_ticklblpos ip_crossax = lv_crossax ip_crosses = lv_crosses ip_crossbetween = lv_crossbetween. ENDIF. lo_node = lo_iterator->get_next( ). IF lo_node IS BOUND. node2 ?= lo_node->query_interface( ixml_iid_element ). ENDIF. ENDWHILE. WHEN OTHERS. ENDCASE. ""legend CASE me->graph_type. WHEN c_graph_bars. node2 ?= node->find_from_name( name = 'legendPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_legendposval = ls_prop-val. node2 ?= node->find_from_name( name = 'overlay' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_barchart->ns_overlayval = ls_prop-val. WHEN c_graph_line. node2 ?= node->find_from_name( name = 'legendPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_legendposval = ls_prop-val. node2 ?= node->find_from_name( name = 'overlay' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_linechart->ns_overlayval = ls_prop-val. WHEN c_graph_pie. node2 ?= node->find_from_name( name = 'legendPos' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_legendposval = ls_prop-val. node2 ?= node->find_from_name( name = 'overlay' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_overlayval = ls_prop-val. node2 ?= node->find_from_name( name = 'pPr' namespace = 'a' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_pprrtl = ls_prop-rtl. node2 ?= node->find_from_name( name = 'endParaRPr' namespace = 'a' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). lo_piechart->ns_endpararprlang = ls_prop-lang. WHEN OTHERS. ENDCASE. node2 ?= node->find_from_name( name = 'plotVisOnly' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_plotvisonlyval = ls_prop-val. node2 ?= node->find_from_name( name = 'dispBlanksAs' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_dispblanksasval = ls_prop-val. node2 ?= node->find_from_name( name = 'showDLblsOverMax' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_prop ). me->graph->ns_showdlblsovermaxval = ls_prop-val. ""--------------------- node2 ?= node->find_from_name( name = 'pageMargins' namespace = 'c' ). zcl_excel_reader_2007=>fill_struct_from_attributes( EXPORTING ip_element = node2 CHANGING cp_structure = ls_pagemargins ). me->graph->pagemargins = ls_pagemargins. endmethod. method PIXEL2EMU. * suppose 96 DPI IF ip_dpi IS SUPPLIED. r_emu = ip_pixel * 914400 / ip_dpi. ELSE. * suppose 96 DPI r_emu = ip_pixel * 914400 / 96. ENDIF. endmethod. method SET_MEDIA. IF ip_media IS SUPPLIED. media = ip_media. ENDIF. media_type = ip_media_type. media_source = c_media_source_xstring. IF ip_width IS SUPPLIED. size-width = ip_width. ENDIF. IF ip_height IS SUPPLIED. size-height = ip_height. ENDIF. endmethod. METHOD set_media_mime. DATA: lv_language TYPE sylangu. io = ip_io. media_source = c_media_source_mime. size-width = ip_width. size-height = ip_height. lv_language = sy-langu. cl_wb_mime_repository=>load_mime( EXPORTING io = ip_io IMPORTING filename = media_name ""mimetype = media_type CHANGING language = lv_language ). SPLIT media_name AT '.' INTO media_name media_type. ENDMETHOD. method SET_MEDIA_WWW. DATA: lv_value(20). media_key_www = ip_key. media_source = c_media_source_www. CALL FUNCTION 'WWWPARAMS_READ' EXPORTING relid = media_key_www-relid objid = media_key_www-objid name = 'fileextension' IMPORTING value = lv_value. media_type = lv_value. SHIFT media_type LEFT DELETING LEADING '.'. size-width = ip_width. size-height = ip_height. endmethod. method SET_POSITION. from_loc-col = zcl_excel_common=>convert_column2int( ip_from_col ) - 1. IF ip_coloff IS SUPPLIED. from_loc-col_offset = ip_coloff. ENDIF. from_loc-row = ip_from_row - 1. IF ip_rowoff IS SUPPLIED. from_loc-row_offset = ip_rowoff. ENDIF. anchor = anchor_one_cell. endmethod. method SET_POSITION2. data: lv_anchor type zexcel_drawing_anchor. lv_anchor = ip_anchor. IF lv_anchor IS INITIAL. IF ip_to IS NOT INITIAL. lv_anchor = anchor_two_cell. ELSE. lv_anchor = anchor_one_cell. ENDIF. ENDIF. CASE lv_anchor. WHEN anchor_absolute OR anchor_one_cell. CLEAR: me->to_loc. WHEN anchor_two_cell. CLEAR: me->size. ENDCASE. me->from_loc = ip_from. me->to_loc = ip_to. me->anchor = lv_anchor. endmethod. ENDCLASS. ",13370,True,3677.5398425062217,median "[[features.external-config]] == Externalized Configuration Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, and command-line arguments. Property values can be injected directly into your beans by using the `@Value` annotation, accessed through Spring's `Environment` abstraction, or be <> through `@ConfigurationProperties`. Spring Boot uses a very particular `PropertySource` order that is designed to allow sensible overriding of values. Properties are considered in the following order (with values from lower items overriding earlier ones): . Default properties (specified by setting `SpringApplication.setDefaultProperties`). . {spring-framework-api}/context/annotation/PropertySource.html[`@PropertySource`] annotations on your `@Configuration` classes. Please note that such property sources are not added to the `Environment` until the application context is being refreshed. This is too late to configure certain properties such as `+logging.*+` and `+spring.main.*+` which are read before refresh begins. . Config data (such as `application.properties` files). . A `RandomValuePropertySource` that has properties only in `+random.*+`. . OS environment variables. . Java System properties (`System.getProperties()`). . JNDI attributes from `java:comp/env`. . `ServletContext` init parameters. . `ServletConfig` init parameters. . Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment variable or system property). . Command line arguments. . `properties` attribute on your tests. Available on {spring-boot-test-module-api}/context/SpringBootTest.html[`@SpringBootTest`] and the <>. . {spring-framework-api}/test/context/TestPropertySource.html[`@TestPropertySource`] annotations on your tests. . <> in the `$HOME/.config/spring-boot` directory when devtools is active. Config data files are considered in the following order: . <> packaged inside your jar (`application.properties` and YAML variants). . <> packaged inside your jar (`application-\\{profile}.properties` and YAML variants). . <> outside of your packaged jar (`application.properties` and YAML variants). . <> outside of your packaged jar (`application-\\{profile}.properties` and YAML variants). NOTE: It is recommended to stick with one format for your entire application. If you have configuration files with both `.properties` and `.yml` format in the same location, `.properties` takes precedence. To provide a concrete example, suppose you develop a `@Component` that uses a `name` property, as shown in the following example: include::code:MyBean[] On your application classpath (for example, inside your jar) you can have an `application.properties` file that provides a sensible default property value for `name`. When running in a new environment, an `application.properties` file can be provided outside of your jar that overrides the `name`. For one-off testing, you can launch with a specific command line switch (for example, `java -jar app.jar --name=""Spring""`). TIP: The `env` and `configprops` endpoints can be useful in determining why a property has a particular value. You can use these two endpoints to diagnose unexpected property values. See the ""<>"" section for details. [[features.external-config.command-line-args]] === Accessing Command Line Properties By default, `SpringApplication` converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring `Environment`. As mentioned previously, command line properties always take precedence over file-based property sources. If you do not want command line properties to be added to the `Environment`, you can disable them by using `SpringApplication.setAddCommandLineProperties(false)`. [[features.external-config.application-json]] === JSON Application Properties Environment variables and system properties often have restrictions that mean some property names cannot be used. To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure. When your application starts, any `spring.application.json` or `SPRING_APPLICATION_JSON` properties will be parsed and added to the `Environment`. For example, the `SPRING_APPLICATION_JSON` property can be supplied on the command line in a UN{asterisk}X shell as an environment variable: [source,shell,indent=0,subs=""verbatim""] ---- $ SPRING_APPLICATION_JSON='{""my"":{""name"":""test""}}' java -jar myapp.jar ---- In the preceding example, you end up with `my.name=test` in the Spring `Environment`. The same JSON can also be provided as a system property: [source,shell,indent=0,subs=""verbatim""] ---- $ java -Dspring.application.json='{""my"":{""name"":""test""}}' -jar myapp.jar ---- Or you could supply the JSON by using a command line argument: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myapp.jar --spring.application.json='{""my"":{""name"":""test""}}' ---- If you are deploying to a classic Application Server, you could also use a JNDI variable named `java:comp/env/spring.application.json`. NOTE: Although `null` values from the JSON will be added to the resulting property source, the `PropertySourcesPropertyResolver` treats `null` properties as missing values. This means that the JSON cannot override properties from lower order property sources with a `null` value. [[features.external-config.files]] === External Application Properties [[features.external-config.files]] Spring Boot will automatically find and load `application.properties` and `application.yaml` files from the following locations when your application starts: . From the classpath .. The classpath root .. The classpath `/config` package . From the current directory .. The current directory .. The `/config` subdirectory in the current directory .. Immediate child directories of the `/config` subdirectory The list is ordered by precedence (with values from lower items overriding earlier ones). Documents from the loaded files are added as `PropertySources` to the Spring `Environment`. If you do not like `application` as the configuration file name, you can switch to another file name by specifying a configprop:spring.config.name[] environment property. For example, to look for `myproject.properties` and `myproject.yaml` files you can run your application as follows: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.name=myproject ---- You can also refer to an explicit location by using the configprop:spring.config.location[] environment property. This properties accepts a comma-separated list of one or more locations to check. The following example shows how to specify two distinct files: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.location=\\ optional:classpath:/default.properties,\\ optional:classpath:/override.properties ---- TIP: Use the prefix `optional:` if the <> and you do not mind if they do not exist. WARNING: `spring.config.name`, `spring.config.location`, and `spring.config.additional-location` are used very early to determine which files have to be loaded. They must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument). If `spring.config.location` contains directories (as opposed to files), they should end in `/`. At runtime they will be appended with the names generated from `spring.config.name` before being loaded. Files specified in `spring.config.location` are imported directly. NOTE: Both directory and file location values are also expanded to check for <>. For example, if you have a `spring.config.location` of `classpath:myconfig.properties`, you will also find appropriate `classpath:myconfig-.properties` files are loaded. In most situations, each configprop:spring.config.location[] item you add will reference a single file or directory. Locations are processed in the order that they are defined and later ones can override the values of earlier ones. [[features.external-config.files.location-groups]] If you have a complex location setup, and you use profile-specific configuration files, you may need to provide further hints so that Spring Boot knows how they should be grouped. A location group is a collection of locations that are all considered at the same level. For example, you might want to group all classpath locations, then all external locations. Items within a location group should be separated with `;`. See the example in the ""`<>`"" section for more details. Locations configured by using `spring.config.location` replace the default locations. For example, if `spring.config.location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:custom-config/` . `optional:file:./custom-config/` If you prefer to add additional locations, rather than replacing them, you can use `spring.config.additional-location`. Properties loaded from additional locations can override those in the default locations. For example, if `spring.config.additional-location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:/;optional:classpath:/config/` . `optional:file:./;optional:file:./config/;optional:file:./config/*/` . `optional:classpath:custom-config/` . `optional:file:./custom-config/` This search ordering lets you specify default values in one configuration file and then selectively override those values in another. You can provide default values for your application in `application.properties` (or whatever other basename you choose with `spring.config.name`) in one of the default locations. These default values can then be overridden at runtime with a different file located in one of the custom locations. NOTE: If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (for example, configprop:spring.config.name[format=envvar] instead of configprop:spring.config.name[]). See <> for details. NOTE: If your application runs in a servlet container or application server, then JNDI properties (in `java:comp/env`) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties. [[features.external-config.files.optional-prefix]] ==== Optional Locations By default, when a specified config data location does not exist, Spring Boot will throw a `ConfigDataLocationNotFoundException` and your application will not start. If you want to specify a location, but you do not mind if it does not always exist, you can use the `optional:` prefix. You can use this prefix with the `spring.config.location` and `spring.config.additional-location` properties, as well as with <> declarations. For example, a `spring.config.import` value of `optional:file:./myconfig.properties` allows your application to start, even if the `myconfig.properties` file is missing. If you want to ignore all `ConfigDataLocationNotFoundExceptions` and always continue to start your application, you can use the `spring.config.on-not-found` property. Set the value to `ignore` using `SpringApplication.setDefaultProperties(...)` or with a system/environment variable. [[features.external-config.files.wildcard-locations]] ==== Wildcard Locations If a config file location includes the `{asterisk}` character for the last path segment, it is considered a wildcard location. Wildcards are expanded when the config is loaded so that immediate subdirectories are also checked. Wildcard locations are particularly useful in an environment such as Kubernetes when there are multiple sources of config properties. For example, if you have some Redis configuration and some MySQL configuration, you might want to keep those two pieces of configuration separate, while requiring that both those are present in an `application.properties` file. This might result in two separate `application.properties` files mounted at different locations such as `/config/redis/application.properties` and `/config/mysql/application.properties`. In such a case, having a wildcard location of `config/*/`, will result in both files being processed. By default, Spring Boot includes `config/*/` in the default search locations. It means that all subdirectories of the `/config` directory outside of your jar will be searched. You can use wildcard locations yourself with the `spring.config.location` and `spring.config.additional-location` properties. NOTE: A wildcard location must contain only one `{asterisk}` and end with `{asterisk}/` for search locations that are directories or `*/` for search locations that are files. Locations with wildcards are sorted alphabetically based on the absolute path of the file names. TIP: Wildcard locations only work with external directories. You cannot use a wildcard in a `classpath:` location. [[features.external-config.files.profile-specific]] ==== Profile Specific Files As well as `application` property files, Spring Boot will also attempt to load profile-specific files using the naming convention `application-\\{profile}`. For example, if your application activates a profile named `prod` and uses YAML files, then both `application.yml` and `application-prod.yml` will be considered. Profile-specific properties are loaded from the same locations as standard `application.properties`, with profile-specific files always overriding the non-specific ones. If several profiles are specified, a last-wins strategy applies. For example, if profiles `prod,live` are specified by the configprop:spring.profiles.active[] property, values in `application-prod.properties` can be overridden by those in `application-live.properties`. [NOTE] ==== The last-wins strategy applies at the <> level. A configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` will not have the same override rules as `classpath:/cfg/;classpath:/ext/`. For example, continuing our `prod,live` example above, we might have the following files: ---- /cfg application-live.properties /ext application-live.properties application-prod.properties ---- When we have a configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` we process all `/cfg` files before all `/ext` files: . `/cfg/application-live.properties` . `/ext/application-prod.properties` . `/ext/application-live.properties` When we have `classpath:/cfg/;classpath:/ext/` instead (with a `;` delimiter) we process `/cfg` and `/ext` at the same level: . `/ext/application-prod.properties` . `/cfg/application-live.properties` . `/ext/application-live.properties` ==== The `Environment` has a set of default profiles (by default, `[default]`) that are used if no active profiles are set. In other words, if no profiles are explicitly activated, then properties from `application-default` are considered. NOTE: Properties files are only ever loaded once. If you have already directly <> a profile specific property files then it will not be imported a second time. [[features.external-config.files.importing]] ==== Importing Additional Data Application properties may import further config data from other locations using the `spring.config.import` property. Imports are processed as they are discovered, and are treated as additional documents inserted immediately below the one that declares the import. For example, you might have the following in your classpath `application.properties` file: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: application: name: ""myapp"" config: import: ""optional:file:./dev.properties"" ---- This will trigger the import of a `dev.properties` file in current directory (if such a file exists). Values from the imported `dev.properties` will take precedence over the file that triggered the import. In the above example, the `dev.properties` could redefine `spring.application.name` to a different value. An import will only be imported once no matter how many times it is declared. The order an import is defined inside a single document within the properties/yaml file does not matter. For instance, the two examples below produce the same result: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: config: import: ""my.properties"" my: property: ""value"" ---- [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: property: ""value"" spring: config: import: ""my.properties"" ---- In both of the above examples, the values from the `my.properties` file will take precedence over the file that triggered its import. Several locations can be specified under a single `spring.config.import` key. Locations will be processed in the order that they are defined, with later imports taking precedence. NOTE: When appropriate, <> are also considered for import. The example above would import both `my.properties` as well as any `my-.properties` variants. [TIP] ==== Spring Boot includes pluggable API that allows various different location addresses to be supported. By default you can import Java Properties, YAML and ""`<>`"". Third-party jars can offer support for additional technologies (there is no requirement for files to be local). For example, you can imagine config data being from external stores such as Consul, Apache ZooKeeper or Netflix Archaius. If you want to support your own locations, see the `ConfigDataLocationResolver` and `ConfigDataLoader` classes in the `org.springframework.boot.context.config` package. ==== [[features.external-config.files.importing-extensionless]] ==== Importing Extensionless Files Some cloud platforms cannot add a file extension to volume mounted files. To import these extensionless files, you need to give Spring Boot a hint so that it knows how to load them. You can do this by putting an extension hint in square brackets. For example, suppose you have a `/etc/config/myconfig` file that you wish to import as yaml. You can import it from your `application.properties` using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""file:/etc/config/myconfig[.yaml]"" ---- [[features.external-config.files.configtree]] ==== Using Configuration Trees When running applications on a cloud platform (such as Kubernetes) you often need to read config values that the platform supplies. It is not uncommon to use environment variables for such purposes, but this can have drawbacks, especially if the value is supposed to be kept secret. As an alternative to environment variables, many cloud platforms now allow you to map configuration into mounted data volumes. For example, Kubernetes can volume mount both https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#populate-a-volume-with-data-stored-in-a-configmap[`ConfigMaps`] and https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod[`Secrets`]. There are two common volume mount patterns that can be used: . A single file contains a complete set of properties (usually written as YAML). . Multiple files are written to a directory tree, with the filename becoming the '`key`' and the contents becoming the '`value`'. For the first case, you can import the YAML or Properties file directly using `spring.config.import` as described <>. For the second case, you need to use the `configtree:` prefix so that Spring Boot knows it needs to expose all the files as properties. As an example, let's imagine that Kubernetes has mounted the following volume: [indent=0] ---- etc/ config/ myapp/ username password ---- The contents of the `username` file would be a config value, and the contents of `password` would be a secret. To import these properties, you can add the following to your `application.properties` or `application.yaml` file: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/"" ---- You can then access or inject `myapp.username` and `myapp.password` properties from the `Environment` in the usual way. TIP: The folders under the config tree form the property name. In the above example, to access the properties as `username` and `password`, you can set `spring.config.import` to `optional:configtree:/etc/config/myapp`. NOTE: Filenames with dot notation are also correctly mapped. For example, in the above example, a file named `myapp.username` in `/etc/config` would result in a `myapp.username` property in the `Environment`. TIP: Configuration tree values can be bound to both string `String` and `byte[]` types depending on the contents expected. If you have multiple config trees to import from the same parent folder you can use a wildcard shortcut. Any `configtree:` location that ends with `/*/` will import all immediate children as config trees. For example, given the following volume: [indent=0] ---- etc/ config/ dbconfig/ db/ username password mqconfig/ mq/ username password ---- You can use `configtree:/etc/config/*/` as the import location: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/*/"" ---- This will add `db.username`, `db.password`, `mq.username` and `mq.password` properties. NOTE: Directories loaded using a wildcard are sorted alphabetically. If you need a different order, then you should list each location as a separate import Configuration trees can also be used for Docker secrets. When a Docker swarm service is granted access to a secret, the secret gets mounted into the container. For example, if a secret named `db.password` is mounted at location `/run/secrets/`, you can make `db.password` available to the Spring environment using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/run/secrets/"" ---- [[features.external-config.files.property-placeholders]] ==== Property Placeholders The values in `application.properties` and `application.yml` are filtered through the existing `Environment` when they are used, so you can refer back to previously defined values (for example, from System properties). The standard `$\\{name}` property-placeholder syntax can be used anywhere within a value. For example, the following file will set `app.description` to ""`MyApp is a Spring Boot application`"": [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- app: name: ""MyApp"" description: ""${app.name} is a Spring Boot application"" ---- TIP: You can also use this technique to create ""`short`"" variants of existing Spring Boot properties. See the _<>_ how-to for details. [[features.external-config.files.multi-document]] ==== Working with Multi-Document Files Spring Boot allows you to split a single physical file into multiple logical documents which are each added independently. Documents are processed in order, from top to bottom. Later documents can override the properties defined in earlier ones. For `application.yml` files, the standard YAML multi-document syntax is used. Three consecutive hyphens represent the end of one document, and the start of the next. For example, the following file has two logical documents: [source,yaml,indent=0,subs=""verbatim""] ---- spring: application: name: ""MyApp"" --- spring: application: name: ""MyCloudApp"" config: activate: on-cloud-platform: ""kubernetes"" ---- For `application.properties` files a special `#---` comment is used to mark the document splits: [source,properties,indent=0,subs=""verbatim""] ---- spring.application.name=MyApp #--- spring.application.name=MyCloudApp spring.config.activate.on-cloud-platform=kubernetes ---- NOTE: Property file separators must not have any leading whitespace and must have exactly three hyphen characters. The lines immediately before and after the separator must not be comments. TIP: Multi-document property files are often used in conjunction with activation properties such as `spring.config.activate.on-profile`. See the <> for details. WARNING: Multi-document property files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. [[features.external-config.files.activation-properties]] ==== Activation Properties It is sometimes useful to only activate a given set of properties when certain conditions are met. For example, you might have properties that are only relevant when a specific profile is active. You can conditionally activate a properties document using `spring.config.activate.*`. The following activation properties are available: .activation properties [cols=""1,4""] |=== | Property | Note | `on-profile` | A profile expression that must match for the document to be active. | `on-cloud-platform` | The `CloudPlatform` that must be detected for the document to be active. |=== For example, the following specifies that the second document is only active when running on Kubernetes, and only when either the ""`prod`"" or ""`staging`"" profiles are active: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- myprop: ""always-set"" --- spring: config: activate: on-cloud-platform: ""kubernetes"" on-profile: ""prod | staging"" myotherprop: ""sometimes-set"" ---- [[features.external-config.encrypting]] === Encrypting Properties Spring Boot does not provide any built in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring `Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the `Environment` before the application starts. See <> for details. If you need a secure way to store credentials and passwords, the https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides support for storing externalized configuration in https://www.vaultproject.io/[HashiCorp Vault]. [[features.external-config.yaml]] === Working with YAML https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The `SpringApplication` class automatically supports YAML as an alternative to properties whenever you have the https://bitbucket.org/asomov/snakeyaml[SnakeYAML] library on your classpath. NOTE: If you use ""`Starters`"", SnakeYAML is automatically provided by `spring-boot-starter`. [[features.external-config.yaml.mapping-to-properties]] ==== Mapping YAML to Properties YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring `Environment`. For example, consider the following YAML document: [source,yaml,indent=0,subs=""verbatim""] ---- environments: dev: url: ""https://dev.example.com"" name: ""Developer Setup"" prod: url: ""https://another.example.com"" name: ""My Cool App"" ---- In order to access these properties from the `Environment`, they would be flattened as follows: [source,properties,indent=0,subs=""verbatim""] ---- environments.dev.url=https://dev.example.com environments.dev.name=Developer Setup environments.prod.url=https://another.example.com environments.prod.name=My Cool App ---- Likewise, YAML lists also need to be flattened. They are represented as property keys with `[index]` dereferencers. For example, consider the following YAML: [source,yaml,indent=0,subs=""verbatim""] ---- my: servers: - ""dev.example.com"" - ""another.example.com"" ---- The preceding example would be transformed into these properties: [source,properties,indent=0,subs=""verbatim""] ---- my.servers[0]=dev.example.com my.servers[1]=another.example.com ---- TIP: Properties that use the `[index]` notation can be bound to Java `List` or `Set` objects using Spring Boot's `Binder` class. For more details see the ""`<>`"" section below. WARNING: YAML files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. So, in the case that you need to load values that way, you need to use a properties file. [[features.external-config.yaml.directly-loading]] [[features.external-config.yaml.directly-loading]] ==== Directly Loading YAML Spring Framework provides two convenient classes that can be used to load YAML documents. The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` loads YAML as a `Map`. You can also use the `YamlPropertySourceLoader` class if you want to load YAML as a Spring `PropertySource`. [[features.external-config.random-values]] === Configuring Random Values The `RandomValuePropertySource` is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: secret: ""${random.value}"" number: ""${random.int}"" bignumber: ""${random.long}"" uuid: ""${random.uuid}"" number-less-than-ten: ""${random.int(10)}"" number-in-range: ""${random.int[1024,65536]}"" ---- The `+random.int*+` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any character and `value,max` are integers. If `max` is provided, then `value` is the minimum value and `max` is the maximum value (exclusive). [[features.external-config.system-environment]] === Configuring System Environment Properties Spring Boot supports setting a prefix for environment properties. This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements. The prefix for system environment properties can be set directly on `SpringApplication`. For example, if you set the prefix to `input`, a property such as `remote.timeout` will also be resolved as `input.remote.timeout` in the system environment. [[features.external-config.typesafe-configuration-properties]] === Type-safe Configuration Properties Using the `@Value(""$\\{property}"")` annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application. TIP: See also the <>. [[features.external-config.typesafe-configuration-properties.java-bean-binding]] ==== JavaBean properties binding It is possible to bind a bean declaring standard JavaBean properties as shown in the following example: include::code:MyProperties[] The preceding POJO defines the following properties: * `my.service.enabled`, with a value of `false` by default. * `my.service.remote-address`, with a type that can be coerced from `String`. * `my.service.security.username`, with a nested ""security"" object whose name is determined by the name of the property. In particular, the type is not used at all there and could have been `SecurityProperties`. * `my.service.security.password`. * `my.service.security.roles`, with a collection of `String` that defaults to `USER`. NOTE: The properties that map to `@ConfigurationProperties` classes available in Spring Boot, which are configured through properties files, YAML files, environment variables, and other mechanisms, are public API but the accessors (getters/setters) of the class itself are not meant to be used directly. [NOTE] ==== Such arrangement relies on a default empty constructor and getters and setters are usually mandatory, since binding is through standard Java Beans property descriptors, just like in Spring MVC. A setter may be omitted in the following cases: * Maps, as long as they are initialized, need a getter but not necessarily a setter, since they can be mutated by the binder. * Collections and arrays can be accessed either through an index (typically with YAML) or by using a single comma-separated value (properties). In the latter case, a setter is mandatory. We recommend to always add a setter for such types. If you initialize a collection, make sure it is not immutable (as in the preceding example). * If nested POJO properties are initialized (like the `Security` field in the preceding example), a setter is not required. If you want the binder to create the instance on the fly by using its default constructor, you need a setter. Some people use Project Lombok to add getters and setters automatically. Make sure that Lombok does not generate any particular constructor for such a type, as it is used automatically by the container to instantiate the object. Finally, only standard Java Bean properties are considered and binding on static properties is not supported. ==== [[features.external-config.typesafe-configuration-properties.constructor-binding]] ==== Constructor binding The example in the previous section can be rewritten in an immutable fashion as shown in the following example: include::code:MyProperties[] In this setup, the presence of a single parameterized constructor implies that constructor binding should be used. This means that the binder will find a constructor with the parameters that you wish to have bound. If your class has multiple constructors, the `@ConstructorBinding` annotation can be used to specify which constructor to use for constructor binding. To opt out of constructor binding for a class with a single parameterized constructor, the constructor must be annotated with `@Autowired`. If you are using Java 16 or later, constructor binding can be used with records. Unless your record has multiple constructors, there is no need to use `@ConstructorBinding`. Nested members of a constructor bound class (such as `Security` in the example above) will also be bound through their constructor. Default values can be specified using `@DefaultValue` and the same conversion service will be applied to coerce the `String` value to the target type of a missing property. By default, if no properties are bound to `Security`, the `MyProperties` instance will contain a `null` value for `security`. If you wish you return a non-null instance of `Security` even when no properties are bound to it, you can use an empty `@DefaultValue` annotation to do so: include::code:nonnull/MyProperties[tag=*] NOTE: To use constructor binding the class must be enabled using `@EnableConfigurationProperties` or configuration property scanning. You cannot use constructor binding with beans that are created by the regular Spring mechanisms (for example `@Component` beans, beans created by using `@Bean` methods or beans loaded by using `@Import`) NOTE: The use of `java.util.Optional` with `@ConfigurationProperties` is not recommended as it is primarily intended for use as a return type. As such, it is not well-suited to configuration property injection. For consistency with properties of other types, if you do declare an `Optional` property and it has no value, `null` rather than an empty `Optional` will be bound. [[features.external-config.typesafe-configuration-properties.enabling-annotated-types]] ==== Enabling @ConfigurationProperties-annotated types Spring Boot provides infrastructure to bind `@ConfigurationProperties` types and register them as beans. You can either enable configuration properties on a class-by-class basis or enable configuration property scanning that works in a similar manner to component scanning. Sometimes, classes annotated with `@ConfigurationProperties` might not be suitable for scanning, for example, if you're developing your own auto-configuration or you want to enable them conditionally. In these cases, specify the list of types to process using the `@EnableConfigurationProperties` annotation. This can be done on any `@Configuration` class, as shown in the following example: include::code:MyConfiguration[] To use configuration property scanning, add the `@ConfigurationPropertiesScan` annotation to your application. Typically, it is added to the main application class that is annotated with `@SpringBootApplication` but it can be added to any `@Configuration` class. By default, scanning will occur from the package of the class that declares the annotation. If you want to define specific packages to scan, you can do so as shown in the following example: include::code:MyApplication[] [NOTE] ==== When the `@ConfigurationProperties` bean is registered using configuration property scanning or through `@EnableConfigurationProperties`, the bean has a conventional name: `-`, where `` is the environment key prefix specified in the `@ConfigurationProperties` annotation and `` is the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used. The bean name in the example above is `com.example.app-com.example.app.SomeProperties`. ==== We recommend that `@ConfigurationProperties` only deal with the environment and, in particular, does not inject other beans from the context. For corner cases, setter injection can be used or any of the `*Aware` interfaces provided by the framework (such as `EnvironmentAware` if you need access to the `Environment`). If you still want to inject other beans using the constructor, the configuration properties bean must be annotated with `@Component` and use JavaBean-based property binding. [[features.external-config.typesafe-configuration-properties.using-annotated-types]] ==== Using @ConfigurationProperties-annotated types This style of configuration works particularly well with the `SpringApplication` external YAML configuration, as shown in the following example: [source,yaml,indent=0,subs=""verbatim""] ---- my: service: remote-address: 192.168.1.1 security: username: ""admin"" roles: - ""USER"" - ""ADMIN"" ---- To work with `@ConfigurationProperties` beans, you can inject them in the same way as any other bean, as shown in the following example: include::code:MyService[] TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys. See the <> for details. [[features.external-config.typesafe-configuration-properties.third-party-configuration]] ==== Third-party Configuration As well as using `@ConfigurationProperties` to annotate a class, you can also use it on public `@Bean` methods. Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control. To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to its bean registration, as shown in the following example: include::code:ThirdPartyConfiguration[] Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example. [[features.external-config.typesafe-configuration-properties.relaxed-binding]] ==== Relaxed Binding Spring Boot uses some relaxed rules for binding `Environment` properties to `@ConfigurationProperties` beans, so there does not need to be an exact match between the `Environment` property name and the bean property name. Common examples where this is useful include dash-separated environment properties (for example, `context-path` binds to `contextPath`), and capitalized environment properties (for example, `PORT` binds to `port`). As an example, consider the following `@ConfigurationProperties` class: include::code:MyPersonProperties[] With the preceding code, the following properties names can all be used: .relaxed binding [cols=""1,4""] |=== | Property | Note | `my.main-project.person.first-name` | Kebab case, which is recommended for use in `.properties` and `.yml` files. | `my.main-project.person.firstName` | Standard camel case syntax. | `my.main-project.person.first_name` | Underscore notation, which is an alternative format for use in `.properties` and `.yml` files. | `MY_MAINPROJECT_PERSON_FIRSTNAME` | Upper case format, which is recommended when using system environment variables. |=== NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase and separated by `-`, such as `my.main-project.person`). .relaxed binding rules per property source [cols=""2,4,4""] |=== | Property Source | Simple | List | Properties Files | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values | YAML Files | Camel case, kebab case, or underscore notation | Standard YAML list syntax or comma-separated values | Environment Variables | Upper case format with underscore as the delimiter (see <>). | Numeric values surrounded by underscores (see <>) | System properties | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values |=== TIP: We recommend that, when possible, properties are stored in lower-case kebab format, such as `my.person.first-name=Rod`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.maps]] ===== Binding Maps When binding to `Map` properties you may need to use a special bracket notation so that the original `key` value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric, `-` or `.` are removed. For example, consider binding the following properties to a `Map`: [source,properties,indent=0,subs=""verbatim"",role=""primary""] .Properties ---- my.map.[/key1]=value1 my.map.[/key2]=value2 my.map./key3=value3 ---- [source,yaml,indent=0,subs=""verbatim"",role=""secondary""] .Yaml ---- my: map: ""[/key1]"": ""value1"" ""[/key2]"": ""value2"" ""/key3"": ""value3"" ---- NOTE: For YAML files, the brackets need to be surrounded by quotes for the keys to be parsed properly. The properties above will bind to a `Map` with `/key1`, `/key2` and `key3` as the keys in the map. The slash has been removed from `key3` because it was not surrounded by square brackets. You may also occasionally need to use the bracket notation if your `key` contains a `.` and you are binding to non-scalar value. For example, binding `a.b=c` to `Map` will return a Map with the entry `{""a""={""b""=""c""}}` whereas `[a.b]=c` will return a Map with the entry `{""a.b""=""c""}`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables]] ===== Binding from Environment Variables Most operating systems impose strict rules around the names that can be used for environment variables. For example, Linux shell variables can contain only letters (`a` to `z` or `A` to `Z`), numbers (`0` to `9`) or the underscore character (`_`). By convention, Unix shell variables will also have their names in UPPERCASE. Spring Boot's relaxed binding rules are, as much as possible, designed to be compatible with these naming restrictions. To convert a property name in the canonical-form to an environment variable name you can follow these rules: * Replace dots (`.`) with underscores (`_`). * Remove any dashes (`-`). * Convert to uppercase. For example, the configuration property `spring.main.log-startup-info` would be an environment variable named `SPRING_MAIN_LOGSTARTUPINFO`. Environment variables can also be used when binding to object lists. To bind to a `List`, the element number should be surrounded with underscores in the variable name. For example, the configuration property `my.service[0].other` would use an environment variable named `MY_SERVICE_0_OTHER`. [[features.external-config.typesafe-configuration-properties.merging-complex-types]] ==== Merging Complex Types When lists are configured in more than one place, overriding works by replacing the entire list. For example, assume a `MyPojo` object with `name` and `description` attributes that are `null` by default. The following example exposes a list of `MyPojo` objects from `MyProperties`: include::code:list/MyProperties[] Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- If the `dev` profile is not active, `MyProperties.list` contains one `MyPojo` entry, as previously defined. If the `dev` profile is enabled, however, the `list` _still_ contains only one entry (with a name of `my another name` and a description of `null`). This configuration _does not_ add a second `MyPojo` instance to the list, and it does not merge the items. When a `List` is specified in multiple profiles, the one with the highest priority (and only that one) is used. Consider the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" - name: ""another name"" description: ""another description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- In the preceding example, if the `dev` profile is active, `MyProperties.list` contains _one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). For YAML, both comma-separated lists and YAML lists can be used for completely overriding the contents of the list. For `Map` properties, you can bind with property values drawn from multiple sources. However, for the same property in multiple sources, the one with the highest priority is used. The following example exposes a `Map` from `MyProperties`: include::code:map/MyProperties[] Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: map: key1: name: ""my name 1"" description: ""my description 1"" --- spring: config: activate: on-profile: ""dev"" my: map: key1: name: ""dev name 1"" key2: name: ""dev name 2"" description: ""dev description 2"" ---- If the `dev` profile is not active, `MyProperties.map` contains one entry with key `key1` (with a name of `my name 1` and a description of `my description 1`). If the `dev` profile is enabled, however, `map` contains two entries with keys `key1` (with a name of `dev name 1` and a description of `my description 1`) and `key2` (with a name of `dev name 2` and a description of `dev description 2`). NOTE: The preceding merging rules apply to properties from all property sources, and not just files. [[features.external-config.typesafe-configuration-properties.conversion]] ==== Properties Conversion Spring Boot attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with bean definitions annotated as `@ConfigurationPropertiesBinding`). NOTE: As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your `ConversionService` is using. Typically, any dependency that you require may not be fully initialized at creation time. You may want to rename your custom `ConversionService` if it is not required for configuration keys coercion and only rely on custom converters qualified with `@ConfigurationPropertiesBinding`. [[features.external-config.typesafe-configuration-properties.conversion.durations]] ===== Converting Durations Spring Boot has dedicated support for expressing durations. If you expose a `java.time.Duration` property, the following formats in application properties are available: * A regular `long` representation (using milliseconds as the default unit unless a `@DurationUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Duration.html#parse-java.lang.CharSequence-[used by `java.time.Duration`] * A more readable format where the value and the unit are coupled (`10s` means 10 seconds) Consider the following example: include::code:javabeanbinding/MyProperties[] To specify a session timeout of 30 seconds, `30`, `PT30S` and `30s` are all equivalent. A read timeout of 500ms can be specified in any of the following form: `500`, `PT0.5S` and `500ms`. You can also use any of the supported units. These are: * `ns` for nanoseconds * `us` for microseconds * `ms` for milliseconds * `s` for seconds * `m` for minutes * `h` for hours * `d` for days The default unit is milliseconds and can be overridden using `@DurationUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it is not milliseconds. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.conversion.periods]] ===== Converting periods In addition to durations, Spring Boot can also work with `java.time.Period` type. The following formats can be used in application properties: * An regular `int` representation (using days as the default unit unless a `@PeriodUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Period.html#parse-java.lang.CharSequence-[used by `java.time.Period`] * A simpler format where the value and the unit pairs are coupled (`1y3d` means 1 year and 3 days) The following units are supported with the simple format: * `y` for years * `m` for months * `w` for weeks * `d` for days NOTE: The `java.time.Period` type never actually stores the number of weeks, it is a shortcut that means ""`7 days`"". [[features.external-config.typesafe-configuration-properties.conversion.data-sizes]] ===== Converting Data Sizes Spring Framework has a `DataSize` value type that expresses a size in bytes. If you expose a `DataSize` property, the following formats in application properties are available: * A regular `long` representation (using bytes as the default unit unless a `@DataSizeUnit` has been specified) * A more readable format where the value and the unit are coupled (`10MB` means 10 megabytes) Consider the following example: include::code:javabeanbinding/MyProperties[] To specify a buffer size of 10 megabytes, `10` and `10MB` are equivalent. A size threshold of 256 bytes can be specified as `256` or `256B`. You can also use any of the supported units. These are: * `B` for bytes * `KB` for kilobytes * `MB` for megabytes * `GB` for gigabytes * `TB` for terabytes The default unit is bytes and can be overridden using `@DataSizeUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.validation]] ==== @ConfigurationProperties Validation Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are annotated with Spring's `@Validated` annotation. You can use JSR-303 `javax.validation` constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example: include::code:MyProperties[] TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@Validated`. To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`. The following example builds on the preceding `MyProperties` example: include::code:nested/MyProperties[] You can also add a custom Spring `Validator` by creating a bean definition called `configurationPropertiesValidator`. The `@Bean` method should be declared `static`. The configuration properties validator is created very early in the application's lifecycle, and declaring the `@Bean` method as static lets the bean be created without having to instantiate the `@Configuration` class. Doing so avoids any problems that may be caused by early instantiation. TIP: The `spring-boot-actuator` module includes an endpoint that exposes all `@ConfigurationProperties` beans. Point your web browser to `/actuator/configprops` or use the equivalent JMX endpoint. See the ""<>"" section for details. [[features.external-config.typesafe-configuration-properties.vs-value-annotation]] ==== @ConfigurationProperties vs. @Value The `@Value` annotation is a core container feature, and it does not provide the same features as type-safe configuration properties. The following table summarizes the features that are supported by `@ConfigurationProperties` and `@Value`: [cols=""4,2,2""] |=== | Feature |`@ConfigurationProperties` |`@Value` | <> | Yes | Limited (see <>) | <> | Yes | No | `SpEL` evaluation | No | Yes |=== [[features.external-config.typesafe-configuration-properties.vs-value-annotation.note]] NOTE: If you do want to use `@Value`, we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters). This will allow Spring Boot to use the same logic as it does when relaxed binding `@ConfigurationProperties`. For example, `@Value(""{demo.item-price}"")` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment. If you used `@Value(""{demo.itemPrice}"")` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered. If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with `@ConfigurationProperties`. Doing so will provide you with structured, type-safe object that you can inject into your own beans. `SpEL` expressions from <> are not processed at time of parsing these files and populating the environment. However, it is possible to write a `SpEL` expression in `@Value`. If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed through `@Value`. ",12282,False,2134.419457305194,median " == Requirements Class ""Core"" The following section describes the core requirements class. === Overview include::../requirements/requirements_class_core.adoc[] A server that implements the OGC API - Processes Standard provides access to processes. Each implementation of the OGC API - Processes Standard has a single `LandingPage` (path `/`) that provides links to * The `APIDefinition` (no fixed path), * The `Conformance` statements (path `/conformance`), * The `processes` metadata (path `/processes`). Note that additional requirements classes may introduce additional links for the landing page. The `APIDefinition` describes the capabilities of the server that can be used by clients to connect to the server or by development tools to support the implementation of servers and clients. Accessing the `APIDefinition` using HTTP GET returns a description of the API. Accessing `Conformance` using HTTP GET returns a list of URIs of requirements classes implemented by the server. The list of processes contains a summary of each process offered by the OGC API - Processes implementation, including the link to a more detailed description of the process. The <> contains information about inputs and outputs and a link to the execution-endpoint for the process. A HTTP POST request to the execution-endpoint creates a new job. The inputs and outputs need to be passed in a JSON execute-request. The URL for accessing status information is delivered in the HTTP header `location`. After a process is finished (status = success/failed), the results/exceptions can be retrieved. [[img_core]] .Resources in the Core requirements class image::figures/PT1_FIG01.png[align=""center""] The OGC API - Processes Standard utilizes elements of the OGC API-Common standard. <> Identifies the API-Common Requirements Classes which are applicable to each section of this standard. [[mapping-to-common]] .Mapping API - Processes Sections to API-Common Requirements Classes [cols=""2,6""] |=== ^|*API - Processes Section* ^|*API-Common Requirements Class* |<>| http://www.opengis.net/spec/ogcapi-common-1/1.0/req/core |<>| http://www.opengis.net/spec/ogcapi-common-1/1.0/req/core |<>| http://www.opengis.net/spec/ogcapi-common-1/1.0/req/core |<>| http://www.opengis.net/spec/ogcapi-common-1/1.0/req/oas30 |<>| http://www.opengis.net/spec/ogcapi-common-1/1.0/req/html |=== [[sc_landing_page]] === Retrieve the API landing page The following section defines the requirements to retrieve an API landing page. ==== Operation include::../requirements/core/REQ_landingpage-op.adoc[] ==== Response include::../requirements/core/REQ_landingpage-success.adoc[] [NOTE] ==== The term “_...based upon the OpenAPI 3.0 schema..._” used in the requirements of this specification means that OpenAPI 3.0 is used to define: * all the required properties of the respective request/response schema, * and any optional properties of the respective request/response schema. It also means that unless explicitly excluded these schemas are extensible with additional properties not defined in the schema using the https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md#schemaObject[`additionalProperties`] mechanism defined in the https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.0.md[OpenAPI 3.0 specification]. ==== .Schema for the landing page [source,yaml] ---- include::../openapi/schemas/landingPage.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/landingPage.yaml[`landingPage.yaml`]. [[link-schema]] .Schema for a link [source,yaml] ---- include::../openapi/schemas/link.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/link.yaml[`link.yaml`]. .Landing page response document ==== [source,json] ---- include::../examples/json/LandingPage.json[] ---- ==== ==== Error situations See <> for general guidance. [[sc_api_definition]] === Retrieve an API definition The following section defines the requirements to retrieve an API definition. ==== Operation Every implementation of OGC API - Processes provides an API definition that describes the capabilities of the server. This definition is used by developers to understand the API, by software clients to connect to the server, or by development tools to support the implementation of servers and clients. include::../requirements/core/REQ_api-definition-op.adoc[] include::../recommendations/core/PER_api-definition-uri.adoc[] Note that multiple API definition formats can be supported. ==== Response include::../requirements/core/REQ_api-definition-success.adoc[] include::../recommendations/core/REC_api-definition-oas.adoc[] If multiple API definition formats are supported by a server, use content negotiation to select the desired representation. [NOTE] ==== Two common approaches are: * an additional path for each encoding of each resource (this can be expressed, for example, using format specific suffixes like "".html""); * an additional query parameter (for example, ""accept"" or ""f"") that overrides the Accept header of the HTTP request. ==== The API definition document describes the API. In other words, there is no need to include the `/api` operation in the API definition itself. The idea is that any implementation of OGC API - Processes can be used by developers that are familiar with the API definition language(s) supported by the server. For example, if an OpenAPI definition is used, it should be possible to create a working client using the OpenAPI definition. The developer may need to learn a little bit about geospatial data types, etc., but it should not be required to read this standard to access the processes and results via the API. ==== Error situations See <> for general guidance. [[sc_conformance_classes]] === Declaration of conformance classes ==== Operation To support ""generic"" clients for accessing servers implementing OGC API - Processes in general - and not ""just"" a specific API / server, the server has to declare the requirements classes it implements and conforms to. include::../requirements/core/REQ_conformance-op.adoc[] ==== Response include::../requirements/core/REQ_conformance-success.adoc[] .Schema for the list of requirements classes [source,yaml] ---- include::../openapi/schemas/confClasses.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/schemas/req-classes.yaml[`req-classes.yaml`]. .Requirements class response document ==== This example response in JSON is for a server that supports OpenAPI 3.0 for the API definition and HTML and JSON as encodings. [source,json] ---- include::../examples/json/ConfClasses.json[] ---- ==== ==== Error situations See <> for general guidance. === Use of HTTP 1.1 include::../requirements/core/REQ_http.adoc[] This include the correct use of status codes, headers. etc. include::../recommendations/core/REC_http-head.adoc[] Supporting the method HEAD in addition to GET can be useful for clients and is simple to implement. In particular, the HEAD method is useful in determine the size of a potential response. include::../recommendations/core/REC_content-length.adoc[] Servers implementing https://docs.ogc.org/DRAFTS/17-069r4.html#cross_origin[CORS] will implement the method OPTIONS, too. [[http_status_codes]] ==== HTTP status codes <> lists the main HTTP status codes that clients should be prepared to receive. This includes, for example, support for specific security schemes or URI redirection. In addition, other error situations may occur in the transport layer outside of the server. [[status_codes]] .Typical HTTP status codes [cols=""15,85"",options=""header""] |=== |Status code |Description |`200` |A successful request. |`201` |The request was successful and one or more new resources have being created. |`204` |The request was successful but did not generate any content. |`400` |The server cannot or will not process the request due to an apparent client error. For example, a query parameter had an incorrect value. |`401` |The request requires user authentication. The response includes a `WWW-Authenticate` header field containing a challenge applicable to the requested resource. |`403` |The server understood the request, but is refusing to fulfill it. While status code `401` indicates missing or bad authentication, status code `403` indicates that authentication is not the issue, but the client is not authorized to perform the requested operation on the resource. |`404` |The requested resource does not exist on the server. For example, a path parameter had an incorrect value. |`405` |The request method is not supported. For example, a POST request was submitted, but the resource only supports GET requests. |`406` |The `Accept` header submitted in the request did not support any of the media types supported by the server for the requested resource. |`410` |The target resource is no longer available at the origin server. |`429` |The user has sent too many requests in a given amount of time (""rate limiting""). |`500` |An internal error occurred in the server. |`501` |The server does not support the functionality required to fulfill the request. |=== More specific guidance is provided for each resource, where applicable. include::../recommendations/core/PER_additional-status-codes.adoc[] When a server encounters an error in the processing of a request, it may wish to include information in addition to the status code in the response. Since Web API interactions are often machine-to-machine, a machine-readable report would be preferred. https://datatracker.ietf.org/doc/html/rfc7807[RFC 7807] addresses this need by providing ""Problem Details"" response schemas for both JSON and XML. include::../recommendations/core/REC_problem-details.adoc[] === Support for cross-origin requests Access to content from a HTML page is by default prohibited for security reasons if the content is located on another host than the webpage (""same-origin policy""). Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A typical example is a web-application accessing processes and data from multiple servers. include::../recommendations/core/REC_cross-origin.adoc[] Two common mechanisms to support cross-origin requests are: * link:https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing (CORS)] * link:https://en.wikipedia.org/wiki/JSONP[JSONP (JSON with padding)] include::../recommendations/core/REC_access-control-expose-headers.adoc[] include::../recommendations/core/REC_html.adoc[] [[sc_limit_parameter]] === Limit parameter Several resources defined in this specification (see <>, <>) use the `limit` parameter to control the number of results that are presented in a response. * The client can request a limit it is interested in. * The server likely has a default value for the limit, and a maximum limit. * If the server has any more results available than it returns (the number it returns is less than or equal to the requested/default/maximum limit) then the server will include a link to the next set of results. So (using the default/maximum values of 10/1000 from the OpenAPI fragment in requirement <> or <>): * If you ask for 10 results, you will get 0 to 10 (as requested) and if there are more, a `next` link; * If you don't specify a limit, you will get 0 to 10 (default) and if there are more, a `next` link; * If you ask for 5000 results, you might get up to 1000 (server-limited) and if there are more, a `next` link; * If you follow the next link from the previous response, you might get up to 1000 additional results and if there are more, a `next` link. This document make requirements and recommendations about links in general and the `next` link in particular at the appropriate resource end points. [[next-link-discussion]] This document does not mandate any specific implementation approach for the `next` links. An implementation could use opaque links that are managed by the server. It is up to the server to determine how long these links can be dereferenced. Clients should be prepared to receive a 404 response. Another implementation approach is to use an implementation-specific parameter that specifies the index within the result set from which the server begins presenting results in the response, like `offset` or the `startIndex` parameter that was used in <>. The API will return no `next` link, if it has returned all selected results, and the server knows that. However, the server may not be aware that it has already returned all selected results. For example, if the request states `limit=10` and the query to the backend returns 10 results, the server may not know, if there are more results or not (in most cases there will be more results), unless the total number of results is also computed, which may be too costly. The server will then add the next link, and if there are no more results, dereferencing the next link will return an empty results list and no next link. This behavior is consistent with the statements above. Clients should not assume that paging is safe against changes to dataset while a client iterates through `next` links. If a server provides opaque links these could be safe and maintain the state during the original request. Using a parameter for the start index, however, will not be safe. [[prev-link-discussion]] This document also makes recommendations about include a `prev` link at the appropriate resource end points. Providing `prev` links supports navigating back and forth between pages, but depending on the implementation approach it may be too complex to implement. === Link headers include::../recommendations/core/REC_link-header.adoc[] [[sc_process_list]] === Retrieve a process list The following section defines the requirements to retrieve the available processes offered by the server. ==== Operation ===== Process list include::../requirements/core/REQ_process-list-op.adoc[] ===== Parameter `limit` include::../requirements/core/REQ_process-list-limit-def.adoc[] include::../recommendations/core/PER_process-list-limit-default-minimum-maximum.adoc[] include::../requirements/core/REQ_process-list-limit-response.adoc[] include::../recommendations/core/PER_process-list-limit-response.adoc[] ==== Response include::../requirements/core/REQ_process-list-success.adoc[] .Schema for the process list [source,yaml] ---- include::../openapi/schemas/processList.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/processList.yaml[`processList.yaml`]. [[schema-processSummary]] .Schema for a process summary [source,yaml] ---- include::../openapi/schemas/processSummary.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/processSummary.yaml[`processSummary.yaml`]. (see also: https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/descriptionType.yaml[`descriptionType.yaml`]). [[job-control-options-schema]] .Schema for the job control options [source,yaml] ---- include::../openapi/schemas/jobControlOptions.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/jobControlOptions.yaml[`jobControlOptions.yaml`]. [[transmission-mode-schema]] .Schema for the transmission mode [source,yaml] ---- include::../openapi/schemas/transmissionMode.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/transmissionMode.yaml[`transmissionMode.yaml`]. The number of process summaries returned depends on the server and the parameter `limit.` See the discussion about the `limit` parameter in the <> section. include::../requirements/core/REQ_links.adoc[] See the discussion about the `next` links in the <> section. include::../recommendations/core/REC_process-list-next-1.adoc[] include::../recommendations/core/REC_process-list-next-2.adoc[] include::../recommendations/core/REC_process-list-next-3.adoc[] See the discussion about the `prev` link in the <> section. include::../recommendations/core/PER_process-list-prev.adoc[] .A HTTP GET request for retrieving the list of offered processes encoded as JSON. ==== [source] ---- GET /processes HTTP/1.1 Host: processing.example.org ---- ==== .A Process list encoded as JSON. ==== [source,json] ---- include::../examples/json/ProcessList.json[] ---- ==== ==== Error situations See <> for general guidance. [[sc_process_description]] === Retrieve a process description The following section defines the requirements to retrieve metadata about a process. ==== Operation include::../requirements/core/REQ_process-description-op.adoc[] ==== Response include::../requirements/core/REQ_process-description-success.adoc[] The <> does not mandate the use of a specific process description to specify the interface of a process. That said, the <> requirements class makes the following recommendation: include::../recommendations/core/REC_ogc-process-description.adoc[] ==== Error situations See <> for general guidance. include::../requirements/core/REQ_process-exception-no-such-process.adoc[] [[sc_create_job]] === Execute a process This section describes the requirements for executing a process. Depending on the description of the <> and the <>, process execution may result in the creation of a <>. ==== Operation include::../requirements/core/REQ_process-execute-op.adoc[] ==== Request body ===== Content schema include::../requirements/core/REQ_process-execute-request.adoc[] [[execute-request-body]] .Schema for execute [source,yaml] ---- include::../openapi/schemas/execute.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/execute.yaml[`execute.yaml`]. [[inline-or-ref-data]] .Schema for an in-line or referenced process input value [source,yaml] ---- include::../openapi/schemas/inlineOrRefData.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/inlineOrRefData.yaml[`inlineOrRefData.yaml`]. (see also: <>, <>, <>) [[output-schema]] .Schema for a process output [source,yaml] ---- include::../openapi/schemas/output.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/output.yaml[`output.yaml`]. [[format-schema]] .Schema for a format qualifier [source,yaml] ---- include::../openapi/schemas/format.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/format.yaml[`format.yaml`]. [[sc_process_inputs]] ===== Process inputs *_Overview:_* Each process input is a name/value pair that appears in the `inputs` section of an execute request. The name of each input is its identifier as specified by the input's definition in the <>. include::../requirements/core/REQ_process-execute-inputs.adoc[] As shown in https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/inlineOrRefData.yaml[inlineOrRefData.yaml], a process input value that is specified in-line in an execute request can be: * a simple literal value, * an array, * a qualified value, * a binary value, * or a bounding box. [[simple-literals]] *_Simple literal values:_* A simple literal value can be a string, number, integer or Boolean. [[input-value-noobject-schema]] .Schema for a simple literal value [source,yaml] ---- include::../openapi/schemas/inputValueNoObject.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/inputValueNoObject.yaml[`inputValueNoObject.yaml`]. (see also: <>, <>) .Simple literal value examples. ==== A string literal: [source] ---- ""stringInput"": ""String value"" ---- A date string: [source] ---- ""dateInput"": ""2021-05-24T20:40:13-05:00"" ---- A number: [source] ---- ""numberInput"": 3.14159 ---- An integer: [source] ---- ""integerInput"": 10 ---- A Boolean: [source] ---- ""booleanInput"": true ---- ==== [[arrays]] *_Array of values:_* Array elements, as per <>, can be: * <>, * embedded arrays, * <>, * <>, * <>, * or references to values using <>. include::../requirements/core/REQ_process-execute-input-array.adoc[] .Array value examples. ==== An array of simple values: [source] ---- ""arrayOfSimpleValues"": [1, 2, 4, 10, 7] ---- An array with a single simple value: [source] ---- ""arrayOfSimpleValues"": [""a""] ---- An array of arrays of simple values: [source] ---- ""arrayOfArrays"": [[1,2,3,4], [""a"",""b"",""c"",""d""]] ---- An array of objects values: [source] ---- ""arrayOfQualifiedValues"": [ { ""value"": { ""measurement"": 10.3, ""uom"": ""m"", ""reference"": ""https://ucum.org/ucum-essence.xml"" } }, { ""value"": { ""measurement"": 10.5, ""uom"": ""m"", ""reference"": ""https://ucum.org/ucum-essence.xml"" } }, { ""value"": { ""measurement"": 10.9, ""uom"": ""m"", ""reference"": ""https://ucum.org/ucum-essence.xml"" } },... ], ---- NOTE: In an execute request, as per requirement <>, object values must be encoded as <>. ==== [[qualified-value]] *_Qualified values:_* A qualified value is a <> that can be optionally qualified with a `format` parameter. Qualified values can be used to encode process input values that, according to their definition in the <>, can be of multiple media types. The `format` parameter is used to identify the specific media type being provided as the process input. Qualified values can also be used to encode object-valued process inputs in order to avoid ambiguity with the built-in value schemas defined in this standard (i.e. <>, <> or <> itself). The actual _value_ in a qualified value object is specified using the `value` key. The value of the `value` key is an instance of <>. [[qualified-value-schema]] .Schema for a qualified value [source,yaml] ---- include::../openapi/schemas/qualifiedInputValue.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/qualifiedInputValue.yaml[`qualifiedInputValue.yaml`]. (see also: <>) [[input-value-schema]] .Schema of a process input value [source,yaml] ---- include::../openapi/schemas/inputValue.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/inputValue.yaml[`inputValue.yaml`]. (see also: <>) include::../requirements/core/REQ_process-execute-input-inline-object.adoc[] include::../requirements/core/REQ_process-execute-input-inline-mixed.adoc[] .Qualified value examples. ==== An example of a complex process input value. [source,json] ---- ""complexObjectInput"": { ""value"": { ""property1"": ""value1"", ""property2"": ""value2"", ""property3"": ""value3"" } } ---- In this second example, the property, `geometryInput` has a cardinality of greater than 1 and value instances can be one of a number of enumerated media types. The schema of `geometryInput` from the <> for the process might be: [source,json] ---- ""geometryInput"": { ""title"": ""Geometry input"", ""description"": ""This is an example of a geometry input. In this case the geometry can be expressed as a GML or GeoJSON geometry."", ""minOccurs"": 2, ""maxOccurs"": 5, ""schema"": { ""oneOf"": [ { ""type"": ""string"", ""contentMediaType"": ""application/gml+xml; version=3.2"", ""contentSchema"": ""http://schemas.opengis.net/gml/3.2.1/geometryBasic2d.xsd"" }, { ""$ref"": ""http://schemas.opengis.net/ogcapi/features/part1/1.0/openapi/schemas/geometryGeoJSON.json"" } ] } }, ---- and an instance of this process input in an execute request might be: [source] ---- ""geometryInputs"": [ { ""value"": ""-77.024519 38.810529 -77.024635 38.810973 -77.024704 38.810962 -77.024776 38.811239 -77.024957 38.81121 -77.024905 38.811012 -77.024905 38.811012 -77.024865 38.810857 -77.025024 38.810832 -77.025071 38.811012 -77.025203 38.810992 -77.02506 38.810444 -77.024519 38.810529"", ""mediaType"": ""application/gml+xml; version=3.2"" }, { ""value"": { ""type"": ""Polygon"", ""coordinates"": [[[ -176.5814819, -44.10896301 ], [ -176.5818024, -44.10964584 ], [ -176.5844116, -44.11236572 ], [ -176.5935974, -44.11021805 ], [ -176.5973511, -44.10743332 ], [ -176.5950928, -44.10562134 ], [ -176.5858459, -44.1043396 ], [ -176.5811157, -44.10667801 ], [ -176.5814819, -44.10896301 ]]] }, ""mediaType"": ""application/geo+json"" } ] ---- In this case, the `mediaType` parameter is used to indicate the specific type of geometry being passed as input in each case; GML Polygon for the first element of the array and GeoJSON Polygon for the second element. ==== [[binary-value]] *_Binary values:_* In some cases, for example in order to pass through firewalls, binary input values need to be encoded in-line in an execute request as a string. [[binary-input-value-schema]] .Schema for an in-line binary value [source,yaml] ---- include::../openapi/schemas/binaryInputValue.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/binaryInputValue.yaml[`binaryInputValue.yaml`]. include::../requirements/core/REQ_process-execute-input-inline-binary.adoc[] .Binary value examples. ==== This is an example of an image process input whose media type is defined in the <>. The schema definition for this process input might be: [source,json] ---- ""schema"": { ""type"": ""string"", ""contentEncoding"": ""binary"", ""contentMediaType"": ""image/tiff; application=geotiff"" } ---- and an example instance value in an execute request might be: [source,json] ---- ""imageInput"": ""R0lGODdhNAHCAfcAAAcHDD+Gs4sLDQpDaqGFdaHE54dJPEoECUlGRteKgcdITgokG4hoVkpY\\ngNzHwKKkqOLm7RRjlEgpHU9iZ44lHQYqVdmki6doVmhHOMOIeJG20HiDjCcKBglIeadISrso\\nJGooFNbN2d2qr8aljyklHwQJQkdvkWaKxIdrb442LidLeGhMTp6LkeP1+Kh3aiUuVAoUHmlu\\ngkcwNYdZRmkJDYGcsDFokElVYyk1NsWWhLEPDtmQldrUyoyFhrjo+Nna5d+4tMGstspoXgc4\\n...qgu7sSu7qbtCs2u7t6u6rLsrp4u7veu76eO6vyu8w0u8xWu8x4u8yau8shu8y+u8zwu90Su9\\n00u91Wu914u92au928u9whsQADs="" ---- NOTE: Even though the schema indicates that the input type is `binary`, when the input value is encoded in-line in an execute request, as per requirement <>, the binary value is encoded as base64-encoded string. In this second example, the image input can be one of a number of value types denoted in JSON Schema by the use of the `oneOf[]` construct. An example schema for this a process input might be: [source,json] ---- ""schema"": { ""oneOf"": [ { ""type"": ""string"", ""contentEncoding"": ""binary"", ""contentMediaType"": ""image/tiff; application=geotiff"" }, { ""type"": ""string"", ""contentEncoding"": ""binary"", ""contentMediaType"": ""image/jp2"" } ] } ---- and a JPEG2000 instance example in an execute request might be: [source,json] ---- { ""value"": ""VBORw0KGgoAAAANSUhEUgAABvwAAAa4CAYAAABMB35kAAABhGlDQ1BJQ0MgcHJvZmlsZQAA\\nKJF9kT1Iw0AcxV9TpSL1A+xQxCFDdbIgKuKoVShChVArtOpgcumH0KQhSXFxFFwLDn4sVh1c\\nnHV1cBUEwQ8QNzcnRRcp8X9JoUWMB8f9eHfvcfcOEOplplkdY4Cm22Y6mRCzuRUx9IogouhH\\n ... \\nj3Z5mX7/PCPVRJV92rpHK24xcJrzk20+tkeYlCPqcZNO3Lpni1OJWatPCcmgGDEqx7Om6lfa\\nppM4k4BTe9+bsn3L9/9/yWhA0PwQGW8ipCZsnZt9lsdrYEM8z/M8z/M8z/M8z/M8z/MzLWY1\\nAAAACUlEQVQ871H6P6JI+TxS5Wn2AAAAAElFTkSuQmCC"", ""mediaType"": ""image/jp2"" } ---- ==== [[bounding-box-value]] *_Bounding box values:_* A process input value instance can be a bounding box. include::../requirements/core/REQ_process-execute-input-inline-bbox.adoc[] [[bbox-schema]] .Schema for a bounding box value [source,yaml] ---- include::../openapi/schemas/bbox.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/bbox.yaml[`bbox.yaml`]. This schema is meant to be a template for defining bounding box process inputs. If the specified `default` and `enum` are suitable for your purposes then you can reference this file directly in your process description. include::../recommendations/core/PER_process-execute-input-inline-bbox.adoc[] *_Input validation_* Process inputs in an execute request and the corresponding process input definition in the <> have a validation relationship. That is to say, that the schema of a process input definition from the <> can be used to validate the component of the corresponding process input value in an execute request that is an instance of <>. [%unnumbered] ==== Consider a process input named `complexObjectInput` with the following definition from an <>: [source,json] ---- ""complexObjectInput"": { ""title"": ""Complex Object Input Example"", ""description"": ""This is an example of a complex object input."", ""schema"": { ""type"": ""object"", ""required"": [ ""property1"", ""property5"" ], ""properties"": { ""property1"": { ""type"": ""string"" }, ""property2"": { ""type"": ""string"", ""format"": ""uri"" }, ""property3"": { ""type"": ""number"" }, ""property4"": { ""type"": ""string"", ""format"": ""date-time"" }, ""property5"": { ""type"": ""boolean"" } } } } ---- and the following instance in an execute request: [source,json] ---- ""inputs"": [ . . . ""complexObjectInput"": { ""value"": { ""property1"": ""value1"", ""property2"": ""value2"", ""property3"": ""value5"" } }, . . . ] ---- The process input value in this execute request is an instance of a <>. For the purposes of validation, the server need only validate the component of the <> that is an instance of <> against the `schema` fragment from the <>. Specifically, the validation target is: [source,json] ---- { ""property1"": ""value1"", ""property2"": ""value2"", ""property3"": ""value5"" } ---- NOTE: This example makes use of an <>. However, any other process description vocabulary may be used and applied, for the purpose of validation, in a similar manner. ==== include::../requirements/core/REQ_process-execute-input-validation.adoc[] [[sc_execution_mode]] ===== Execution mode A process may be executed synchronously or asynchronously. In which of these two modes a server responds is a function of the job control options specified in the <> and the presence or absence of the HTTP `Prefer` header (http://tools.ietf.org/rfc/rfc7240.txt[IETF RFC 7240]). include::../requirements/core/REQ_process-execute-default-execution-mode.adoc[] include::../requirements/core/REQ_process-execute-auto-execution-mode.adoc[] include::../recommendations/core/REC_process-execute-honor-prefer.adoc[] include::../recommendations/core/REC_process-execute-handle-prefer.adoc[] include::../recommendations/core/REC_process-execute-preference-applied.adoc[] [[sc_process_outputs]] ===== Process outputs *_Overview:_* Each process output is a named object that appears in the `outputs` section of an <>. The name of each output is its identifier as specified by the output's definition in the <>. *_Default outputs:_* include::../requirements/core/REQ_process-execute-default-outputs.adoc[] *_Output value format:_* A process output can be defined in the <> as being of one or more media types. In cases where a specific output can be presented in one of a number of media types, the `format` parameter in the <> can be used to indicate the format that should be used to present the process output value in the server's <>. [[sc_output_value_size]] *_Output value size:_* Since a priori knowledge of the size of any given output is generally not known, hints can be provided to the server to prevent the inadvertant transmission of large outputs. Return preferences signal to a server how output values should be transmitted based on the size of the output and any accompanying https://datatracker.ietf.org/doc/html/rfc7240#section-4.2[`return` preferences] as define defined in http://tools.ietf.org/rfc/rfc7240.txt[IETF RFC 7240]. include::../recommendations/core/REC_process-execute-honor-return-preference.adoc[] include::../recommendations/core/REC_process-execute-handle-return-preference.adoc[] ==== Example .An execute request. ==== [source,json] ---- include::../examples/json/Execute.json[] ---- ==== [[sc_execute_response]] ==== Response ===== Overview The manner in which a server responds to a process execution request is determined by the following parameters: * the <> (synchronous or asynchronous), * the number of outputs requested, * the negotiated content type for the response (via the HTTP Accept header), * and any negotiated client preferences (via the HTTP Prefer header). The following table maps the possible responses based on the combinations of these execute parameters. The column headers denote: . *Negotiated execute mode*: see <> . *Requested # outputs*: the number of output requested in the <> . *Return preference*: the negotiated <> . *Response HTTP code*: the https://datatracker.ietf.org/doc/html/rfc2616#section-6.1.1[HTTP status code] that the server should generate in this context . *Response headers*: any required https://datatracker.ietf.org/doc/html/rfc2616#section-14[HTTP headers] that the server must include in this context . *Response media type*: the value of the HTTP `Content-Type` header that the server should generate in this context . *Response body*: a description of the content of the response body in this context . *Req./Rec./Perm.*: the corresponding requirements/recommendations/permission as per this specification [[table_core_execute_responses]] .Execute responses based on number of requested outputs, request HTTP headers and the size of output values. [cols=8,options=""header""] |=== |Negotiated execute mode |Requested # outputs |Return preference (`Prefer` header) |Response HTTP code |Response headers |Response media type (`Content-Type` header) |Response body |Req./Rec./Perm. .4+|sync |1 |_n/a_ |200 | |_as negotiated_ |requested process output |See requirement: <> 1.3+|N |_none_ .3+|200 .3+| .3+|application/json .3+|<> |See <>,<> |minimal |See <>,<> |representation |See <>,<> |async |_n/a_ |_n/a_ |200 |_Location_ to newly created job |application/json |<> |See requirement: <> |=== [NOTE] ==== * The value *_n/a_* in a cell means that the corresponding parameter is not applicable, not specified, not required or can be ignored in this context. * The value *_as negotiated_* means that the output content type is as negotiated between the client and the server based on the value of the HTTP Accept header. ==== [NOTE] ==== This table shows all possible combinations of execute parameters that are specified by this standard. Not all of these combinations need to be implemented by a server conforming to this standard. For example, a server that only offers processes that can be executed synchronously does not need to implement any of the asynchronous requirements. ==== [[sync_note_3]] [NOTE] ==== * See requirement: <> * See permission: <> ==== [[sync_note_4]] [NOTE] ==== * See recommendation: <> ==== [[sync_note_5]] [NOTE] ==== * See recommendation: <> ==== [[sync_note_6]] [NOTE] ==== * See recommendation: <> ==== [[schema_results]] .Schema for processing results presented as a JSON document [source,yaml] ---- include::../openapi/schemas/results.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/results.yaml[`results.yaml`]. This schema defines a map using the respective output identifier as the key. The value of an output can be returned as an in-line value or by reference. ===== Response requesting a single processing output When a process is executed synchronously and a single processing output is requested, the following requirements and recommendations apply: include::../requirements/core/REQ_process-execute-success-sync-one.adoc[] NOTE: The size of a response may be determined without actually transmitting the entire response by using the <> method to retrieve the <> header. ===== Response requesting multiple processing outputs When a process is executed synchronously and multiple processing outputs are requested, the following requirements and recommendations apply: include::../requirements/core/REQ_process-execute-success-sync-many-json.adoc[] include::../recommendations/core/REC_process-execute-success-sync-many-json-prefer-none.adoc[] include::../recommendations/core/REC_process-execute-success-sync-many-json-prefer-minimal.adoc[] include::../recommendations/core/REC_process-execute-success-sync-many-json-prefer-representation.adoc[] include::../recommendations/core/PER_process-execute-success-sync-many-other-formats.adoc[] ===== Job creation on synchronous process execution This specification does not mandate that servers create a job as a result of executing a process synchronously. However the following permission is given: include::../recommendations/core/PER_process-execute-sync-job.adoc[] For servers that implement this permission and do create a job as a result of synchronous execution of a process, the following requirement applies: include::../requirements/core/REQ_job-results-success-sync.adoc[] The job reference in the header can then be used to <> of the original synchronous execution. ===== Response for asynchronous processes execution In the case of asynchronous execution, the following requirement applies: include::../requirements/core/REQ_process-execute-success-async.adoc[] ==== Error situations See <> for general guidance. If the process with the specified identifier does not exist on the server, see requirement <>. [[sc_retrieve_status_info]] === Retrieve status information about a job The following section describes the requirements to retrieve information about the status of a job. ==== Operation include::../requirements/core/REQ_job-op.adoc[] ==== Response include::../requirements/core/REQ_job-success.adoc[] [[schema-statusInfo]] .Schema for status info [source,yaml] ---- include::../openapi/schemas/statusInfo.yaml[] ---- NOTE: This schema can also be obtained from https://raw.githubusercontent.com/opengeospatial/ogcapi-processes/master/core/openapi/schemas/statusInfo.yaml[`statusInfo.yaml`]. .Schema for status codes [source,yaml] ---- include::../openapi/schemas/statusCode.yaml[] ---- NOTE: This schema can also be obtained from http://schemas.opengis.net/ogcapi/processes/part1/1.0/openapi/schemas/statusCode.yaml[`statusCode.yaml`]. The job status information includes several optional date-time fields that represent milestones in the life cycle of a job. The following are recommended for servers that decide to populate some or all of these date-time fields: include::../recommendations/core/REC_job-status.adoc[] NOTE: Once a job has finished execution and is no longer consuming compute resources, the duration of processing can be computed as `finished-started`. The `updated` field, however, may still be revised as the system continues processing outputs, storing results, releasing compute resources, etc. .A HTTP GET request for retrieving status information about a job encoded as JSON. ==== [source] ---- GET /jobs/81574318-1eb1-4d7c-af61-4b3fbcf33c4f HTTP/1.1 Host: processing.example.org ---- ==== .A job encoded as JSON. ==== [source,json] ---- include::../examples/json/StatusInfo.json[] ---- ==== ==== Error situations See <> for general guidance. If the process with the specified identifier does not exist on the server, see requirement <>. include::../requirements/core/REQ_job-exception-no-such-job.adoc[] [[sc_retrieve_job_results]] === Retrieve job results A process can generate zero or more outputs. This clause specifies how: * processing results can be retrieved individually in a single request, * a subset of processing results can be retrieved in a single request, * or all processing results can be retrieved in a single request. [[sc_retrieve_job_results_one]] ==== Retrieving results individually ===== Operation include::../requirements/core/REQ_job-result-op.adoc[] NOTE: The size of a processing result may be determined without actually transmitting the entire result by using the <> method to retrieve the <> header. [[sc_retrieve_job_results_many]] ==== Retrieving multiple results ===== Operation include::../requirements/core/REQ_job-results-op.adoc[] ===== Parameters include::../requirements/core/REQ_job-results-param-outputs.adoc[] include::../requirements/core/REQ_job-results-param-outputs-response.adoc[] include::../requirements/core/REQ_job-results-param-outputs-omit.adoc[] ==== Response ===== Overview The manner in which a server responds when retrieving job results depends on: * the number of outputs requested, * the negotiated content type for the response (via the HTTP Accept header) or lack thereof, * and any negotiated client preferences (via the HTTP Prefer header). The following table maps the possible responses based on the combinations of these execute parameters. The column headers in the following table denote: . *Requested # outputs*: the number of outputs requested in the <> . *Access path*: the API endpoint from which the result(s) can be retrieved . *Return preference*: the negotiated <> . *Response HTTP code*: the https://datatracker.ietf.org/doc/html/rfc2616#section-6.1.1[HTTP status code] that the server should generate in this context . *Response media type*: the value of the HTTP `Content-Type` header that the server should generate in this context . *Response body*: a description of the content of the response body in this context . *Req./Rec./Perm.*: the corresponding requirements/recommendations/permission as per this specification [[table_core_getresults_responses]] .Table mapping get results responses based on the input parameter values used on the original execute request. [cols=7,options=""header""] |=== |Requested # outputs |Access path |Return preference (`Prefer` header) |Response HTTP code |Response media type (`Content-Type` header) |Response body |Req./Rec./Perm. |1 |/jobs/{jobID}/results/{outputID} |_n/a_ |200 |_as negotiated_ |requested process output value |See requirement: <> 1.3+|N .3+|/jobs/{jobID}/results |_none_ .3+|200 .3+|application/json .3+|<> |See <>,<> |minimal |See <>,<> |representation |See <>,<> |=== [NOTE] ==== * The value *_n/a_* in a cell means value of the corresponding parameter is not applicable, not specified, not required or can be ignored in this context. * The value *_as negotiated_* means that the output content type is as negotiated between the client and the server based on the value of the HTTP Accept header. ==== [[async_note_2]] [NOTE] ==== * See requirement: <> * See permission: <> ==== [[async_note_3]] [NOTE] ==== * See recommendation: <> ==== [[async_note_4]] [NOTE] ==== * See recommendation: <> ==== [[async_note_5]] [NOTE] ==== * See recommendation: <> ==== The following requirements apply when retrieving the results of a job that was created by executing a process asynchronously OR was created by executing a process synchronously on a server that creates a job even for synchronous execution: ===== Retrieving results individually include::../requirements/core/REQ_job-results-success-async-one.adoc[] ===== Retrieving multiple results include::../requirements/core/REQ_job-results-success-async-many.adoc[] include::../recommendations/core/REC_job-results-success-async-many-json-prefer-none.adoc[] include::../recommendations/core/REC_job-results-success-async-many-json-prefer-minimal.adoc[] include::../recommendations/core/REC_job-results-success-async-many-json-prefer-representation.adoc[] include::../recommendations/core/PER_job-results-success-async-many-other-formats.adoc[] .A HTTP GET request for retrieving the result a job encoded as JSON. ==== [source] ---- GET /jobs/81574318-1eb1-4d7c-af61-4b3fbcf33c4f/results HTTP/1.1 Host: processing.example.org ---- ==== .A result encoded as JSON. ==== [source,json] ---- include::../examples/json/Result.json[] ---- ==== ==== Error situations See <> for general guidance. include::../requirements/core/REQ_job-results-exception-no-such-job.adoc[] include::../requirements/core/REQ_job-results-exception-results-not-ready.adoc[] include::../requirements/core/REQ_job-results-failed.adoc[] ",12287,False,2134.6702326679097,median "// Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include