text,length,is_long_context,metric_val,label_metric "/*========================================================================= Program: Visualization Toolkit Module: vtkBinnedDecimation.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include ""vtkBinnedDecimation.h"" #include ""vtkArrayDispatch.h"" #include ""vtkArrayListTemplate.h"" // For processing attribute data #include ""vtkBoundingBox.h"" #include ""vtkCellArray.h"" #include ""vtkCellArrayIterator.h"" #include ""vtkCellData.h"" #include ""vtkDataArray.h"" #include ""vtkDataArrayRange.h"" #include ""vtkExecutive.h"" #include ""vtkFloatArray.h"" #include ""vtkIdTypeArray.h"" #include ""vtkInformation.h"" #include ""vtkInformationVector.h"" #include ""vtkLogger.h"" #include ""vtkMath.h"" #include ""vtkObjectFactory.h"" #include ""vtkPointData.h"" #include ""vtkPolyData.h"" #include ""vtkSMPThreadLocal.h"" #include ""vtkSMPTools.h"" #include ""vtkTriangle.h"" #include #include vtkStandardNewMacro(vtkBinnedDecimation); //---------------------------------------------------------------------------- // Core algorithms and functors to implement threading and type dispatch. Note // that four different algorithms are implemented, partially for demonstrative // purposes but also for the fun of it. If I had to pick one, I'd pick // algorithm 4) BIN_CENTERS which scales better for large numbers of bins, and // generally produces the best results. namespace { // There are essentially four different algorithms implemented here depending // on how the output points are generated in each bin: 1) reuse the input // points; 2) generate new points by selecting one of the points falling // into each bin; 3) generate new points at bin centers; and 4) average the // points (and attribute data) contained within the bins. // Functor to bin points to generate bin ids. The binning functor is common // to all the algorithms / output options. template struct BinPoints { PointsT* Points; TIds* BinIds; int Divisions[3]; double Bounds[6]; double H[3]; // For performance double hX, hY, hZ; double fX, fY, fZ, bX, bY, bZ; vtkIdType xD, yD, zD, xyD; BinPoints( PointsT* pts, TIds* binIds, const int* dims, const double* bounds, const double* spacing) : Points(pts) , BinIds(binIds) { for (auto i = 0; i < 3; ++i) { this->Divisions[i] = dims[i]; this->Bounds[2 * i] = bounds[2 * i]; this->Bounds[2 * i + 1] = bounds[2 * i + 1]; this->H[i] = spacing[i]; } // Used for performance this->hX = this->H[0] = spacing[0]; this->hY = this->H[1] = spacing[1]; this->hZ = this->H[2] = spacing[2]; this->fX = 1.0 / spacing[0]; this->fY = 1.0 / spacing[1]; this->fZ = 1.0 / spacing[2]; this->bX = this->Bounds[0] = bounds[0]; this->Bounds[1] = bounds[1]; this->bY = this->Bounds[2] = bounds[2]; this->Bounds[3] = bounds[3]; this->bZ = this->Bounds[4] = bounds[4]; this->Bounds[5] = bounds[5]; this->xD = this->Divisions[0]; this->yD = this->Divisions[1]; this->zD = this->Divisions[2]; this->xyD = this->Divisions[0] * this->Divisions[1]; } // Functions to obtain bin index inlined for performance. void GetBinIndices(const double* x, int ijk[3]) const { // Compute point index. Make sure it lies within range of locator. TIds tmp0 = static_cast(((x[0] - bX) * fX)); TIds tmp1 = static_cast(((x[1] - bY) * fY)); TIds tmp2 = static_cast(((x[2] - bZ) * fZ)); ijk[0] = tmp0 < 0 ? 0 : (tmp0 >= xD ? xD - 1 : tmp0); ijk[1] = tmp1 < 0 ? 0 : (tmp1 >= yD ? yD - 1 : tmp1); ijk[2] = tmp2 < 0 ? 0 : (tmp2 >= zD ? zD - 1 : tmp2); } TIds GetBinIndex(const double* x) const { int ijk[3]; this->GetBinIndices(x, ijk); return (ijk[0] + ijk[1] * xD + ijk[2] * xyD); } void operator()(vtkIdType ptId, vtkIdType endPtId) { const auto points = vtk::DataArrayTupleRange<3>(this->Points, ptId, endPtId); double x[3]; TIds* bins = this->BinIds + ptId; for (const auto tuple : points) { x[0] = static_cast(tuple[0]); x[1] = static_cast(tuple[1]); x[2] = static_cast(tuple[2]); *bins++ = this->GetBinIndex(x); } } }; // Generate the output triangles. This functor is common to // three of the algorithms #1-3. template struct GenerateTriangles { const TIds* BinIds; const TPtMap* PointMap; vtkCellArray* Tris; vtkSMPThreadLocal> CellIterator; const TIds* TriMap; vtkIdType* OutTris; vtkIdType* OutTriOffsets; ArrayList* Arrays; GenerateTriangles(TIds* bins, TPtMap* ptMap, vtkCellArray* tris, TIds* triMap, vtkIdType* outTris, vtkIdType* outTriOffsets, ArrayList* arrays) : BinIds(bins) , PointMap(ptMap) , Tris(tris) , TriMap(triMap) , OutTris(outTris) , OutTriOffsets(outTriOffsets) , Arrays(arrays) { } void Initialize() { this->CellIterator.Local().TakeReference(this->Tris->NewIterator()); } void operator()(vtkIdType triId, vtkIdType endTriId) { const TIds* binIds = this->BinIds; const TPtMap* ptMap = this->PointMap; vtkIdType npts; const vtkIdType* tri; vtkCellArrayIterator* cellIter = this->CellIterator.Local(); const TIds* triMap = this->TriMap; vtkIdType *outTris = this->OutTris, *outTri; vtkIdType *outTriOffsets = this->OutTriOffsets, *outOffsets; for (; triId < endTriId; ++triId) { if ((triMap[triId + 1] - triMap[triId]) > 0) // spit out triangle { cellIter->GetCellAtId(triId, npts, tri); outOffsets = outTriOffsets + triMap[triId]; *outOffsets = triMap[triId] * 3; outTri = outTris + *outOffsets; outTri[0] = ptMap[binIds[tri[0]]]; outTri[1] = ptMap[binIds[tri[1]]]; outTri[2] = ptMap[binIds[tri[2]]]; if (this->Arrays) // copy cell data if requested { this->Arrays->Copy(triId, triMap[triId]); } } } } void Reduce() {} }; //============================ Implement algorithms ================== //============================ 1) Reuse INPUT_POINTS ================= // Traverse cells and mark points and cells that are included in the output template struct SelectOutput { const TIds* BinIds; unsigned char* PointUses; vtkCellArray* Tris; TIds* TriMap; vtkSMPThreadLocal> CellIterator; SelectOutput(TIds* bins, unsigned char* ptUses, vtkCellArray* tris, TIds* triMap) : BinIds(bins) , PointUses(ptUses) , Tris(tris) , TriMap(triMap) { } void Initialize() { this->CellIterator.Local().TakeReference(this->Tris->NewIterator()); } void operator()(vtkIdType triId, vtkIdType endTriId) { vtkIdType npts; const vtkIdType* tri; vtkCellArrayIterator* cellIter = this->CellIterator.Local(); TIds* triMap = this->TriMap + triId; unsigned char* ptUses = this->PointUses; for (; triId < endTriId; ++triId, ++triMap) { cellIter->GetCellAtId(triId, npts, tri); // All three points have to be in different bins if (this->BinIds[tri[0]] != this->BinIds[tri[1]] && this->BinIds[tri[0]] != this->BinIds[tri[2]] && this->BinIds[tri[1]] != this->BinIds[tri[2]]) { *triMap = 1; ptUses[tri[0]] = 1; ptUses[tri[1]] = 1; ptUses[tri[2]] = 1; } else // mark excluded from output { *triMap = 0; } } } void Reduce() {} }; // Only initialize bins that actually contain a point. We are doing // this to avoid using std::atomic which the other algorithms use. template struct InitializePointMap { const TIds* BinIds; const unsigned char* PointUses; TIds* PointMap; InitializePointMap(TIds* binIds, unsigned char* ptUses, TIds* ptMap) : BinIds(binIds) , PointUses(ptUses) , PointMap(ptMap) { } void operator()(vtkIdType ptId, vtkIdType endPtId) { const TIds* binIds = this->BinIds; const unsigned char* ptUses = this->PointUses + ptId; TIds* ptMap = this->PointMap; for (; ptId < endPtId; ++ptId) { if (*ptUses++ > 0) { ptMap[binIds[ptId]] = (-1); // mark unvisited } } } }; //---------------------------------------------------------------------------- // Decimation algorithm #1 which reuses the input points. template void ReuseDecimate(vtkIdType numPts, PointsT* pts, vtkIdType numTris, vtkCellArray* tris, vtkCellData* inCD, vtkCellData* outCD, vtkIdType numBins, const int* dims, const double* bounds, const double* spacing, vtkPolyData* output) { // Setup execution. Several arrays are used to transform the data. // The bin id of each point TIds* binIds = new TIds[numPts]; // Is the point used in the output ? unsigned char* ptUses = new unsigned char[numPts]; std::fill_n(ptUses, numPts, 0); // The output point id assigned to each bin (if bin contains an output point). TIds* ptMap = new TIds[numBins]; // Which triangle cells are output? And later, the offsets into the // output cell array. TIds* triMap = new TIds[numTris + 1]; // Bin points to generate a bin index for each point BinPoints binPoints(pts, binIds, dims, bounds, spacing); vtkSMPTools::For(0, numPts, binPoints); // Select which triangles and points are sent to the output. SelectOutput selectOutput(binIds, ptUses, tris, triMap); vtkSMPTools::For(0, numTris, selectOutput); // Initialize the point map, only the bins that contain something InitializePointMap initPtMap(binIds, ptUses, ptMap); vtkSMPTools::For(0, numPts, initPtMap); // Prefix sums to roll up the points and cells, and setup offsets for // subsequent threading. This could be threaded, although the gains // are likely modest. vtkIdType numOutPts = 0; for (vtkIdType ptId = 0; ptId < numPts; ++ptId) { if (ptUses[ptId] > 0) { if (ptMap[binIds[ptId]] < 0) { ptMap[binIds[ptId]] = ptId; ++numOutPts; } } } vtkIdType mark, numOutTris = 0; for (vtkIdType triId = 0; triId < numTris; ++triId) { mark = triMap[triId]; triMap[triId] = numOutTris; numOutTris += mark; } triMap[numTris] = numOutTris; // Produce the decimated output vtkCellArray* outTrisArray = output->GetPolys(); vtkNew outConn; vtkIdType* outTris = outConn->WritePointer(0, numOutTris * 3); vtkNew outOffsets; vtkIdType* outTriOffsets = outOffsets->WritePointer(0, numOutTris + 1); outTriOffsets[numOutTris] = 3 * numOutTris; ArrayList arrays; if (outCD) // copy cell data if requested { outCD->CopyAllocate(inCD, numOutTris); arrays.AddArrays(numOutTris, inCD, outCD); } // Produce output triangles. GenerateTriangles genTris( binIds, ptMap, tris, triMap, outTris, outTriOffsets, (outCD != nullptr ? (&arrays) : nullptr)); vtkSMPTools::For(0, numTris, genTris); outTrisArray->SetData(outOffsets, outConn); // Clean up delete[] triMap; delete[] ptMap; delete[] ptUses; delete[] binIds; } //---------------------------------------------------------------------------- // Dispatch to the decimate algorithm #1 which reuses input points. struct PointReuseWorker { template void operator()(DataT* pts, bool largeIds, vtkCellArray* tris, vtkCellData* inCD, vtkCellData* outCD, int* divs, double bounds[6], double spacing[3], vtkPolyData* output) { vtkIdType numPts = pts->GetNumberOfTuples(); vtkIdType numTris = tris->GetNumberOfCells(); vtkIdType numBins = divs[0] * divs[1] * divs[2]; // Use the appropriate id type for memory and performance reasons. if (!largeIds) { ReuseDecimate( numPts, pts, numTris, tris, inCD, outCD, numBins, divs, bounds, spacing, output); } else { ReuseDecimate( numPts, pts, numTris, tris, inCD, outCD, numBins, divs, bounds, spacing, output); } } }; //==========2) Generate new points from selected points BIN_POINTS ============= //==========3) Generate new points at BIN_CENTERS ============================== // These algorithms #2 and #3 are essentially the same with the difference // being how the output points are created. // Traverse cells and map input points and cells to output points and cells template struct MapOutput { const TIds* BinIds; std::atomic* PointMap; vtkCellArray* Tris; TIds* TriMap; vtkSMPThreadLocal> CellIterator; MapOutput(TIds* bins, std::atomic* ptMap, vtkCellArray* tris, TIds* triMap) : BinIds(bins) , PointMap(ptMap) , Tris(tris) , TriMap(triMap) { } // This method is used to select a point id within a bin from a potential // set of contributing point ids, which becomes the single point id // associated with the bin. Since there are possibly multiple, simultaneous // writes to a bin, an atomic is used to prevent data races etc. inline void WritePtId(std::atomic& binId, vtkIdType ptId) { // Because of zero initialization, a negative ptId is written. The end result is // that we select the smallest point id from the set of points within a bin. TIds currentId, targetId = (-(ptId + 1)); do { currentId = binId; if (currentId < targetId) { return; } } while (!atomic_compare_exchange_weak(&binId, ¤tId, targetId)); } void Initialize() { this->CellIterator.Local().TakeReference(this->Tris->NewIterator()); } void operator()(vtkIdType triId, vtkIdType endTriId) { vtkIdType npts; const vtkIdType* tri; vtkCellArrayIterator* cellIter = this->CellIterator.Local(); TIds* triMap = this->TriMap + triId; std::atomic* ptMap = this->PointMap; TIds binIds[3]; for (; triId < endTriId; ++triId, ++triMap) { cellIter->GetCellAtId(triId, npts, tri); binIds[0] = this->BinIds[tri[0]]; binIds[1] = this->BinIds[tri[1]]; binIds[2] = this->BinIds[tri[2]]; // All three points have to be in different bins for triangle insertion if (binIds[0] != binIds[1] && binIds[0] != binIds[2] && binIds[1] != binIds[2]) { *triMap = 1; this->WritePtId(ptMap[binIds[0]], tri[0]); this->WritePtId(ptMap[binIds[1]], tri[1]); this->WritePtId(ptMap[binIds[2]], tri[2]); } else // mark excluded from output { *triMap = 0; } } } // Reduce is required if Initialize() defined. void Reduce() {} }; // Count the number of points in each z-slice of the binning volume. The // resulting slice offsets are used to thread the generation of the output // points. template struct CountPoints { const int* Dims; std::atomic* PointMap; int* SliceOffsets; CountPoints(const int* dims, std::atomic* ptMap, int* sliceOffsets) : Dims(dims) , PointMap(ptMap) , SliceOffsets(sliceOffsets) { } void Initialize() {} void operator()(vtkIdType slice, vtkIdType endSlice) { int binOffset = slice * this->Dims[0] * this->Dims[1]; for (; slice < endSlice; ++slice) { vtkIdType numSlicePts = 0; for (auto j = 0; j < this->Dims[1]; ++j) { for (auto i = 0; i < this->Dims[0]; ++i) { if (this->PointMap[binOffset] != 0) { ++numSlicePts; } ++binOffset; } } this->SliceOffsets[slice] = numSlicePts; } // for all slices in this batch } void Reduce() { // Prefix sum to roll up total point count across all of the slices. TIds numSlicePts, numNewPts = 0; for (auto i = 0; i < this->Dims[2]; ++i) { numSlicePts = this->SliceOffsets[i]; this->SliceOffsets[i] = numNewPts; numNewPts += numSlicePts; } this->SliceOffsets[this->Dims[2]] = numNewPts; } }; // Generate output points; either from bin centers, or from // selecting one of the points in the bin. template struct GenerateBinPoints { int PointGenerationMode; const double* Bounds; const double* Spacing; const int* Dims; int* SliceOffsets; std::atomic* PointMap; PointsT* InPoints; ArrayList* Arrays; float* OutPoints; GenerateBinPoints(int genMode, const double* bounds, const double* spacing, const int* dims, int* sliceOffsets, std::atomic* ptMap, PointsT* inPts, ArrayList* arrays, float* outPts) : PointGenerationMode(genMode) , Bounds(bounds) , Spacing(spacing) , Dims(dims) , SliceOffsets(sliceOffsets) , PointMap(ptMap) , InPoints(inPts) , Arrays(arrays) , OutPoints(outPts) { } void operator()(vtkIdType slice, vtkIdType endSlice) { int binOffset = slice * this->Dims[0] * this->Dims[1]; vtkIdType oldPtId; vtkIdType newPtId = this->SliceOffsets[slice]; float* xOut; double xIn[3]; const auto pts = vtk::DataArrayTupleRange<3>(this->InPoints); for (; slice < endSlice; ++slice) { for (auto j = 0; j < this->Dims[1]; ++j) { for (auto i = 0; i < this->Dims[0]; ++i) { oldPtId = this->PointMap[binOffset]; if (oldPtId != 0) { oldPtId = -(oldPtId + 1); // transform back to non-negative point id xOut = this->OutPoints + 3 * newPtId; if (this->PointGenerationMode == vtkBinnedDecimation::BIN_CENTERS) { xIn[0] = this->Bounds[0] + ((0.5 + static_cast(i)) * this->Spacing[0]); xIn[1] = this->Bounds[2] + ((0.5 + static_cast(j)) * this->Spacing[1]); xIn[2] = this->Bounds[4] + ((0.5 + static_cast(slice)) * this->Spacing[2]); } else // genMode == vtkBinnedDecimation::BIN_POINTS { const auto xp = pts[oldPtId]; xIn[0] = xp[0]; xIn[1] = xp[1]; xIn[2] = xp[2]; } xOut[0] = xIn[0]; xOut[1] = xIn[1]; xOut[2] = xIn[2]; this->PointMap[binOffset] = newPtId; // update to new point id if (this->Arrays) // copy point data if requested { this->Arrays->Copy(oldPtId, newPtId); } newPtId++; } ++binOffset; } } } // for all slices in this batch } }; //---------------------------------------------------------------------------- // Decimation algorithms #2-3 which generates new points for each bin. Either // a bin center point is generated, or one of the points contained in the bin // is selected and copied to the output. template void BinPointsDecimate(int genMode, vtkIdType numPts, PointsT* pts, vtkPointData* inPD, vtkPointData* outPD, vtkIdType numTris, vtkCellArray* tris, vtkCellData* inCD, vtkCellData* outCD, vtkIdType numBins, const int* dims, const double* bounds, const double* spacing, vtkPolyData* output) { // Setup execution. Several arrays are used to transform the data. // The bin id of each point. TIds* binIds = new TIds[numPts]; // Now bin points to generate a bin index for each point. BinPoints binPoints(pts, binIds, dims, bounds, spacing); vtkSMPTools::For(0, numPts, binPoints); // The ptMap is the output point id assigned to each bin (if the bin // contains an output point). Note that multiple, simultaneous writes can // occur to a bin hence the use of atomics. Initialize to zero via {}. Zero // is a problem because a ptId can == zero; as a workaround, we'll // initially use negative ids, and convert to positive ids in the // final composition. std::atomic* ptMap = new std::atomic[numBins] {}; // Is the triangle output? And eventually the offset into the output cell array. TIds* triMap = new TIds[numTris + 1]; // Begin to construct mappings of input points and cells, to output points // and cells. MapOutput mapOutput(binIds, ptMap, tris, triMap); vtkSMPTools::For(0, numTris, mapOutput); // Now generate the new points. First generate new point ids, and then // produce the actual points. int* sliceOffsets = new int[dims[2] + 1]; CountPoints countPts(dims, ptMap, sliceOffsets); vtkSMPTools::For(0, dims[2], countPts); int numNewPts = sliceOffsets[dims[2]]; vtkNew newPts; newPts->SetDataType(VTK_FLOAT); // could be the same type as the input point type newPts->SetNumberOfPoints(numNewPts); ArrayList ptArrays; if (outPD) // copy point data if requested { outPD->CopyAllocate(inPD, numNewPts); ptArrays.AddArrays(numNewPts, inPD, outPD); } GenerateBinPoints genPts(genMode, bounds, spacing, dims, sliceOffsets, ptMap, pts, (outPD != nullptr ? (&ptArrays) : nullptr), vtkFloatArray::FastDownCast(newPts->GetData())->GetPointer(0)); vtkSMPTools::For(0, dims[2], genPts); output->SetPoints(newPts); // Create a mapping of the input triangles to the output triangles. vtkIdType mark, numOutTris = 0; for (vtkIdType triId = 0; triId < numTris; ++triId) { mark = triMap[triId]; triMap[triId] = numOutTris; numOutTris += mark; } triMap[numTris] = numOutTris; // Produce the decimated output. We'll directly create the offset // and connectivity arrays for the output polydata. vtkCellArray* outTrisArray = output->GetPolys(); vtkNew outConn; vtkIdType* outTris = outConn->WritePointer(0, numOutTris * 3); vtkNew outOffsets; vtkIdType* outTriOffsets = outOffsets->WritePointer(0, numOutTris + 1); outTriOffsets[numOutTris] = 3 * numOutTris; ArrayList arrays; if (outCD) // copy cell data if requested { outCD->CopyAllocate(inCD, numOutTris); arrays.AddArrays(numOutTris, inCD, outCD); } GenerateTriangles> genTris( binIds, ptMap, tris, triMap, outTris, outTriOffsets, (outCD != nullptr ? (&arrays) : nullptr)); vtkSMPTools::For(0, numTris, genTris); outTrisArray->SetData(outOffsets, outConn); // Clean up delete[] sliceOffsets; delete[] triMap; delete[] ptMap; delete[] binIds; } //---------------------------------------------------------------------------- // Invoke the decimate algorithm which generates either a selected bin point, // or bin centered point. Depending on the id size, use large 64-bit ids or // 32-bit ids (enhances performance and reduces memory usage). struct BinPointsWorker { template void operator()(DataT* pts, vtkPointData* inPD, vtkPointData* outPD, bool largeIds, int genMode, vtkCellArray* tris, vtkCellData* inCD, vtkCellData* outCD, int* divs, double bounds[6], double spacing[3], vtkPolyData* output) { vtkIdType numPts = pts->GetNumberOfTuples(); vtkIdType numTris = tris->GetNumberOfCells(); vtkIdType numBins = divs[0] * divs[1] * divs[2]; if (!largeIds) { BinPointsDecimate(genMode, numPts, pts, inPD, outPD, numTris, tris, inCD, outCD, numBins, divs, bounds, spacing, output); } else { BinPointsDecimate(genMode, numPts, pts, inPD, outPD, numTris, tris, inCD, outCD, numBins, divs, bounds, spacing, output); } } }; //========================== 4) Generate points from BIN_AVERAGES ============ // Traverse cells and mark output triangles. Sort points based on the bins // they fall into. We need to keep track of the inserted points in each bin, // which are combined later to produce an average position. //------------------------------------------------------------------------------ // Sort bins with associated bin ids. This creates runs of points for each // bin, which are later averaged to create a new point in each bin. template struct BinTuple { TIds PtId; // originating point id TIds Bin; // i-j-k index into bin space // Operator< used to support the sort operation. Just sort on bin // id; points within a bin can be in any order. bool operator<(const BinTuple& tuple) const { return (Bin < tuple.Bin ? true : false); } }; template struct BinPointTuples : public BinPoints { BinTuple* BinTuples; BinPointTuples(PointsT* pts, BinTuple* binTuples, const int* dims, const double* bounds, const double* spacing) : BinPoints(pts, nullptr, dims, bounds, spacing) , BinTuples(binTuples) { } void operator()(vtkIdType ptId, vtkIdType endPtId) { const auto points = vtk::DataArrayTupleRange<3>(this->Points, ptId, endPtId); double x[3]; BinTuple* bins = this->BinTuples + ptId; for (const auto tuple : points) { (*bins).PtId = ptId++; x[0] = static_cast(tuple[0]); x[1] = static_cast(tuple[1]); x[2] = static_cast(tuple[2]); (*bins).Bin = this->GetBinIndex(x); ++bins; } } }; template struct MarkBinnedTris { const BinTuple* BinTuples; vtkCellArray* Tris; TIds* TriMap; vtkSMPThreadLocal> CellIterator; MarkBinnedTris(BinTuple* bt, vtkCellArray* tris, TIds* triMap) : BinTuples(bt) , Tris(tris) , TriMap(triMap) { } void Initialize() { this->CellIterator.Local().TakeReference(this->Tris->NewIterator()); } void operator()(vtkIdType triId, vtkIdType endTriId) { vtkIdType npts; const vtkIdType* tri; vtkCellArrayIterator* cellIter = this->CellIterator.Local(); TIds* triMap = this->TriMap + triId; TIds binIds[3]; for (; triId < endTriId; ++triId, ++triMap) { cellIter->GetCellAtId(triId, npts, tri); binIds[0] = this->BinTuples[tri[0]].Bin; binIds[1] = this->BinTuples[tri[1]].Bin; binIds[2] = this->BinTuples[tri[2]].Bin; // All three points have to be in different bins for triangle insertion if (binIds[0] != binIds[1] && binIds[0] != binIds[2] && binIds[1] != binIds[2]) { *triMap = 1; } else // mark excluded from output { *triMap = 0; } } } void Reduce() {} }; // Produce the output triangles from the bin tuples. template struct BinAveTriangles { const BinTuple* BinTuples; vtkCellArray* Tris; vtkSMPThreadLocal> CellIterator; const TIds* TriMap; vtkIdType* OutTris; vtkIdType* OutTriOffsets; ArrayList* Arrays; BinAveTriangles(const BinTuple* bt, vtkCellArray* tris, TIds* triMap, vtkIdType* outTris, vtkIdType* outTriOffsets, ArrayList* arrays) : BinTuples(bt) , Tris(tris) , TriMap(triMap) , OutTris(outTris) , OutTriOffsets(outTriOffsets) , Arrays(arrays) { } void Initialize() { this->CellIterator.Local().TakeReference(this->Tris->NewIterator()); } void operator()(vtkIdType triId, vtkIdType endTriId) { const BinTuple* binTuples = this->BinTuples; vtkIdType npts; const vtkIdType* tri; vtkCellArrayIterator* cellIter = this->CellIterator.Local(); const TIds* triMap = this->TriMap; vtkIdType *outTris = this->OutTris, *outTri; vtkIdType *outTriOffsets = this->OutTriOffsets, *outOffsets; for (; triId < endTriId; ++triId) { if ((triMap[triId + 1] - triMap[triId]) > 0) // spit out triangle { cellIter->GetCellAtId(triId, npts, tri); outOffsets = outTriOffsets + triMap[triId]; *outOffsets = triMap[triId] * 3; outTri = outTris + *outOffsets; outTri[0] = binTuples[tri[0]].Bin; // set the bin id outTri[1] = binTuples[tri[1]].Bin; outTri[2] = binTuples[tri[2]].Bin; if (this->Arrays) // copy cell data if requested { this->Arrays->Copy(triId, triMap[triId]); } } } } void Reduce() {} }; // Generate the output triangles by rewriting bin ids into new point ids template struct GenerateAveTriangles { const BinTuple* BinTuples; const TIds* Offsets; vtkIdType* OutTris; GenerateAveTriangles(const BinTuple* bt, TIds* offsets, vtkIdType* outTris) : BinTuples(bt) , Offsets(offsets) , OutTris(outTris) { } void operator()(vtkIdType triId, vtkIdType endTriId) { const BinTuple* binTuples = this->BinTuples; const TIds* offsets = this->Offsets; vtkIdType* outTri = this->OutTris + 3 * triId; for (; triId < endTriId; ++triId, outTri += 3) { outTri[0] = (*(binTuples + offsets[outTri[0]])).PtId; outTri[1] = (*(binTuples + offsets[outTri[1]])).PtId; outTri[2] = (*(binTuples + offsets[outTri[2]])).PtId; } } }; // A clever way to build offsets in parallel. Basically each thread builds // offsets across a range of the sorted map. template struct MapOffsets { const BinTuple* BinTuples; TIds* Offsets; TIds NumPts; TIds NumBins; TIds BatchSize; MapOffsets(BinTuple* bt, TIds* offsets, TIds numPts, TIds numBins, TIds numBatches) : BinTuples(bt) , Offsets(offsets) , NumPts(numPts) , NumBins(numBins) { this->BatchSize = static_cast(ceil(static_cast(numPts) / numBatches)); } // Traverse sorted points (i.e., tuples) and update bin offsets. void operator()(vtkIdType batch, vtkIdType batchEnd) { TIds* offsets = this->Offsets; const BinTuple* curPt = this->BinTuples + batch * this->BatchSize; const BinTuple* endBatchPt = this->BinTuples + batchEnd * this->BatchSize; const BinTuple* endPt = this->BinTuples + this->NumPts; const BinTuple* prevPt; endBatchPt = (endBatchPt > endPt ? endPt : endBatchPt); // Special case at the very beginning of the bin tuples array. If // the first point is in bin# N, then all bins up and including // N must refer to the first point. if (curPt == this->BinTuples) { prevPt = this->BinTuples; std::fill_n(offsets, curPt->Bin + 1, 0); // offset to the first points } // at the very beginning of the map (sorted points array) // We are entering this functor somewhere in the interior of the // mapped points array. All we need to do is point to the entry // position because we are interested only in prevPt->Bin. else { prevPt = curPt; } // else in the middle of a batch // Okay we have a starting point for a bin run. Now we can begin // filling in the offsets in this batch. A previous thread should // have/will have completed the previous and subsequent runs outside // of the [batch,batchEnd) range for (curPt = prevPt; curPt < endBatchPt;) { for (; curPt->Bin == prevPt->Bin && curPt <= endBatchPt; ++curPt) { ; // advance } // Fill in any gaps in the offset array if (curPt < endPt) // still within range of points { std::fill_n(offsets + prevPt->Bin + 1, curPt->Bin - prevPt->Bin, curPt - this->BinTuples); prevPt = curPt; } else // at the end of the points { std::fill_n( offsets + prevPt->Bin + 1, this->NumBins - prevPt->Bin - 1, curPt - this->BinTuples); } } // for all batches in this range } // operator() }; // Count the number of averaged points in each z-slice of the binning volume. // The resulting offsets are used to thread the generation of the output // points. template struct CountAvePts { const int* Dims; const TIds* Offsets; int* SliceOffsets; CountAvePts(const int* dims, const TIds* offsets, int* sliceOffsets) : Dims(dims) , Offsets(offsets) , SliceOffsets(sliceOffsets) { } void Initialize() {} void operator()(vtkIdType slice, vtkIdType endSlice) { int binNum = slice * this->Dims[0] * this->Dims[1]; for (; slice < endSlice; ++slice) { vtkIdType numSlicePts = 0; for (auto j = 0; j < this->Dims[1]; ++j) { for (auto i = 0; i < this->Dims[0]; ++i) { if ((this->Offsets[binNum + 1] - this->Offsets[binNum]) > 0) { ++numSlicePts; } ++binNum; } } this->SliceOffsets[slice] = numSlicePts; } // for all slices in this batch } void Reduce() { // Prefix sum to roll up total point count in each slice TIds numSlicePts, numNewPts = 0; for (auto i = 0; i < this->Dims[2]; ++i) { numSlicePts = this->SliceOffsets[i]; this->SliceOffsets[i] = numNewPts; numNewPts += numSlicePts; } this->SliceOffsets[this->Dims[2]] = numNewPts; } }; // Generate points from the binning -- in this case from the average // position of all points in each bin. template struct GenerateAveBinPoints { const int* Dims; PointsT* InPoints; const int* SliceOffsets; BinTuple* BinTuples; const TIds* Offsets; ArrayList* Arrays; float* OutPoints; vtkSMPThreadLocal> PtIds; GenerateAveBinPoints(const int* dims, PointsT* inPts, const int* sliceOffsets, BinTuple* binTuples, const TIds* offsets, ArrayList* arrays, float* outPts) : Dims(dims) , InPoints(inPts) , SliceOffsets(sliceOffsets) , BinTuples(binTuples) , Offsets(offsets) , Arrays(arrays) , OutPoints(outPts) { } void operator()(vtkIdType slice, vtkIdType endSlice) { int binNum = slice * this->Dims[0] * this->Dims[1]; vtkIdType newPtId = this->SliceOffsets[slice]; float* xOut; double xAve[3]; const auto pts = vtk::DataArrayTupleRange<3>(this->InPoints); BinTuple* binTuples = this->BinTuples; const TIds* offsets = this->Offsets; BinTuple* pIds; TIds pId; std::vector v = this->PtIds.Local(); for (; slice < endSlice; ++slice) { for (auto j = 0; j < this->Dims[1]; ++j) { for (auto i = 0; i < this->Dims[0]; ++i) { TIds npts = offsets[binNum + 1] - offsets[binNum]; if (npts > 0) { // Average the points in the bin xAve[0] = xAve[1] = xAve[2] = 0.0; pIds = binTuples + offsets[binNum]; v.resize(npts); for (auto idx = 0; idx < npts; ++idx) { pId = (*(pIds + idx)).PtId; v[idx] = pId; const auto p = pts[pId]; xAve[0] += p[0]; xAve[1] += p[1]; xAve[2] += p[2]; } xAve[0] /= static_cast(npts); xAve[1] /= static_cast(npts); xAve[2] /= static_cast(npts); xOut = this->OutPoints + 3 * newPtId; xOut[0] = xAve[0]; xOut[1] = xAve[1]; xOut[2] = xAve[2]; if (this->Arrays) // average point data if requested { this->Arrays->Average(npts, v.data(), newPtId); } (*pIds).PtId = newPtId; // update to new point id newPtId++; } ++binNum; } // for i } // for j } // for all slices in this batch } }; //---------------------------------------------------------------------------- // Decimation algorithm which generates new points for each bin by averaging // the point coordinates and point attributes in each bin. This algorithm // typically produces the best results. For small numbers of bins it can be // a tad slower, but generally scales better as the number of bins is // increased. template void AvePointsDecimate(vtkIdType numPts, PointsT* pts, vtkPointData* inPD, vtkPointData* outPD, vtkIdType numTris, vtkCellArray* tris, vtkCellData* inCD, vtkCellData* outCD, vtkIdType numBins, const int* dims, const double* bounds, const double* spacing, vtkPolyData* output) { // Setup execution. Several arrays are used to transform the data. // Define the bin id and associated point id of each point. BinTuple* binTuples = new BinTuple[numPts]; // Now bin points to generate a bin index for each point. BinPointTuples binPoints(pts, binTuples, dims, bounds, spacing); vtkSMPTools::For(0, numPts, binPoints); // Initially, triMap indicates which triangles are output. And then // contains the offsets into the output triangles array. TIds* triMap = new TIds[numTris + 1]; // Begin to construct mappings of input points and cells, to output points // and cells. First identify the triangles to be sent to the output. MarkBinnedTris markBinnedTris(binTuples, tris, triMap); vtkSMPTools::For(0, numTris, markBinnedTris); // Create a mapping of the input triangles to the output triangles. vtkIdType mark, numOutTris = 0; for (vtkIdType triId = 0; triId < numTris; ++triId) { mark = triMap[triId]; triMap[triId] = numOutTris; numOutTris += mark; } triMap[numTris] = numOutTris; // Generate the cell output (decimated list of triangles), with the // triangle connectivity based on bin ids (not point ids). We'll directly // create the offet and connectivity arrays for the output polydata. vtkCellArray* outTrisArray = output->GetPolys(); vtkNew outConn; vtkIdType* outTris = outConn->WritePointer(0, numOutTris * 3); vtkNew outOffsets; vtkIdType* outTriOffsets = outOffsets->WritePointer(0, numOutTris + 1); outTriOffsets[numOutTris] = 3 * numOutTris; ArrayList arrays; if (outCD) // copy cell data if requested { outCD->CopyAllocate(inCD, numOutTris); arrays.AddArrays(numOutTris, inCD, outCD); } BinAveTriangles binTris( binTuples, tris, triMap, outTris, outTriOffsets, (outCD != nullptr ? (&arrays) : nullptr)); vtkSMPTools::For(0, numTris, binTris); outTrisArray->SetData(outOffsets, outConn); // Now sort the bin tuples by bin id. This is the first step in // transforming the input points to new points. The sort operation // will organize points into lists per bin. vtkSMPTools::Sort(binTuples, binTuples + numPts); // To rapidly (random) access the bins, we have to build an offset array // into the sorted bin tuples (i.e., runs of points in each bin). TIds* offsets = new TIds[numBins + 1]; TIds numBatches = (numPts < 10000 ? 1 : 100); // totally arbitrary MapOffsets offMapper(binTuples, offsets, numPts, numBins, numBatches); vtkSMPTools::For(0, numBatches, offMapper); offsets[numBins] = numPts; // Now to generate the new points, build an offset array that basically // represents the number of new points generated in each z-slice. First we // have to count the new points, and then accumulate them with a prefix // sum. For convenience, this is done on a bin slice-by-slice manner. int* sliceOffsets = new int[dims[2] + 1]; CountAvePts countPts(dims, offsets, sliceOffsets); vtkSMPTools::For(0, dims[2], countPts); int numNewPts = sliceOffsets[dims[2]]; // The points (and optional point attributes) are generated by averaging // the contributions of all points in each bin. A new point is generated // and its id is placed into the bin tuples array (needed for final // generation of the triangles). // Should output point type be the same as the input point type? vtkNew newPts; newPts->SetDataType(VTK_FLOAT); newPts->SetNumberOfPoints(numNewPts); ArrayList ptArrays; if (outPD) // copy point data if requested { outPD->CopyAllocate(inPD, numNewPts); ptArrays.AddArrays(numNewPts, inPD, outPD); } // Do the core work of averaging point coordinates and attributes. GenerateAveBinPoints genPts(dims, pts, sliceOffsets, binTuples, offsets, (outPD != nullptr ? (&ptArrays) : nullptr), vtkFloatArray::FastDownCast(newPts->GetData())->GetPointer(0)); vtkSMPTools::For(0, dims[2], genPts); output->SetPoints(newPts); // Finally map the triangle connectivity list to the new point ids. GenerateAveTriangles genAveTris(binTuples, offsets, outTris); vtkSMPTools::For(0, numOutTris, genAveTris); // Clean up delete[] binTuples; delete[] triMap; delete[] offsets; delete[] sliceOffsets; } //---------------------------------------------------------------------------- // Invoke the decimate algorithm which generates an averaged point from the // points within a bin. struct AvePointsWorker { template void operator()(DataT* pts, vtkPointData* inPD, vtkPointData* outPD, bool largeIds, vtkCellArray* tris, vtkCellData* inCD, vtkCellData* outCD, int* divs, double bounds[6], double spacing[3], vtkPolyData* output) { vtkIdType numPts = pts->GetNumberOfTuples(); vtkIdType numTris = tris->GetNumberOfCells(); vtkIdType numBins = divs[0] * divs[1] * divs[2]; if (!largeIds) { AvePointsDecimate(numPts, pts, inPD, outPD, numTris, tris, inCD, outCD, numBins, divs, bounds, spacing, output); } else { AvePointsDecimate(numPts, pts, inPD, outPD, numTris, tris, inCD, outCD, numBins, divs, bounds, spacing, output); } } }; } // anonymous namespace //---------------------------------------------------------------------------- // Construct with default NumberOfDivisions to 256, DivisionSpacing to 1 // in all (x,y,z) directions. AutoAdjustNumberOfDivisions is set to ON. // ComputeNumberOfDivisions to OFF. vtkBinnedDecimation::vtkBinnedDecimation() { this->Bounds[0] = this->Bounds[1] = this->Bounds[2] = 0.0; this->Bounds[3] = this->Bounds[4] = this->Bounds[5] = 0.0; this->NumberOfXDivisions = this->NumberOfDivisions[0] = 256; this->NumberOfYDivisions = this->NumberOfDivisions[1] = 256; this->NumberOfZDivisions = this->NumberOfDivisions[2] = 256; this->AutoAdjustNumberOfDivisions = true; this->ComputeNumberOfDivisions = 0; this->DivisionOrigin[0] = 0.0; this->DivisionOrigin[1] = 0.0; this->DivisionOrigin[2] = 0.0; this->DivisionSpacing[0] = 1.0; this->DivisionSpacing[1] = 1.0; this->DivisionSpacing[2] = 1.0; this->PointGenerationMode = BIN_POINTS; this->ProducePointData = true; this->ProduceCellData = false; this->LargeIds = false; } //---------------------------------------------------------------------------- vtkBinnedDecimation::~vtkBinnedDecimation() {} //---------------------------------------------------------------------------- // Use the same approach as vtkQuadricClustering (which is a bit of a mess but // we want consistent behavior between the two classes). void vtkBinnedDecimation::ConfigureBinning(vtkPolyData* input, vtkIdType numPts) { // Prepare the bounds. Use the faster vtkPoints::GetBounds() because the // general vtkPolyData::GetBounds() is much slower. double bounds[6]; input->GetPoints()->GetBounds(bounds); for (vtkIdType i = 0; i < 6; ++i) { this->Bounds[i] = bounds[i]; } // Estimate the number of divisions based on the number of points in the // input. (To minimize chance of overflow, force math in vtkIdType type, // which is sometimes bigger than int, and never smaller.) vtkIdType target = numPts; vtkIdType numDiv = static_cast(this->NumberOfXDivisions) * this->NumberOfYDivisions * this->NumberOfZDivisions / 2; // This particular implementation is limited to 2^31 (VTK_INT_MAX) bins. // This is to manage memory allocation and simplify the algorithm. if (this->AutoAdjustNumberOfDivisions && numDiv > target) { double factor = pow(((double)numDiv / (double)target), 0.33333); this->NumberOfDivisions[0] = this->NumberOfXDivisions = (int)(0.5 + (double)(this->NumberOfXDivisions) / factor); this->NumberOfDivisions[1] = this->NumberOfYDivisions = (int)(0.5 + (double)(this->NumberOfYDivisions) / factor); this->NumberOfDivisions[2] = this->NumberOfZDivisions = (int)(0.5 + (double)(this->NumberOfZDivisions) / factor); } else { this->NumberOfDivisions[0] = this->NumberOfXDivisions; this->NumberOfDivisions[1] = this->NumberOfYDivisions; this->NumberOfDivisions[2] = this->NumberOfZDivisions; } if (this->ComputeNumberOfDivisions) { // Extend the bounds so that it will not produce fractions of bins. double x, y, z; x = floor((bounds[0] - this->DivisionOrigin[0]) / this->DivisionSpacing[0]); y = floor((bounds[2] - this->DivisionOrigin[1]) / this->DivisionSpacing[1]); z = floor((bounds[4] - this->DivisionOrigin[2]) / this->DivisionSpacing[2]); this->Bounds[0] = this->DivisionOrigin[0] + (x * this->DivisionSpacing[0]); this->Bounds[2] = this->DivisionOrigin[1] + (y * this->DivisionSpacing[1]); this->Bounds[4] = this->DivisionOrigin[2] + (z * this->DivisionSpacing[2]); x = ceil((bounds[1] - this->Bounds[0]) / this->DivisionSpacing[0]); y = ceil((bounds[3] - this->Bounds[2]) / this->DivisionSpacing[1]); z = ceil((bounds[5] - this->Bounds[4]) / this->DivisionSpacing[2]); this->Bounds[1] = this->Bounds[0] + (x * this->DivisionSpacing[0]); this->Bounds[3] = this->Bounds[2] + (y * this->DivisionSpacing[1]); this->Bounds[5] = this->Bounds[4] + (z * this->DivisionSpacing[2]); this->NumberOfDivisions[0] = static_cast(x); this->NumberOfDivisions[1] = static_cast(y); this->NumberOfDivisions[2] = static_cast(z); vtkLog(INFO, ""Auto adjusted to Divisions("" << this->NumberOfDivisions[0] << "","" << this->NumberOfDivisions[1] << "","" << this->NumberOfDivisions[2] << "")""); } else { this->DivisionOrigin[0] = bounds[0]; this->DivisionOrigin[1] = bounds[2]; this->DivisionOrigin[2] = bounds[4]; this->DivisionSpacing[0] = (bounds[1] - bounds[0]) / this->NumberOfDivisions[0]; this->DivisionSpacing[1] = (bounds[3] - bounds[2]) / this->NumberOfDivisions[1]; this->DivisionSpacing[2] = (bounds[5] - bounds[4]) / this->NumberOfDivisions[2]; } vtkBoundingBox::ClampDivisions(VTK_INT_MAX, this->NumberOfDivisions); } //---------------------------------------------------------------------------- int vtkBinnedDecimation::RequestData(vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // get the info objects vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); // get the input and output vtkPolyData* input = nullptr; if (inInfo) { input = vtkPolyData::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); } vtkPolyData* output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); // Ensure there is some input vtkIdType numPts; if (!input || (numPts = input->GetNumberOfPoints()) < 1) { vtkLog(INFO, ""Empty input (no points).""); return 1; } // Do a quick check as to whether triangles are available. vtkCellArray* inTris = input->GetPolys(); vtkIdType numTris, triSize; if (inTris == nullptr || (numTris = inTris->GetNumberOfCells()) < 1 || (triSize = inTris->GetNumberOfConnectivityEntries()) != numTris * 4) { vtkLog(INFO, ""Empty input, or non-triangles in input.""); return 1; } // Setup the binning (divisions,origin,spacing). this->ConfigureBinning(input, numPts); vtkIdType numBins = static_cast(this->NumberOfDivisions[0]) * this->NumberOfDivisions[1] * this->NumberOfDivisions[2]; // Grab relevant information vtkPoints* inPts = input->GetPoints(); vtkPointData* inPD = input->GetPointData(); vtkPointData* outPD = (this->ProducePointData ? output->GetPointData() : nullptr); vtkCellData* inCD = input->GetCellData(); vtkCellData* outCD = (this->ProduceCellData ? output->GetCellData() : nullptr); // Prepare the triangle output. vtkNew outTris; output->SetPolys(outTris); // Determine what type of ids are needed: smaller id types save a lot of // memory. this->LargeIds = ((numBins > VTK_INT_MAX || numPts > VTK_INT_MAX || numTris > VTK_INT_MAX) ? true : false); // Fast path: dispatch to real point types using vtkArrayDispatch::Reals; // There are four possible algorithms to take depending on the desired // output. Algorithms 2-3 are very similar and combined here. if (this->PointGenerationMode == vtkBinnedDecimation::INPUT_POINTS) { // Algorithm 1: reuse input points output->SetPoints(inPts); if (outPD) { outPD->PassData(inPD); } using PointReuseDispatch = vtkArrayDispatch::DispatchByValueType; PointReuseWorker deciWorker; if (!PointReuseDispatch::Execute(inPts->GetData(), deciWorker, this->LargeIds, inTris, inCD, outCD, this->NumberOfDivisions, this->Bounds, this->DivisionSpacing, output)) { // Fallback to slowpath for other point types deciWorker(inPts->GetData(), this->LargeIds, inTris, inCD, outCD, this->NumberOfDivisions, this->Bounds, this->DivisionSpacing, output); } } // Algorithms 2 & 3: generate new points: from selecting a point, or bin centers else if (this->PointGenerationMode == vtkBinnedDecimation::BIN_CENTERS || this->PointGenerationMode == vtkBinnedDecimation::BIN_POINTS) { using BinPointsDispatch = vtkArrayDispatch::DispatchByValueType; BinPointsWorker deciWorker; if (!BinPointsDispatch::Execute(inPts->GetData(), deciWorker, inPD, outPD, this->LargeIds, this->PointGenerationMode, inTris, inCD, outCD, this->NumberOfDivisions, this->Bounds, this->DivisionSpacing, output)) { // Fallback to slowpath for other point types deciWorker(inPts->GetData(), inPD, outPD, this->LargeIds, this->PointGenerationMode, inTris, inCD, outCD, this->NumberOfDivisions, this->Bounds, this->DivisionSpacing, output); } } // Algorithm 4: average points in bins else // if ( this->PointGenerationMode == vtkBinnedDecimation::BIN_AVERAGE ) { using AvePointsDispatch = vtkArrayDispatch::DispatchByValueType; AvePointsWorker deciWorker; if (!AvePointsDispatch::Execute(inPts->GetData(), deciWorker, inPD, outPD, this->LargeIds, inTris, inCD, outCD, this->NumberOfDivisions, this->Bounds, this->DivisionSpacing, output)) { // Fallback to slowpath for other point types deciWorker(inPts->GetData(), inPD, outPD, this->LargeIds, inTris, inCD, outCD, this->NumberOfDivisions, this->Bounds, this->DivisionSpacing, output); } } return 1; } //---------------------------------------------------------------------------- void vtkBinnedDecimation::SetNumberOfDivisions(int div0, int div1, int div2) { this->NumberOfDivisions[0] = div0; this->NumberOfDivisions[1] = div1; this->NumberOfDivisions[2] = div2; this->SetNumberOfXDivisions(div0); this->SetNumberOfYDivisions(div1); this->SetNumberOfZDivisions(div2); } //---------------------------------------------------------------------------- void vtkBinnedDecimation::SetNumberOfXDivisions(int num) { if (this->NumberOfXDivisions == num && this->ComputeNumberOfDivisions == 0) { return; } if (num < 1) { vtkLog(ERROR, ""You cannot use less than one division.""); return; } this->Modified(); this->NumberOfXDivisions = num; this->ComputeNumberOfDivisions = 0; } //---------------------------------------------------------------------------- void vtkBinnedDecimation::SetNumberOfYDivisions(int num) { if (this->NumberOfYDivisions == num && this->ComputeNumberOfDivisions == 0) { return; } if (num < 1) { vtkLog(ERROR, ""You cannot use less than one division.""); return; } this->Modified(); this->NumberOfYDivisions = num; this->ComputeNumberOfDivisions = 0; } //---------------------------------------------------------------------------- void vtkBinnedDecimation::SetNumberOfZDivisions(int num) { if (this->NumberOfZDivisions == num && this->ComputeNumberOfDivisions == 0) { return; } if (num < 1) { vtkLog(ERROR, ""You cannot use less than one division.""); return; } this->Modified(); this->NumberOfZDivisions = num; this->ComputeNumberOfDivisions = 0; } //---------------------------------------------------------------------------- int* vtkBinnedDecimation::GetNumberOfDivisions() { static int divs[3]; this->GetNumberOfDivisions(divs); return divs; } //---------------------------------------------------------------------------- void vtkBinnedDecimation::GetNumberOfDivisions(int divs[3]) { divs[0] = this->NumberOfXDivisions; divs[1] = this->NumberOfYDivisions; divs[2] = this->NumberOfZDivisions; } //---------------------------------------------------------------------------- void vtkBinnedDecimation::SetDivisionOrigin(double x, double y, double z) { if (this->ComputeNumberOfDivisions && this->DivisionOrigin[0] == x && this->DivisionOrigin[1] == y && this->DivisionOrigin[2] == z) { return; } this->Modified(); this->DivisionOrigin[0] = x; this->DivisionOrigin[1] = y; this->DivisionOrigin[2] = z; this->ComputeNumberOfDivisions = 1; } //---------------------------------------------------------------------------- void vtkBinnedDecimation::SetDivisionSpacing(double x, double y, double z) { if (this->ComputeNumberOfDivisions && this->DivisionSpacing[0] == x && this->DivisionSpacing[1] == y && this->DivisionSpacing[2] == z) { return; } if (x <= 0) { vtkLog(ERROR, ""Spacing (x) should be larger than 0.0, setting to 1.0""); x = 1.0; } if (y <= 0) { vtkLog(ERROR, ""Spacing (x) should be larger than 0.0, setting to 1.0""); y = 1.0; } if (z <= 0) { vtkLog(ERROR, ""Spacing (x) should be larger than 0.0, setting to 1.0""); z = 1.0; } this->Modified(); this->DivisionSpacing[0] = x; this->DivisionSpacing[1] = y; this->DivisionSpacing[2] = z; this->ComputeNumberOfDivisions = 1; } //---------------------------------------------------------------------------- int vtkBinnedDecimation::FillInputPortInformation(int port, vtkInformation* info) { int retval = this->Superclass::FillInputPortInformation(port, info); info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1); return retval; } //---------------------------------------------------------------------------- void vtkBinnedDecimation::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << ""Bounds: "" << this->Bounds[0] << "" "" << this->Bounds[1] << "" "" << this->Bounds[2] << "" "" << this->Bounds[3] << "" "" << this->Bounds[4] << "" "" << this->Bounds[5] << ""\\n""; if (this->ComputeNumberOfDivisions) { os << indent << ""Using Spacing and Origin to construct bins\\n""; } else { os << indent << ""Using input bounds and NumberOfDivisions to construct bins\\n""; } os << indent << ""Division Spacing: "" << this->DivisionSpacing[0] << "", "" << this->DivisionSpacing[1] << "", "" << this->DivisionSpacing[2] << endl; os << indent << ""Division Origin: "" << this->DivisionOrigin[0] << "", "" << this->DivisionOrigin[1] << "", "" << this->DivisionOrigin[2] << endl; os << indent << ""Number of X Divisions: "" << this->NumberOfXDivisions << ""\\n""; os << indent << ""Number of Y Divisions: "" << this->NumberOfYDivisions << ""\\n""; os << indent << ""Number of Z Divisions: "" << this->NumberOfZDivisions << ""\\n""; os << indent << ""Auto Adjust Number Of Divisions: "" << (this->AutoAdjustNumberOfDivisions ? ""On\\n"" : ""Off\\n""); os << indent << ""Point Generation Mode :"" << this->PointGenerationMode << endl; os << indent << ""Pass Point Data : "" << this->ProducePointData << endl; os << indent << ""Produce Cell Data : "" << this->ProduceCellData << endl; } ",16267,True,3125.1818781553825,median "== [[BlockManager]] BlockManager -- Key-Value Store of Blocks of Data `BlockManager` is a key-value store of blocks of data (*block storage*) identified by a block ID. `BlockManager` acts as a local cache that runs on every node in a Spark cluster, i.e. the link:spark-driver.adoc[driver] and link:spark-Executor.adoc[executors]. `BlockManager` provides interface for uploading and fetching blocks both locally and remotely using various stores, i.e. <>. `BlockManager` is <> exclusively when `SparkEnv` is link:spark-SparkEnv.adoc#create-BlockManager[created] (for the driver and executors). While being created, `BlockManager` gets a <>, <>, <> and <> (that it immediately wires together, i.e. `BlockInfoManager` with `MemoryStore` and `DiskStore` with `DiskBlockManager`). [[futureExecutionContext]] `BlockManager` uses a Scala https://www.scala-lang.org/api/current/scala/concurrent/ExecutionContextExecutorService.html[ExecutionContextExecutorService] to execute *FIXME* asynchronously (on a thread pool with *block-manager-future* prefix and maximum of 128 threads). The common idiom in Spark to access a `BlockManager` regardless of a location, i.e. the driver or executors, is through link:spark-SparkEnv.adoc#get[SparkEnv]: [source, scala] ---- // BlockManager is a private[spark] class // so the following has to be under org.apache.spark package // e.g. package org.apache.spark import org.apache.spark.storage.BlockManager val bm: BlockManager = SparkEnv.get.blockManager ---- `BlockManager` is a link:spark-BlockDataManager.adoc[BlockDataManager], i.e. manages the storage for blocks that can represent cached RDD partitions, intermediate shuffle outputs, broadcasts, etc. `BlockManager` is a link:spark-BlockEvictionHandler.adoc[BlockEvictionHandler] that can <> if required. *Cached blocks* are blocks with non-zero sum of memory and disk sizes. TIP: Use link:spark-webui.adoc[Web UI], esp. link:spark-webui-storage.adoc[Storage] and link:spark-webui-executors.adoc[Executors] tabs, to monitor the memory used. TIP: Use link:spark-submit.adoc[spark-submit]'s command-line options, i.e. link:spark-submit.adoc#driver-memory[--driver-memory] for the driver and link:spark-submit.adoc#executor-memory[--executor-memory] for executors or their equivalents as Spark properties, i.e. link:spark-submit.adoc#spark.executor.memory[spark.executor.memory] and link:spark-submit.adoc#spark_driver_memory[spark.driver.memory], to control the memory for storage memory. A <> when a link:spark-SparkEnv.adoc#create[Spark application starts] and must be <> before it is fully operable. When <>, `BlockManager` uses link:spark-ShuffleClient-ExternalShuffleClient.adoc[ExternalShuffleClient] to read other executors' shuffle files. [[metrics]] `BlockManager` uses link:spark-BlockManager-BlockManagerSource.adoc[BlockManagerSource] to report metrics under the name *BlockManager*. [[internal-properties]] .BlockManager's Internal Properties [cols=""1,1,2"",options=""header"",width=""100%""] |=== | Name | Initial Value | Description | `blockInfoManager` | FIXME | [[blockInfoManager]] link:spark-BlockInfoManager.adoc[BlockInfoManager] for...FIXME | `diskStore` | FIXME | [[diskStore]] link:spark-DiskStore.adoc[DiskStore] for...FIXME | `diskBlockManager` | FIXME | [[diskBlockManager]] link:spark-DiskBlockManager.adoc[DiskBlockManager] for...FIXME | `maxMemory` | Total available link:spark-MemoryManager.adoc#maxOnHeapStorageMemory[on-heap] and link:spark-MemoryManager.adoc#maxOffHeapStorageMemory[off-heap] memory for storage (in bytes) | [[maxMemory]] Total maximum value that `BlockManager` can ever possibly use (that depends on <> and may vary over time). | `maxOffHeapMemory` | | [[maxOffHeapMemory]] | `maxOnHeapMemory` | | [[maxOnHeapMemory]] | `memoryStore` | | [[memoryStore]] link:spark-MemoryStore.adoc[MemoryStore] (with the <>, the <>, <> and this `BlockManager` as the link:spark-BlockEvictionHandler.adoc[BlockEvictionHandler]) |=== [[logging]] [TIP] ==== Enable `INFO`, `DEBUG` or `TRACE` logging level for `org.apache.spark.storage.BlockManager` logger to see what happens inside. Add the following line to `conf/log4j.properties`: ``` log4j.logger.org.apache.spark.storage.BlockManager=TRACE ``` Refer to link:spark-logging.adoc[Logging]. ==== [TIP] ==== You may want to shut off WARN messages being printed out about the current state of blocks using the following line to cut the noise: ``` log4j.logger.org.apache.spark.storage.BlockManager=OFF ``` ==== === [[getLocations]] `getLocations` Method CAUTION: FIXME === [[blockIdsToHosts]] `blockIdsToHosts` Method CAUTION: FIXME === [[getLocationBlockIds]] `getLocationBlockIds` Method CAUTION: FIXME === [[getPeers]] `getPeers` Method CAUTION: FIXME === [[releaseAllLocksForTask]] `releaseAllLocksForTask` Method CAUTION: FIXME === [[stop]] Stopping BlockManager -- `stop` Method [source, scala] ---- stop(): Unit ---- `stop`...FIXME NOTE: `stop` is used exclusively when `SparkEnv` is requested to link:spark-SparkEnv.adoc#stop[stop]. === [[getMatchingBlockIds]] Getting IDs of Existing Blocks (For a Given Filter) -- `getMatchingBlockIds` Method [source, scala] ---- getMatchingBlockIds(filter: BlockId => Boolean): Seq[BlockId] ---- `getMatchingBlockIds`...FIXME NOTE: `getMatchingBlockIds` is used exclusively when `BlockManagerSlaveEndpoint` is requested to link:spark-blockmanager-BlockManagerSlaveEndpoint.adoc#GetMatchingBlockIds[handle a GetMatchingBlockIds message]. === [[getLocalValues]] `getLocalValues` Method [source, scala] ---- getLocalValues(blockId: BlockId): Option[BlockResult] ---- `getLocalValues`...FIXME Internally, when `getLocalValues` is executed, you should see the following DEBUG message in the logs: ``` DEBUG BlockManager: Getting local block [blockId] ``` `getLocalValues` link:spark-BlockInfoManager.adoc#lockForReading[obtains a read lock for `blockId`]. When no `blockId` block was found, you should see the following DEBUG message in the logs and `getLocalValues` returns ""nothing"" (i.e. `NONE`). ``` DEBUG Block [blockId] was not found ``` When the `blockId` block was found, you should see the following DEBUG message in the logs: ``` DEBUG Level for block [blockId] is [level] ``` If `blockId` block has memory level and link:spark-MemoryStore.adoc#contains[is registered in `MemoryStore`], `getLocalValues` returns a <> as `Memory` read method and with a `CompletionIterator` for an interator: 1. link:spark-MemoryStore.adoc#getValues[Values iterator from `MemoryStore` for `blockId`] for ""deserialized"" persistence levels. 2. Iterator from link:spark-SerializerManager.adoc#dataDeserializeStream[`SerializerManager` after the data stream has been deserialized] for the `blockId` block and link:spark-MemoryStore.adoc#getBytes[the bytes for `blockId` block] for ""serialized"" persistence levels. NOTE: `getLocalValues` is used when link:spark-TorrentBroadcast.adoc#readBroadcastBlock[`TorrentBroadcast` reads the blocks of a broadcast variable and stores them in a local `BlockManager`]. CAUTION: FIXME === [[getRemoteValues]] `getRemoteValues` Internal Method [source, scala] ---- getRemoteValues[T: ClassTag](blockId: BlockId): Option[BlockResult] ---- `getRemoteValues`...FIXME === [[get]] Retrieving Block from Local or Remote Block Managers -- `get` Method [source, scala] ---- get[T: ClassTag](blockId: BlockId): Option[BlockResult] ---- `get` attempts to get the `blockId` block from a local block manager first before requesting it from remote block managers. Internally, `get` tries to <>. If the block was found, you should see the following INFO message in the logs and `get` returns the local <>. ``` INFO Found block [blockId] locally ``` If however the block was not found locally, `get` tries to <>. If retrieved from a remote block manager, you should see the following INFO message in the logs and `get` returns the remote <>. ``` INFO Found block [blockId] remotely ``` In the end, `get` returns ""nothing"" (i.e. `NONE`) when the `blockId` block was not found either in the local `BlockManager` or any remote `BlockManager`. [NOTE] ==== `get` is used when: * `BlockManager` is requested to <> and <> * `BlockRDD` is requested to link:spark-streaming-BlockRDD.adoc#compute[compute a partition] * Spark Streaming's `WriteAheadLogBackedBlockRDD` is requested to `compute` a partition ==== === [[getLocalBytes]] Getting Local Block Data As Bytes -- `getLocalBytes` Method CAUTION: FIXME === [[getBlockData]] Finding Shuffle Block Data -- `getBlockData` Method CAUTION: FIXME === [[removeBlockInternal]] `removeBlockInternal` Method CAUTION: FIXME === [[externalShuffleServiceEnabled]] Is External Shuffle Service Enabled? -- `externalShuffleServiceEnabled` Flag When the link:spark-ExternalShuffleService.adoc[External Shuffle Service] is enabled for a Spark application, `BlockManager` uses link:spark-ShuffleClient-ExternalShuffleClient.adoc[ExternalShuffleClient] to read other executors' shuffle files. CAUTION: FIXME How is `shuffleClient` used? === [[stores]] Stores A *Store* is the place where blocks are held. There are the following possible stores: * link:spark-MemoryStore.adoc[MemoryStore] for memory storage level. * link:spark-DiskStore.adoc[DiskStore] for disk storage level. * `ExternalBlockStore` for OFF_HEAP storage level. === [[putBlockData]] Storing Block Data Locally -- `putBlockData` Method [source, scala] ---- putBlockData( blockId: BlockId, data: ManagedBuffer, level: StorageLevel, classTag: ClassTag[_]): Boolean ---- `putBlockData` simply <> (given the given storage `level`). NOTE: `putBlockData` is part of the link:spark-BlockDataManager.adoc#putBlockData[BlockDataManager Contract]. Internally, `putBlockData` wraps `ChunkedByteBuffer` around `data` buffer's NIO `ByteBuffer` and calls <>. === [[putBytes]] Storing Block Bytes Locally -- `putBytes` Method [source, scala] ---- putBytes( blockId: BlockId, bytes: ChunkedByteBuffer, level: StorageLevel, tellMaster: Boolean = true): Boolean ---- `putBytes` makes sure that the `bytes` are not `null` and <>. [NOTE] ==== `putBytes` is used when: * `BlockManager` is requested to <> * `TaskRunner` is requested to link:spark-executor-TaskRunner.adoc#run-result-sent-via-blockmanager[run] (and the result size is above link:spark-Executor.adoc#maxDirectResultSize[maxDirectResultSize]) * `TorrentBroadcast` is requested to link:spark-TorrentBroadcast.adoc#writeBlocks[writeBlocks] and link:spark-TorrentBroadcast.adoc#readBlocks[readBlocks] * Spark Streaming's `WriteAheadLogBackedBlockRDD` is requested to `compute` * Spark Streaming's `BlockManagerBasedBlockHandler` is requested to `storeBlock` * Spark Streaming's `WriteAheadLogBasedBlockHandler` is requested to `storeBlock` ==== ==== [[doPutBytes]] `doPutBytes` Internal Method [source, scala] ---- def doPutBytes[T]( blockId: BlockId, bytes: ChunkedByteBuffer, level: StorageLevel, classTag: ClassTag[T], tellMaster: Boolean = true, keepReadLock: Boolean = false): Boolean ---- `doPutBytes` calls the internal helper <> with a function that accepts a `BlockInfo` and does the uploading. Inside the function, if the link:spark-rdd-StorageLevel.adoc[storage `level`]'s replication is greater than 1, it immediately starts <> of the `blockId` block on a separate thread (from `futureExecutionContext` thread pool). The replication uses the input `bytes` and `level` storage level. For a memory storage level, the function checks whether the storage `level` is deserialized or not. For a deserialized storage `level`, ``BlockManager``'s link:spark-SerializerManager.adoc#dataDeserializeStream[`SerializerManager` deserializes `bytes` into an iterator of values] that link:spark-MemoryStore.adoc#putIteratorAsValues[`MemoryStore` stores]. If however the storage `level` is not deserialized, the function requests link:spark-MemoryStore.adoc#putBytes[`MemoryStore` to store the bytes] If the put did not succeed and the storage level is to use disk, you should see the following WARN message in the logs: ``` WARN BlockManager: Persisting block [blockId] to disk instead. ``` And link:spark-DiskStore.adoc#putBytes[`DiskStore` stores the bytes]. NOTE: link:spark-DiskStore.adoc[DiskStore] is requested to store the bytes of a block with memory and disk storage level only when link:spark-MemoryStore.adoc[MemoryStore] has failed. If the storage level is to use disk only, link:spark-DiskStore.adoc#putBytes[`DiskStore` stores the bytes]. `doPutBytes` requests <> and if the block was successfully stored, and the driver should know about it (`tellMaster`), the function <>. The link:spark-taskscheduler-taskmetrics.adoc#incUpdatedBlockStatuses[current `TaskContext` metrics are updated with the updated block status] (only when executed inside a task where `TaskContext` is available). You should see the following DEBUG message in the logs: ``` DEBUG BlockManager: Put block [blockId] locally took [time] ms ``` The function waits till the earlier asynchronous replication finishes for a block with replication level greater than `1`. The final result of `doPutBytes` is the result of storing the block successful or not (as computed earlier). NOTE: `doPutBytes` is used exclusively when `BlockManager` is requested to <>. === [[maybeCacheDiskValuesInMemory]] `maybeCacheDiskValuesInMemory` Method CAUTION: FIXME === [[doPut]] `doPut` Internal Method [source, scala] ---- doPut[T]( blockId: BlockId, level: StorageLevel, classTag: ClassTag[_], tellMaster: Boolean, keepReadLock: Boolean)(putBody: BlockInfo => Option[T]): Option[T] ---- `doPut` is an internal helper method for <> and <>. `doPut` executes the input `putBody` function with a link:spark-BlockInfo.adoc[BlockInfo] being a new `BlockInfo` object (with `level` storage level) that link:spark-BlockInfoManager.adoc#lockNewBlockForWriting[`BlockInfoManager` managed to create a write lock for]. If the block has already been created (and link:spark-BlockInfoManager.adoc#lockNewBlockForWriting[`BlockInfoManager` did not manage to create a write lock for]), the following WARN message is printed out to the logs: ``` WARN Block [blockId] already exists on this machine; not re-adding it ``` `doPut` <> when `keepReadLock` flag is disabled and returns `None` immediately. If however the write lock has been given, `doPut` executes `putBody`. If the result of `putBody` is `None` the block is considered saved successfully. For successful save and `keepReadLock` enabled, link:spark-BlockInfoManager.adoc#downgradeLock[`BlockInfoManager` is requested to downgrade an exclusive write lock for `blockId` to a shared read lock]. For successful save and `keepReadLock` disabled, link:spark-BlockInfoManager.adoc#unlock[`BlockInfoManager` is requested to release lock on `blockId`]. For unsuccessful save, <> and the following WARN message is printed out to the logs: ``` WARN Putting block [blockId] failed ``` Ultimately, the following DEBUG message is printed out to the logs: ``` DEBUG Putting block [blockId] [withOrWithout] replication took [usedTime] ms ``` === [[removeBlock]] Removing Block From Memory and Disk -- `removeBlock` Method [source, scala] ---- removeBlock(blockId: BlockId, tellMaster: Boolean = true): Unit ---- `removeBlock` removes the `blockId` block from the link:spark-MemoryStore.adoc[MemoryStore] and link:spark-DiskStore.adoc[DiskStore]. When executed, it prints out the following DEBUG message to the logs: ``` DEBUG Removing block [blockId] ``` It requests link:spark-BlockInfoManager.adoc[BlockInfoManager] for lock for writing for the `blockId` block. If it receives none, it prints out the following WARN message to the logs and quits. ``` WARN Asked to remove block [blockId], which does not exist ``` Otherwise, with a write lock for the block, the block is removed from link:spark-MemoryStore.adoc[MemoryStore] and link:spark-DiskStore.adoc[DiskStore] (see link:spark-MemoryStore.adoc#remove[Removing Block in `MemoryStore`] and link:spark-DiskStore.adoc#remove[Removing Block in `DiskStore`]). If both removals fail, it prints out the following WARN message: ``` WARN Block [blockId] could not be removed as it was not found in either the disk, memory, or external block store ``` The block is removed from link:spark-BlockInfoManager.adoc[BlockInfoManager]. It then <> that is used to <> (if the input `tellMaster` and the info's `tellMaster` are both enabled, i.e. `true`) and the link:spark-taskscheduler-taskmetrics.adoc#incUpdatedBlockStatuses[current TaskContext metrics are updated with the change]. NOTE: It is used to <> and <> as well as in link:spark-blockmanager-BlockManagerSlaveEndpoint.adoc#RemoveBlock[`BlockManagerSlaveEndpoint` while handling `RemoveBlock` messages]. === [[removeRdd]] Removing RDD Blocks -- `removeRdd` Method [source, scala] ---- removeRdd(rddId: Int): Int ---- `removeRdd` removes all the blocks that belong to the `rddId` RDD. It prints out the following INFO message to the logs: ``` INFO Removing RDD [rddId] ``` It then requests RDD blocks from link:spark-BlockInfoManager.adoc[BlockInfoManager] and <> (without informing the driver). The number of blocks removed is the final result. NOTE: It is used by link:spark-blockmanager-BlockManagerSlaveEndpoint.adoc#RemoveRdd[`BlockManagerSlaveEndpoint` while handling `RemoveRdd` messages]. === [[removeBroadcast]] Removing Broadcast Blocks -- `removeBroadcast` Method [source, scala] ---- removeBroadcast(broadcastId: Long, tellMaster: Boolean): Int ---- `removeBroadcast` removes all the blocks of the input `broadcastId` broadcast. Internally, it starts by printing out the following DEBUG message to the logs: ``` DEBUG Removing broadcast [broadcastId] ``` It then requests all the link:spark-BlockDataManager.adoc#BroadcastBlockId[BroadcastBlockId] objects that belong to the `broadcastId` broadcast from link:spark-BlockInfoManager.adoc[BlockInfoManager] and <>. The number of blocks removed is the final result. NOTE: It is used by link:spark-blockmanager-BlockManagerSlaveEndpoint.adoc#RemoveBroadcast[`BlockManagerSlaveEndpoint` while handling `RemoveBroadcast` messages]. === [[getStatus]] Getting Block Status -- `getStatus` Method CAUTION: FIXME === [[creating-instance]] Creating BlockManager Instance `BlockManager` takes the following when created: * [[executorId]] Executor ID * [[rpcEnv]] link:spark-rpc.adoc[RpcEnv] * [[master]] link:spark-BlockManagerMaster.adoc[BlockManagerMaster] * [[serializerManager]] link:spark-SerializerManager.adoc[SerializerManager] * [[conf]] link:spark-SparkConf.adoc[SparkConf] * [[memoryManager]] link:spark-MemoryManager.adoc[MemoryManager] * [[mapOutputTracker]] link:spark-service-mapoutputtracker.adoc[MapOutputTracker] * [[shuffleManager]] link:spark-ShuffleManager.adoc[ShuffleManager] * <> * [[securityManager]] `SecurityManager` * [[numUsableCores]] CPU cores NOTE: `executorId` is `SparkContext.DRIVER_IDENTIFIER`, i.e. `driver` for the driver, and the value of link:spark-CoarseGrainedExecutorBackend.adoc#executor-id[--executor-id] command-line argument for link:spark-CoarseGrainedExecutorBackend.adoc[CoarseGrainedExecutorBackend] executors or link:spark-executor-backends-MesosExecutorBackend.adoc[MesosExecutorBackend]. CAUTION: FIXME Elaborate on the executor backends and executor ids. When created, `BlockManager` sets <> internal flag per link:spark-ExternalShuffleService.adoc#spark.shuffle.service.enabled[spark.shuffle.service.enabled] Spark property. `BlockManager` then creates an instance of link:spark-DiskBlockManager.adoc[DiskBlockManager] (requesting `deleteFilesOnStop` when an external shuffle service is not in use). `BlockManager` creates an instance of link:spark-BlockInfoManager.adoc[BlockInfoManager] (as `blockInfoManager`). `BlockManager` creates *block-manager-future* daemon cached thread pool with 128 threads maximum (as `futureExecutionContext`). `BlockManager` creates a link:spark-MemoryStore.adoc[MemoryStore] and link:spark-DiskStore.adoc[DiskStore]. link:spark-MemoryManager.adoc[MemoryManager] gets the link:spark-MemoryStore.adoc[MemoryStore] object assigned. `BlockManager` calculates the maximum memory to use (as `maxMemory`) by requesting the maximum link:spark-MemoryManager.adoc#maxOnHeapStorageMemory[on-heap] and link:spark-MemoryManager.adoc#maxOffHeapStorageMemory[off-heap] storage memory from the assigned `MemoryManager`. NOTE: link:spark-UnifiedMemoryManager.adoc[UnifiedMemoryManager] is the default `MemoryManager` (as of Spark 1.6). `BlockManager` calculates the port used by the external shuffle service (as `externalShuffleServicePort`). NOTE: It is computed specially in Spark on YARN. CAUTION: FIXME Describe the YARN-specific part. `BlockManager` creates a client to read other executors' shuffle files (as `shuffleClient`). If the external shuffle service is used an link:spark-ShuffleClient-ExternalShuffleClient.adoc[ExternalShuffleClient] is created or the input link:spark-BlockTransferService.adoc[BlockTransferService] is used. `BlockManager` sets <> (as `maxFailuresBeforeLocationRefresh`). `BlockManager` registers link:spark-blockmanager-BlockManagerSlaveEndpoint.adoc[BlockManagerSlaveEndpoint] with the input link:spark-rpc.adoc[RpcEnv], itself, and link:spark-service-mapoutputtracker.adoc[MapOutputTracker] (as `slaveEndpoint`). === [[shuffleServerId]] `shuffleServerId` CAUTION: FIXME === [[initialize]] Initializing BlockManager -- `initialize` Method [source, scala] ---- initialize(appId: String): Unit ---- `initialize` initializes a `BlockManager` on the driver and executors (see link:spark-SparkContext.adoc#creating-instance[Creating SparkContext Instance] and link:spark-Executor.adoc#creating-instance[Creating Executor Instance], respectively). NOTE: The method must be called before a `BlockManager` can be considered fully operable. `initialize` does the following in order: 1. Initializes link:spark-BlockTransferService.adoc#init[BlockTransferService] 2. Initializes the internal shuffle client, be it link:spark-ShuffleClient-ExternalShuffleClient.adoc[ExternalShuffleClient] or link:spark-BlockTransferService.adoc[BlockTransferService]. 3. link:spark-BlockManagerMaster.adoc#registerBlockManager[Registers itself with the driver's `BlockManagerMaster`] (using the `id`, `maxMemory` and its `slaveEndpoint`). + The `BlockManagerMaster` reference is passed in when the <> on the driver and executors. 4. Sets <> to an instance of <> given an executor id, host name and port for link:spark-BlockTransferService.adoc[BlockTransferService]. 5. It creates the address of the server that serves this executor's shuffle files (using <>) CAUTION: FIXME Review the initialize procedure again CAUTION: FIXME Describe `shuffleServerId`. Where is it used? If the <>, the following INFO appears in the logs: ``` INFO external shuffle service port = [externalShuffleServicePort] ``` It link:spark-BlockManagerMaster.adoc#registerBlockManager[registers itself to the driver's BlockManagerMaster] passing the <>, the maximum memory (as `maxMemory`), and the link:spark-blockmanager-BlockManagerSlaveEndpoint.adoc[BlockManagerSlaveEndpoint]. Ultimately, if the initialization happens on an executor and the <>, it <>. NOTE: `initialize` is called when the link:spark-SparkContext-creating-instance-internals.adoc#BlockManager-initialization[driver is launched (and `SparkContext` is created)] and when an link:spark-Executor.adoc#creating-instance[`Executor` is created] (for link:spark-CoarseGrainedExecutorBackend.adoc#RegisteredExecutor[CoarseGrainedExecutorBackend] and link:spark-executor-backends-MesosExecutorBackend.adoc[MesosExecutorBackend]). ==== [[registerWithExternalShuffleServer]] Registering Executor's BlockManager with External Shuffle Server -- `registerWithExternalShuffleServer` Method [source, scala] ---- registerWithExternalShuffleServer(): Unit ---- `registerWithExternalShuffleServer` is an internal helper method to register the `BlockManager` for an executor with an link:spark-ExternalShuffleService.adoc[external shuffle server]. NOTE: It is executed when a <>. When executed, you should see the following INFO message in the logs: ``` INFO Registering executor with local external shuffle service. ``` It uses <> to link:spark-ShuffleClient-ExternalShuffleClient.adoc#registerWithShuffleServer[register the block manager] using <> (i.e. the host, the port and the executorId) and a `ExecutorShuffleInfo`. NOTE: The `ExecutorShuffleInfo` uses `localDirs` and `subDirsPerLocalDir` from link:spark-DiskBlockManager.adoc[DiskBlockManager] and the class name of the constructor link:spark-ShuffleManager.adoc[ShuffleManager]. It tries to register at most 3 times with 5-second sleeps in-between. NOTE: The maximum number of attempts and the sleep time in-between are hard-coded, i.e. they are not configured. Any issues while connecting to the external shuffle service are reported as ERROR messages in the logs: ``` ERROR Failed to connect to external shuffle server, will retry [#attempts] more times after waiting 5 seconds... ``` === [[reregister]] Re-registering BlockManager with Driver and Reporting Blocks -- `reregister` Method [source, scala] ---- reregister(): Unit ---- When executed, `reregister` prints the following INFO message to the logs: ``` INFO BlockManager: BlockManager [blockManagerId] re-registering with master ``` `reregister` then link:spark-BlockManagerMaster.adoc#registerBlockManager[registers itself to the driver's `BlockManagerMaster`] (just as it was when <>). It passes the <>, the maximum memory (as `maxMemory`), and the link:spark-blockmanager-BlockManagerSlaveEndpoint.adoc[BlockManagerSlaveEndpoint]. `reregister` will then report all the local blocks to the link:spark-BlockManagerMaster.adoc[BlockManagerMaster]. You should see the following INFO message in the logs: ``` INFO BlockManager: Reporting [blockInfoManager.size] blocks to the master. ``` For each block metadata (in link:spark-BlockInfoManager.adoc[BlockInfoManager]) it <> and <>. If there is an issue communicating to the link:spark-BlockManagerMaster.adoc[BlockManagerMaster], you should see the following ERROR message in the logs: ``` ERROR BlockManager: Failed to report [blockId] to master; giving up. ``` After the ERROR message, `reregister` stops reporting. NOTE: `reregister` is called when a link:spark-Executor.adoc#heartbeats-and-active-task-metrics[`Executor` was informed to re-register while sending heartbeats]. === [[getCurrentBlockStatus]] Calculate Current Block Status -- `getCurrentBlockStatus` Method [source, scala] ---- getCurrentBlockStatus(blockId: BlockId, info: BlockInfo): BlockStatus ---- `getCurrentBlockStatus` returns the current `BlockStatus` of the `BlockId` block (with the block's current link:spark-rdd-StorageLevel.adoc[StorageLevel], memory and disk sizes). It uses link:spark-MemoryStore.adoc[MemoryStore] and link:spark-DiskStore.adoc[DiskStore] for size and other information. NOTE: Most of the information to build `BlockStatus` is already in `BlockInfo` except that it may not necessarily reflect the current state per link:spark-MemoryStore.adoc[MemoryStore] and link:spark-DiskStore.adoc[DiskStore]. Internally, it uses the input link:spark-BlockInfo.adoc[BlockInfo] to know about the block's storage level. If the storage level is not set (i.e. `null`), the returned `BlockStatus` assumes the link:spark-rdd-StorageLevel.adoc[default `NONE` storage level] and the memory and disk sizes being `0`. If however the storage level is set, `getCurrentBlockStatus` uses link:spark-MemoryStore.adoc[MemoryStore] and link:spark-DiskStore.adoc[DiskStore] to check whether the block is stored in the storages or not and request for their sizes in the storages respectively (using their `getSize` or assume `0`). NOTE: It is acceptable that the `BlockInfo` says to use memory or disk yet the block is not in the storages (yet or anymore). The method will give current status. NOTE: `getCurrentBlockStatus` is used when <>, <> or <> or <>. === [[reportAllBlocks]] `reportAllBlocks` Internal Method [source, scala] ---- reportAllBlocks(): Unit ---- `reportAllBlocks`...FIXME NOTE: `reportAllBlocks` is used when `BlockManager` is requested to <>. === [[reportBlockStatus]] Reporting Current Storage Status of Block to Driver -- `reportBlockStatus` Internal Method [source, scala] ---- reportBlockStatus( blockId: BlockId, info: BlockInfo, status: BlockStatus, droppedMemorySize: Long = 0L): Unit ---- `reportBlockStatus` is an internal method for <> and if told to re-register it prints out the following INFO message to the logs: ``` INFO BlockManager: Got told to re-register updating block [blockId] ``` It does asynchronous reregistration (using `asyncReregister`). In either case, it prints out the following DEBUG message to the logs: ``` DEBUG BlockManager: Told master about block [blockId] ``` NOTE: `reportBlockStatus` is used when `BlockManager` is requested to <>, <>, <>, <> and <>. === [[tryToReportBlockStatus]] Reporting Block Status Update to Driver -- `tryToReportBlockStatus` Internal Method [source, scala] ---- def tryToReportBlockStatus( blockId: BlockId, info: BlockInfo, status: BlockStatus, droppedMemorySize: Long = 0L): Boolean ---- `tryToReportBlockStatus` link:spark-BlockManagerMaster.adoc#updateBlockInfo[reports block status update] to <> and returns its response. NOTE: `tryToReportBlockStatus` is used when `BlockManager` is requested to <> or <>. === [[broadcast]] Broadcast Values When a new broadcast value is created, link:spark-TorrentBroadcast.adoc[TorrentBroadcast] blocks are put in the block manager. You should see the following `TRACE` message: ``` TRACE Put for block [blockId] took [startTimeMs] to get into synchronized block ``` It puts the data in the memory first and drop to disk if the memory store can't hold it. ``` DEBUG Put block [blockId] locally took [startTimeMs] ``` === [[BlockManagerId]] BlockManagerId FIXME === [[execution-context]] Execution Context *block-manager-future* is the execution context for...FIXME === Misc The underlying abstraction for blocks in Spark is a `ByteBuffer` that limits the size of a block to 2GB (`Integer.MAX_VALUE` - see http://stackoverflow.com/q/8076472/1305344[Why does FileChannel.map take up to Integer.MAX_VALUE of data?] and https://issues.apache.org/jira/browse/SPARK-1476[SPARK-1476 2GB limit in spark for blocks]). This has implication not just for managed blocks in use, but also for shuffle blocks (memory mapped blocks are limited to 2GB, even though the API allows for `long`), ser-deser via byte array-backed output streams. When a non-local executor starts, it initializes a `BlockManager` object using link:spark-SparkConf.adoc#spark.app.id[spark.app.id] Spark property for the id. === [[BlockResult]] BlockResult `BlockResult` is a description of a fetched block with the `readMethod` and `bytes`. === [[registerTask]] Registering Task with BlockInfoManager -- `registerTask` Method [source, scala] ---- registerTask(taskAttemptId: Long): Unit ---- `registerTask` link:spark-BlockInfoManager.adoc#registerTask[registers the input `taskAttemptId` with `BlockInfoManager`]. NOTE: `registerTask` is used exclusively when link:spark-taskscheduler-Task.adoc#run[`Task` runs]. === [[getDiskWriter]] Offering DiskBlockObjectWriter To Write Blocks To Disk (For Current BlockManager) -- `getDiskWriter` Method [source, scala] ---- getDiskWriter( blockId: BlockId, file: File, serializerInstance: SerializerInstance, bufferSize: Int, writeMetrics: ShuffleWriteMetrics): DiskBlockObjectWriter ---- `getDiskWriter` link:spark-blockmanager-DiskBlockObjectWriter.adoc#creating-instance[creates a `DiskBlockObjectWriter`] with <> Spark property for `syncWrites`. NOTE: `getDiskWriter` uses the same `serializerManager` that was used to <>. NOTE: `getDiskWriter` is used when link:spark-BypassMergeSortShuffleWriter.adoc#write[`BypassMergeSortShuffleWriter` writes records into one single shuffle block data file], in link:spark-ShuffleExternalSorter.adoc#writeSortedFile[ShuffleExternalSorter], `UnsafeSorterSpillWriter`, link:spark-ExternalSorter.adoc[ExternalSorter], and `ExternalAppendOnlyMap`. === [[addUpdatedBlockStatusToTaskMetrics]] Recording Updated BlockStatus In Current Task's TaskMetrics -- `addUpdatedBlockStatusToTaskMetrics` Internal Method [source, scala] ---- addUpdatedBlockStatusToTaskMetrics(blockId: BlockId, status: BlockStatus): Unit ---- `addUpdatedBlockStatusToTaskMetrics` link:spark-taskscheduler-TaskContext.adoc#get[takes an active `TaskContext`] (if available) and link:spark-taskscheduler-taskmetrics.adoc#incUpdatedBlockStatuses[records updated `BlockStatus` for `Block`] (in the link:spark-taskscheduler-TaskContext.adoc#taskMetrics[task's `TaskMetrics`]). NOTE: `addUpdatedBlockStatusToTaskMetrics` is used when `BlockManager` <> (for a block that was successfully stored), <>, <>, <> (possibly spilling it to disk) and <>. === [[shuffleMetricsSource]] Requesting Shuffle-Related Spark Metrics Source -- `shuffleMetricsSource` Method [source, scala] ---- shuffleMetricsSource: Source ---- `shuffleMetricsSource` requests the <> for the link:spark-ShuffleClient.adoc#shuffleMetrics[shuffle-related metrics] and creates a link:spark-BlockManager-ShuffleMetricsSource.adoc[ShuffleMetricsSource] with the link:spark-BlockManager-ShuffleMetricsSource.adoc#sourceName[source name] per link:spark-ExternalShuffleService.adoc#spark.shuffle.service.enabled[spark.shuffle.service.enabled] configuration property: * *ExternalShuffle* when link:spark-ExternalShuffleService.adoc#spark.shuffle.service.enabled[spark.shuffle.service.enabled] configuration property is on (`true`) * *NettyBlockTransfer* when link:spark-ExternalShuffleService.adoc#spark.shuffle.service.enabled[spark.shuffle.service.enabled] configuration property is off (`false`) NOTE: link:spark-ExternalShuffleService.adoc#spark.shuffle.service.enabled[spark.shuffle.service.enabled] configuration property is off (`false`) by default. NOTE: `shuffleMetricsSource` is used exclusively when `Executor` is link:spark-Executor.adoc#creating-instance[created] (for non-local / cluster modes). === [[settings]] Settings .Spark Properties [cols=""1,1,2"",options=""header"",width=""100%""] |=== | Spark Property | Default Value | Description | [[spark_blockManager_port]] `spark.blockManager.port` | `0` | Port to use for the block manager when a more specific setting for the driver or executors is not provided. | [[spark_shuffle_sync]] `spark.shuffle.sync` | `false` | Controls whether link:spark-blockmanager-DiskBlockObjectWriter.adoc#commitAndGet[`DiskBlockObjectWriter` should force outstanding writes to disk when committing a single atomic block], i.e. all operating system buffers should synchronize with the disk to ensure that all changes to a file are in fact recorded in the storage. |=== === [[replicate]] Replicating Block To Peers -- `replicate` Internal Method [source, scala] ---- replicate( blockId: BlockId, data: BlockData, level: StorageLevel, classTag: ClassTag[_], existingReplicas: Set[BlockManagerId] = Set.empty): Unit ---- `replicate`...FIXME NOTE: `replicate` is used when `BlockManager` is requested to <>, <> and <>. === [[replicateBlock]] `replicateBlock` Method [source, scala] ---- replicateBlock( blockId: BlockId, existingReplicas: Set[BlockManagerId], maxReplicas: Int): Unit ---- `replicateBlock`...FIXME NOTE: `replicateBlock` is used exclusively when `BlockManagerSlaveEndpoint` is requested to link:spark-blockmanager-BlockManagerSlaveEndpoint.adoc#receiveAndReply-ReplicateBlock[handle ReplicateBlock messages]. === [[putIterator]] `putIterator` Method [source, scala] ---- putIterator[T: ClassTag]( blockId: BlockId, values: Iterator[T], level: StorageLevel, tellMaster: Boolean = true): Boolean ---- `putIterator`...FIXME [NOTE] ==== `putIterator` is used when: * `BlockManager` is requested to <> * Spark Streaming's `BlockManagerBasedBlockHandler` is requested to `storeBlock` ==== === [[putSingle]] `putSingle` Method [source, scala] ---- putSingle[T: ClassTag]( blockId: BlockId, value: T, level: StorageLevel, tellMaster: Boolean = true): Boolean ---- `putSingle`...FIXME NOTE: `putSingle` is used when `TorrentBroadcast` is requested to link:spark-TorrentBroadcast.adoc#writeBlocks[read the blocks of a broadcast variable] and link:spark-TorrentBroadcast.adoc#readBroadcastBlock[readBroadcastBlock]. === [[getRemoteBytes]] Fetching Block From Remote Nodes -- `getRemoteBytes` Method [source, scala] ---- getRemoteBytes(blockId: BlockId): Option[ChunkedByteBuffer] ---- `getRemoteBytes`...FIXME [NOTE] ==== `getRemoteBytes` is used when: * `BlockManager` is requested to <> * `TorrentBroadcast` is requested to link:spark-TorrentBroadcast.adoc#readBlocks[readBlocks] * `TaskResultGetter` is requested to link:spark-TaskResultGetter.adoc#enqueueSuccessfulTask[enqueuing a successful IndirectTaskResult] ==== === [[getRemoteValues]] `getRemoteValues` Internal Method [source, scala] ---- getRemoteValues[T: ClassTag](blockId: BlockId): Option[BlockResult] ---- `getRemoteValues`...FIXME NOTE: `getRemoteValues` is used exclusively when `BlockManager` is requested to <>. === [[getSingle]] `getSingle` Method [source, scala] ---- getSingle[T: ClassTag](blockId: BlockId): Option[T] ---- `getSingle`...FIXME NOTE: `getSingle` is used exclusively in Spark tests. === [[shuffleClient]] `shuffleClient` Property [source, scala] ---- shuffleClient: ShuffleClient ---- `shuffleClient` is a link:spark-ShuffleClient.adoc[ShuffleClient] that `BlockManager` uses for the following: * <> * <> `shuffleClient` is also used when `BlockStoreShuffleReader` is requested to link:spark-BlockStoreShuffleReader.adoc#read[read combined key-value records for a reduce task] (and creates a link:spark-ShuffleBlockFetcherIterator.adoc#shuffleClient[ShuffleBlockFetcherIterator]). `shuffleClient` can be either a link:spark-ShuffleClient-ExternalShuffleClient.adoc[ExternalShuffleClient] or the <> (that is the link:spark-NettyBlockTransferService.adoc[NettyBlockTransferService] given by link:spark-SparkEnv.adoc#create-BlockManager[SparkEnv]). CAUTION: FIXME Figure [[shuffleClient-externalShuffleServiceEnabled]] `shuffleClient` uses `spark.shuffle.service.enabled` configuration property (default: `false`) that controls whether to use link:spark-ShuffleClient-ExternalShuffleClient.adoc[ExternalShuffleClient] (`true`) or the <> (i.e. link:spark-NettyBlockTransferService.adoc[NettyBlockTransferService]). === [[blockTransferService]] `blockTransferService` Property When <>, `BlockManager` is given a link:spark-BlockTransferService.adoc[BlockTransferService] that is used for the following services: * <> * <> NOTE: Remote nodes, peers, block managers are all synonyms. The `BlockTransferService` acts as the <> when <> configuration property is off (which is the default). When <>, `BlockManager` requests the `BlockTransferService` to link:spark-BlockTransferService.adoc#init[init]. `BlockManager` also requests the <> to link:spark-ShuffleClient.adoc#init[init] (that does nothing by default). When <>, `BlockManager` requests the `BlockTransferService` to link:spark-BlockTransferService.adoc#close[close]. `BlockManager` also requests the <> to `close`. === [[getOrElseUpdate]] Getting Block From Block Managers Or Computing and Storing It Otherwise -- `getOrElseUpdate` Method [source, scala] ---- getOrElseUpdate[T]( blockId: BlockId, level: StorageLevel, classTag: ClassTag[T], makeIterator: () => Iterator[T]): Either[BlockResult, Iterator[T]] ---- [NOTE] ==== _I think_ it is fair to say that `getOrElseUpdate` is like link:++https://www.scala-lang.org/api/current/scala/collection/mutable/Map.html#getOrElseUpdate(key:K,op:=%3EV):V++[getOrElseUpdate] of https://www.scala-lang.org/api/current/scala/collection/mutable/Map.html[scala.collection.mutable.Map] in Scala. [source, scala] ---- getOrElseUpdate(key: K, op: ⇒ V): V ---- Quoting the official scaladoc: If given key `K` is already in this map, `getOrElseUpdate` returns the associated value `V`. Otherwise, `getOrElseUpdate` computes a value `V` from given expression `op`, stores with the key `K` in the map and returns that value. Since `BlockManager` is a key-value store of blocks of data identified by a block ID that works just fine. ==== `getOrElseUpdate` first attempts to <> by the `BlockId` (from the local block manager first and, if unavailable, requesting remote peers). [TIP] ==== Enable `INFO` logging level for `org.apache.spark.storage.BlockManager` logger to see what happens when `BlockManager` tries to <>. See <> in this document. ==== `getOrElseUpdate` gives the `BlockResult` of the block if found. If however the block was not found (in any block manager in a Spark cluster), `getOrElseUpdate` <> (for the input `BlockId`, the `makeIterator` function and the `StorageLevel`). `getOrElseUpdate` branches off per the result. For `None`, `getOrElseUpdate` <> for the `BlockId` and eventually returns the `BlockResult` (unless terminated by a `SparkException` due to some internal error). For `Some(iter)`, `getOrElseUpdate` returns an iterator of `T` values. NOTE: `getOrElseUpdate` is used exclusively when `RDD` is requested to link:spark-rdd-RDD.adoc#getOrCompute[get or compute an RDD partition] (for a `RDDBlockId` with a RDD ID and a partition index). === [[doPutIterator]] `doPutIterator` Internal Method [source, scala] ---- doPutIterator[T]( blockId: BlockId, iterator: () => Iterator[T], level: StorageLevel, classTag: ClassTag[T], tellMaster: Boolean = true, keepReadLock: Boolean = false): Option[PartiallyUnrolledIterator[T]] ---- `doPutIterator` simply <> with the `putBody` function that accepts a `BlockInfo` and does the following: . `putBody` branches off per whether the `StorageLevel` indicates to use a link:spark-rdd-StorageLevel.adoc#useMemory[memory] or simply a link:spark-rdd-StorageLevel.adoc#useDisk[disk], i.e. * When the input `StorageLevel` indicates to link:spark-rdd-StorageLevel.adoc#useMemory[use a memory] for storage in link:spark-rdd-StorageLevel.adoc#deserialized[deserialized] format, `putBody` requests <> to link:spark-MemoryStore.adoc#putIteratorAsValues[putIteratorAsValues] (for the `BlockId` and with the `iterator` factory function). + If the <> returned a correct value, the internal `size` is set to the value. + If however the <> failed to give a correct value, FIXME * When the input `StorageLevel` indicates to link:spark-rdd-StorageLevel.adoc#useMemory[use memory] for storage in link:spark-rdd-StorageLevel.adoc#deserialized[serialized] format, `putBody`...FIXME * When the input `StorageLevel` does not indicate to use memory for storage but link:spark-rdd-StorageLevel.adoc#useDisk[disk] instead, `putBody`...FIXME . `putBody` requests the <> . Only when the block was successfully stored in either the memory or disk store: * `putBody` <> to the <> when the input `tellMaster` flag (default: enabled) and the `tellMaster` flag of the block info are both enabled. * `putBody` <> (with the `BlockId` and `BlockStatus`) * `putBody` prints out the following DEBUG message to the logs: + ``` Put block [blockId] locally took [time] ms ``` * When the input `StorageLevel` indicates to use link:spark-rdd-StorageLevel.adoc#replication[replication], `putBody` <> followed by <> (with the input `BlockId` and the `StorageLevel` as well as the `BlockData` to replicate) * With a successful replication, `putBody` prints out the following DEBUG message to the logs: + ``` Put block [blockId] remotely took [time] ms ``` . In the end, `putBody` may or may not give a `PartiallyUnrolledIterator` if...FIXME NOTE: `doPutIterator` is used when `BlockManager` is requested to <> and <>. === [[dropFromMemory]] Removing Blocks From Memory Only -- `dropFromMemory` Method [source, scala] ---- dropFromMemory( blockId: BlockId, data: () => Either[Array[T], ChunkedByteBuffer]): StorageLevel ---- NOTE: `dropFromMemory` is part of the link:spark-BlockEvictionHandler.adoc#dropFromMemory[BlockEvictionHandler Contract] to...FIXME When `dropFromMemory` is executed, you should see the following INFO message in the logs: ``` INFO BlockManager: Dropping block [blockId] from memory ``` It then asserts that the `blockId` block is link:spark-BlockInfoManager.adoc#assertBlockIsLockedForWriting[locked for writing]. If the block's link:spark-rdd-StorageLevel.adoc[StorageLevel] uses disks and the internal link:spark-DiskStore.adoc[DiskStore] object (`diskStore`) does not contain the block, it is saved then. You should see the following INFO message in the logs: ``` INFO BlockManager: Writing block [blockId] to disk ``` CAUTION: FIXME Describe the case with saving a block to disk. The block's memory size is fetched and recorded (using `MemoryStore.getSize`). The block is link:spark-MemoryStore.adoc#remove[removed from memory] if exists. If not, you should see the following WARN message in the logs: ``` WARN BlockManager: Block [blockId] could not be dropped from memory as it does not exist ``` It then <> and <>. It only happens when `info.tellMaster`. CAUTION: FIXME When would `info.tellMaster` be `true`? A block is considered updated when it was written to disk or removed from memory or both. If either happened, the link:spark-taskscheduler-taskmetrics.adoc#incUpdatedBlockStatuses[current TaskContext metrics are updated with the change]. Ultimately, `dropFromMemory` returns the current storage level of the block. ",12343,True,2783.328131320427,median "/****************************************************************************** * * Copyright (c) 2017, the Perspective Authors. * * This file is part of the Perspective library, distributed under the terms of * the Apache License 2.0. The full license can be found in the LICENSE file. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace perspective { t_tscalar get_dominant(t_tscalvec& values) { if (values.empty()) return mknone(); std::sort(values.begin(), values.end()); t_tscalar delem = values[0]; t_index dcount = 1; t_index count = 1; for (t_index idx = 1, loop_end = values.size(); idx < loop_end; ++idx) { const t_tscalar& prev = values[idx - 1]; const t_tscalar& curr = values[idx]; if (curr == prev && curr.is_valid()) { ++count; } if ((idx + 1) == static_cast(values.size()) || curr != prev) { if (count > dcount) { delem = prev; dcount = count; } count = 1; } } return delem; } t_tree_unify_rec::t_tree_unify_rec(t_uindex sptidx, t_uindex daggidx, t_uindex saggidx, t_uindex nstrands) : m_sptidx(sptidx), m_daggidx(daggidx), m_saggidx(saggidx), m_nstrands(nstrands) { } t_stree::t_stree(const t_pivotvec& pivots, const t_aggspecvec& aggspecs, const t_schema& schema, const t_config& cfg) : m_pivots(pivots), m_init(false), m_curidx(1), m_aggspecs(aggspecs), m_schema(schema), m_cur_aggidx(1), m_dotcount(0), m_minmax(aggspecs.size()), m_has_delta(false) { auto g_agg_str = cfg.get_grand_agg_str(); m_grand_agg_str = g_agg_str.empty() ? ""Grand Aggregate"" : g_agg_str; } t_stree::~t_stree() { for (t_sidxmap::iterator iter = m_smap.begin(); iter != m_smap.end(); ++iter) { free(const_cast(iter->first)); } } t_uindex t_stree::get_num_aggcols() const { return m_aggspecs.size(); } t_str t_stree::repr() const { std::stringstream ss; ss << ""t_stree<"" << this << "">""; return ss.str(); } void t_stree::init() { m_nodes = std::make_shared(); m_idxpkey = std::make_shared(); m_idxleaf = std::make_shared(); t_tscalar value = m_symtable.get_interned_tscalar(m_grand_agg_str.c_str()); t_tnode node(0, root_pidx(), value, 0, value, 1, 0); m_nodes->insert(node); t_svec columns; t_dtypevec dtypes; for (const auto& spec : m_aggspecs) { auto cinfo = spec.get_output_specs(m_schema); for (const auto& ci : cinfo) { columns.push_back(ci.m_name); dtypes.push_back(ci.m_type); } } t_schema schema(columns, dtypes); t_uindex capacity = DEFAULT_EMPTY_CAPACITY; m_aggregates = std::make_shared(schema, capacity); m_aggregates->init(); m_aggregates->set_size(capacity); m_aggcols = t_colcptrvec(columns.size()); for (t_uindex idx = 0, loop_end = columns.size(); idx < loop_end; ++idx) { m_aggcols[idx] = m_aggregates->get_const_column(columns[idx]).get(); } m_deltas = std::make_shared(); m_features = std::vector(CTX_FEAT_LAST_FEATURE); m_init = true; } t_tscalar t_stree::get_value(t_tvidx idx) const { iter_by_idx iter = m_nodes->get().find(idx); PSP_VERBOSE_ASSERT(iter != m_nodes->get().end(), ""Reached end iterator""); return iter->m_value; } t_tscalar t_stree::get_sortby_value(t_tvidx idx) const { iter_by_idx iter = m_nodes->get().find(idx); PSP_VERBOSE_ASSERT(iter != m_nodes->get().end(), ""Reached end iterator""); return iter->m_sort_value; } void t_stree::build_strand_table_phase_1(t_tscalar pkey, t_op op, t_uindex idx, t_uindex npivots, t_uindex strand_count_idx, t_uindex aggcolsize, t_bool force_current_row, const t_colcptrvec& piv_ccols, const t_colcptrvec& piv_tcols, const t_colcptrvec& agg_ccols, const t_colcptrvec& agg_dcols, t_colptrvec& piv_scols, t_colptrvec& agg_acols, t_column* agg_scount, t_column* spkey, t_uindex& insert_count, t_bool& pivots_neq, const t_svec& pivot_like) const { pivots_neq = false; t_sset pivmap; t_bool all_eq_tt = true; for (t_uindex pidx = 0, ploop_end = pivot_like.size(); pidx < ploop_end; ++pidx) { const t_str& colname = pivot_like.at(pidx); if (pivmap.find(colname) != pivmap.end()) { continue; } pivmap.insert(colname); piv_scols[pidx]->push_back(piv_ccols[pidx]->get_scalar(idx)); const t_uint8* trans_ = piv_tcols[pidx]->get_nth(idx); t_value_transition trans = static_cast(*trans_); if (trans != VALUE_TRANSITION_EQ_TT) all_eq_tt = false; if (pidx < npivots) { pivots_neq = pivots_neq || pivots_changed(trans); } } for (t_uindex aggidx = 0; aggidx < aggcolsize; ++aggidx) { if (aggidx != strand_count_idx) { if (pivots_neq || force_current_row) { agg_acols[aggidx]->push_back( agg_ccols[aggidx]->get_scalar(idx)); } else { agg_acols[aggidx]->push_back( agg_dcols[aggidx]->get_scalar(idx)); } } } t_int8 cval; if (op == OP_DELETE) { cval = -1; } else { if (t_env::backout_force_current_row()) { cval = !all_eq_tt || pivots_neq ? 1 : 0; } else { cval = npivots == 0 || !all_eq_tt || pivots_neq || force_current_row ? 1 : 0; } } agg_scount->push_back(cval); spkey->push_back(pkey); ++insert_count; } void t_stree::build_strand_table_phase_2(t_tscalar pkey, t_uindex idx, t_uindex npivots, t_uindex strand_count_idx, t_uindex aggcolsize, const t_colcptrvec& piv_pcols, const t_colcptrvec& agg_pcols, t_colptrvec& piv_scols, t_colptrvec& agg_acols, t_column* agg_scount, t_column* spkey, t_uindex& insert_count, const t_svec& pivot_like) const { t_sset pivmap; for (t_uindex pidx = 0, ploop_end = pivot_like.size(); pidx < ploop_end; ++pidx) { const t_str& colname = pivot_like.at(pidx); if (pivmap.find(colname) != pivmap.end()) { continue; } pivmap.insert(colname); piv_scols[pidx]->push_back(piv_pcols[pidx]->get_scalar(idx)); } for (t_uindex aggidx = 0; aggidx < aggcolsize; ++aggidx) { if (aggidx != strand_count_idx) { agg_acols[aggidx]->push_back( agg_pcols[aggidx]->get_scalar(idx).negate()); } } agg_scount->push_back(t_int8(-1)); spkey->push_back(pkey); ++insert_count; } t_build_strand_table_common_rval t_stree::build_strand_table_common(const t_table& flattened, const t_aggspecvec& aggspecs, const t_config& config) const { PSP_TRACE_SENTINEL(); PSP_VERBOSE_ASSERT(m_init, ""touching uninited object""); t_build_strand_table_common_rval rv; rv.m_flattened_schema = flattened.get_schema(); t_sset sschema_colset; for (const auto& piv : m_pivots) { const t_str& colname = piv.colname(); t_str sortby_colname = config.get_sort_by(colname); auto add_col = [&sschema_colset, &rv](const t_str& cname) { if (sschema_colset.find(cname) == sschema_colset.end()) { rv.m_pivot_like_columns.push_back(cname); rv.m_strand_schema.add_column( cname, rv.m_flattened_schema.get_dtype(cname)); sschema_colset.insert(cname); } }; add_col(colname); add_col(sortby_colname); } rv.m_pivsize = sschema_colset.size(); t_sset aggcolset; for (const auto& aggspec : aggspecs) { for (const auto& dep : aggspec.get_dependencies()) { if (dep.type() == DEPTYPE_COLUMN) { const t_str& depname = dep.name(); aggcolset.insert(depname); if (aggspec.is_non_delta() && sschema_colset.find(depname) == sschema_colset.end()) { rv.m_pivot_like_columns.push_back(depname); rv.m_strand_schema.add_column( depname, rv.m_flattened_schema.get_dtype(depname)); sschema_colset.insert(depname); } } } } rv.m_npivotlike = sschema_colset.size(); rv.m_strand_schema.add_column( ""psp_pkey"", flattened.get_const_column(""psp_pkey"")->get_dtype()); for (const auto& aggcol : aggcolset) { rv.m_aggschema.add_column( aggcol, rv.m_flattened_schema.get_dtype(aggcol)); } rv.m_aggschema.add_column(""psp_strand_count"", DTYPE_INT8); return rv; } // can contain additional rows // notably pivot changed rows will be added std::pair t_stree::build_strand_table(const t_table& flattened, const t_table& delta, const t_table& prev, const t_table& current, const t_table& transitions, const t_aggspecvec& aggspecs, const t_config& config) const { PSP_TRACE_SENTINEL(); PSP_VERBOSE_ASSERT(m_init, ""touching uninited object""); auto rv = build_strand_table_common(flattened, aggspecs, config); // strand table t_table_sptr strands = std::make_shared(rv.m_strand_schema); strands->init(); // strand table t_table_sptr aggs = std::make_shared(rv.m_aggschema); aggs->init(); t_col_csptr pkey_col = flattened.get_const_column(""psp_pkey""); t_col_csptr op_col = flattened.get_const_column(""psp_op""); t_uindex npivotlike = rv.m_npivotlike; t_colcptrvec piv_pcols(npivotlike); t_colcptrvec piv_ccols(npivotlike); t_colcptrvec piv_tcols(npivotlike); t_colptrvec piv_scols(npivotlike); t_uindex insert_count = 0; for (t_uindex pidx = 0; pidx < npivotlike; ++pidx) { const t_str& piv = rv.m_strand_schema.m_columns[pidx]; piv_pcols[pidx] = prev.get_const_column(piv).get(); piv_ccols[pidx] = current.get_const_column(piv).get(); piv_tcols[pidx] = transitions.get_const_column(piv).get(); piv_scols[pidx] = strands->get_column(piv).get(); } t_uindex aggcolsize = rv.m_aggschema.m_columns.size(); t_colcptrvec agg_ccols(aggcolsize); t_colcptrvec agg_pcols(aggcolsize); t_colcptrvec agg_dcols(aggcolsize); t_colptrvec agg_acols(aggcolsize); t_uindex strand_count_idx = 0; for (t_uindex aggidx = 0; aggidx < aggcolsize; ++aggidx) { const t_str& aggcol = rv.m_aggschema.m_columns[aggidx]; if (aggcol == ""psp_strand_count"") { agg_dcols[aggidx] = 0; agg_ccols[aggidx] = 0; agg_pcols[aggidx] = 0; strand_count_idx = aggidx; } else { agg_dcols[aggidx] = delta.get_const_column(aggcol).get(); agg_ccols[aggidx] = current.get_const_column(aggcol).get(); agg_pcols[aggidx] = prev.get_const_column(aggcol).get(); } agg_acols[aggidx] = aggs->get_column(aggcol).get(); } t_column* agg_scount = aggs->get_column(""psp_strand_count"").get(); t_column* spkey = strands->get_column(""psp_pkey"").get(); t_mask msk_prev, msk_curr; if (config.has_filters()) { msk_prev = filter_table_for_config(prev, config); msk_curr = filter_table_for_config(current, config); } t_bool has_filters = config.has_filters(); if (has_filters) { for (t_uindex idx = 0, loop_end = flattened.size(); idx < loop_end; ++idx) { t_bool filter_prev = msk_prev.get(idx); t_bool filter_curr = msk_curr.get(idx); t_tscalar pkey = pkey_col->get_scalar(idx); t_uint8 op_ = *(op_col->get_nth(idx)); t_op op = static_cast(op_); t_bool pivots_neq; if (!filter_prev && !filter_curr) { // nothing to do continue; } else if (!filter_prev && filter_curr) { // apply current row build_strand_table_phase_1(pkey, op, idx, rv.m_pivsize, strand_count_idx, aggcolsize, true, piv_ccols, piv_tcols, agg_ccols, agg_dcols, piv_scols, agg_acols, agg_scount, spkey, insert_count, pivots_neq, rv.m_pivot_like_columns); } else if (filter_prev && !filter_curr) { // reverse prev row build_strand_table_phase_2(pkey, idx, rv.m_pivsize, strand_count_idx, aggcolsize, piv_pcols, agg_pcols, piv_scols, agg_acols, agg_scount, spkey, insert_count, rv.m_pivot_like_columns); } else if (filter_prev && filter_curr) { // should be handled as normal build_strand_table_phase_1(pkey, op, idx, rv.m_pivsize, strand_count_idx, aggcolsize, false, piv_ccols, piv_tcols, agg_ccols, agg_dcols, piv_scols, agg_acols, agg_scount, spkey, insert_count, pivots_neq, rv.m_pivot_like_columns); if (op == OP_DELETE || !pivots_neq) { continue; } build_strand_table_phase_2(pkey, idx, rv.m_pivsize, strand_count_idx, aggcolsize, piv_pcols, agg_pcols, piv_scols, agg_acols, agg_scount, spkey, insert_count, rv.m_pivot_like_columns); } } } else { for (t_uindex idx = 0, loop_end = flattened.size(); idx < loop_end; ++idx) { t_tscalar pkey = pkey_col->get_scalar(idx); t_uint8 op_ = *(op_col->get_nth(idx)); t_op op = static_cast(op_); t_bool pivots_neq; build_strand_table_phase_1(pkey, op, idx, rv.m_pivsize, strand_count_idx, aggcolsize, false, piv_ccols, piv_tcols, agg_ccols, agg_dcols, piv_scols, agg_acols, agg_scount, spkey, insert_count, pivots_neq, rv.m_pivot_like_columns); if (op == OP_DELETE || !pivots_neq) { continue; } build_strand_table_phase_2(pkey, idx, rv.m_pivsize, strand_count_idx, aggcolsize, piv_pcols, agg_pcols, piv_scols, agg_acols, agg_scount, spkey, insert_count, rv.m_pivot_like_columns); } } strands->reserve(insert_count); strands->set_size(insert_count); aggs->reserve(insert_count); aggs->set_size(insert_count); agg_scount->valid_raw_fill(true); return std::pair(strands, aggs); } // can contain additional rows // notably pivot changed rows will be added std::pair t_stree::build_strand_table(const t_table& flattened, const t_aggspecvec& aggspecs, const t_config& config) const { PSP_TRACE_SENTINEL(); PSP_VERBOSE_ASSERT(m_init, ""touching uninited object""); auto rv = build_strand_table_common(flattened, aggspecs, config); // strand table t_table_sptr strands = std::make_shared(rv.m_strand_schema); strands->init(); // strand table t_table_sptr aggs = std::make_shared(rv.m_aggschema); aggs->init(); t_col_csptr pkey_col = flattened.get_const_column(""psp_pkey""); t_col_csptr op_col = flattened.get_const_column(""psp_op""); t_uindex npivotlike = rv.m_npivotlike; t_colcptrvec piv_fcols(npivotlike); t_colptrvec piv_scols(npivotlike); t_uindex insert_count = 0; for (t_uindex pidx = 0; pidx < npivotlike; ++pidx) { const t_str& piv = rv.m_strand_schema.m_columns[pidx]; piv_fcols[pidx] = flattened.get_const_column(piv).get(); piv_scols[pidx] = strands->get_column(piv).get(); } t_uindex aggcolsize = rv.m_aggschema.m_columns.size(); t_colcptrvec agg_fcols(aggcolsize); t_colptrvec agg_acols(aggcolsize); t_uindex strand_count_idx = 0; for (t_uindex aggidx = 0; aggidx < aggcolsize; ++aggidx) { const t_str& aggcol = rv.m_aggschema.m_columns[aggidx]; if (aggcol == ""psp_strand_count"") { agg_fcols[aggidx] = 0; strand_count_idx = aggidx; } else { agg_fcols[aggidx] = flattened.get_const_column(aggcol).get(); } agg_acols[aggidx] = aggs->get_column(aggcol).get(); } t_column* agg_scount = aggs->get_column(""psp_strand_count"").get(); t_column* spkey = strands->get_column(""psp_pkey"").get(); t_mask msk; if (config.has_filters()) { msk = filter_table_for_config(flattened, config); } t_bool has_filters = config.has_filters(); for (t_uindex idx = 0, loop_end = flattened.size(); idx < loop_end; ++idx) { t_bool filter = !has_filters || msk.get(idx); t_tscalar pkey = pkey_col->get_scalar(idx); t_uint8 op_ = *(op_col->get_nth(idx)); t_op op = static_cast(op_); if (!filter || op == OP_DELETE) { // nothing to do continue; } for (t_uindex pidx = 0, ploop_end = rv.m_pivot_like_columns.size(); pidx < ploop_end; ++pidx) { piv_scols[pidx]->push_back( piv_fcols[pidx]->get_scalar(idx)); } for (t_uindex aggidx = 0; aggidx < aggcolsize; ++aggidx) { if (aggidx != strand_count_idx) { agg_acols[aggidx]->push_back( agg_fcols[aggidx]->get_scalar(idx)); } } agg_scount->push_back(1); spkey->push_back(pkey); ++insert_count; } strands->reserve(insert_count); strands->set_size(insert_count); aggs->reserve(insert_count); aggs->set_size(insert_count); agg_scount->valid_raw_fill(true); return std::pair(strands, aggs); } t_bool t_stree::pivots_changed(t_value_transition t) const { return t == VALUE_TRANSITION_NEQ_TF || t == VALUE_TRANSITION_NVEQ_FT || t == VALUE_TRANSITION_NEQ_TT; } void t_stree::populate_pkey_idx(const t_dtree_ctx& ctx, const t_dtree& dtree, t_uindex dptidx, t_uindex sptidx, t_uindex ndepth, t_idxpkey& new_idx_pkey) { if (ndepth == dtree.last_level()) { auto pkey_col = ctx.get_pkey_col(); auto strand_count_col = ctx.get_strand_count_col(); auto liters = ctx.get_leaf_iterators(dptidx); for (auto lfiter = liters.first; lfiter != liters.second; ++lfiter) { auto lfidx = *lfiter; auto pkey = m_symtable.get_interned_tscalar( pkey_col->get_scalar(lfidx)); auto strand_count = *(strand_count_col->get_nth(lfidx)); if (strand_count > 0) { t_stpkey s(sptidx, pkey); new_idx_pkey.insert(s); } if (strand_count < 0) { remove_pkey(sptidx, pkey); } } } } void t_stree::update_shape_from_static(const t_dtree_ctx& ctx) { m_newids.clear(); m_newleaves.clear(); m_tree_unification_records.clear(); const t_col_csptr scount = ctx.get_aggtable().get_const_column(""psp_strand_count_sum""); const t_dtree& dtree = ctx.get_tree(); // map dptidx to sptidx std::map nmap; nmap[0] = 0; t_filter filter; // update root auto root_iter = m_nodes->get().find(0); auto root_node = *root_iter; t_index root_nstrands = *(scount->get_nth(0)) + root_node.m_nstrands; root_node.set_nstrands(root_nstrands); m_nodes->get().replace(root_iter, root_node); t_tree_unify_rec unif_rec(0, 0, 0, root_nstrands); m_tree_unification_records.push_back(unif_rec); t_idxpkey new_idx_pkey; for (auto dptidx : dtree.dfs()) { t_uindex sptidx = 0; t_depth ndepth = dtree.get_depth(dptidx); if (dptidx == 0) { populate_pkey_idx( ctx, dtree, dptidx, sptidx, ndepth, new_idx_pkey); continue; } t_uindex p_dptidx = dtree.get_parent(dptidx); t_uindex p_sptidx = nmap[p_dptidx]; t_tscalar value = m_symtable.get_interned_tscalar( dtree.get_value(filter, dptidx)); t_tscalar sortby_value = m_symtable.get_interned_tscalar( dtree.get_sortby_value(filter, dptidx)); t_uindex src_ridx = dptidx; auto iter = m_nodes->get().find( boost::make_tuple(p_sptidx, value)); auto nstrands = *(scount->get_nth(dptidx)); if (iter == m_nodes->get().end() && nstrands < 0) { continue; } if (iter == m_nodes->get().end()) { // create node and enqueue sptidx = genidx(); t_uindex aggsize = m_aggregates->size(); if (sptidx == aggsize) { t_float64 scale = 1.3; t_uindex new_size = scale * aggsize; m_aggregates->extend(new_size); } t_uindex dst_ridx = gen_aggidx(); t_tnode node(sptidx, p_sptidx, value, ndepth, sortby_value, nstrands, dst_ridx); m_newids.insert(sptidx); if (ndepth == dtree.last_level()) { m_newleaves.insert(sptidx); } auto insert_pair = m_nodes->insert(node); if (!insert_pair.second) { auto failed_because = *(insert_pair.first); std::cout << ""failed because of "" << failed_because << std::endl; } PSP_VERBOSE_ASSERT(insert_pair.second, ""Failed to insert node""); t_tree_unify_rec unif_rec( sptidx, src_ridx, dst_ridx, nstrands); m_tree_unification_records.push_back(unif_rec); } else { sptidx = iter->m_idx; // update node t_tnode node = *iter; node.set_sort_value(sortby_value); t_uindex dst_ridx = node.m_aggidx; nstrands = node.m_nstrands + nstrands; t_tree_unify_rec unif_rec( sptidx, src_ridx, dst_ridx, nstrands); m_tree_unification_records.push_back(unif_rec); sptidx = iter->m_idx; node.set_nstrands(nstrands); t_bool replaced = m_nodes->get().replace(iter, node); PSP_VERBOSE_ASSERT(replaced, ""Failed to replace""); } populate_pkey_idx( ctx, dtree, dptidx, sptidx, ndepth, new_idx_pkey); nmap[dptidx] = sptidx; } auto biter = new_idx_pkey.get().begin(); auto eiter = new_idx_pkey.get().end(); for (auto iter = biter; iter != eiter; ++iter) { t_stpkey s(iter->m_idx, iter->m_pkey); m_idxpkey->insert(s); } mark_zero_desc(); } void t_stree::mark_zero_desc() { auto zeros = zero_strands(); t_uidxset z_desc; for (auto z : zeros) { auto d = get_descendents(z); std::copy( d.begin(), d.end(), std::inserter(z_desc, z_desc.end())); } for (auto n : z_desc) { auto iter = m_nodes->get().find(n); auto node = *iter; node.set_nstrands(0); m_nodes->get().replace(iter, node); } } void t_stree::update_aggs_from_static(const t_dtree_ctx& ctx, const t_gstate& gstate) { const t_table& src_aggtable = ctx.get_aggtable(); t_agg_update_info agg_update_info; t_schema aggschema = m_aggregates->get_schema(); for (auto colname : aggschema.m_columns) { agg_update_info.m_src.push_back( src_aggtable.get_const_column(colname).get()); agg_update_info.m_dst.push_back( m_aggregates->get_column(colname).get()); agg_update_info.m_aggspecs.push_back( ctx.get_aggspec(colname)); } auto is_col_scaled_aggregate = [&]( int col_idx ) -> bool { int agg_type = agg_update_info.m_aggspecs[ col_idx ].agg(); return agg_type == AGGTYPE_SCALED_DIV || agg_type == AGGTYPE_SCALED_ADD || agg_type == AGGTYPE_SCALED_MUL; }; size_t col_cnt = aggschema.m_columns.size(); auto &cols_topo_sorted = agg_update_info.m_dst_topo_sorted; cols_topo_sorted.clear(); cols_topo_sorted.reserve(col_cnt); static bool const enable_aggregate_reordering = true; static bool const enable_fix_double_calculation = true; std::unordered_set< t_column* > dst_visited; auto push_column = [&]( size_t idx ) { if ( enable_fix_double_calculation ) { t_column* dst = agg_update_info.m_dst[ idx ]; if ( dst_visited.find( dst ) != dst_visited.end() ) { return; } dst_visited.insert( dst ); } cols_topo_sorted.push_back( idx ); }; if ( enable_aggregate_reordering ) { // Move scaled agg columns to the end // This does not handle case where scaled aggregate depends on other scaled aggregate // ( not sure if that is possible ) for (size_t i = 0; i < col_cnt; ++i) { if (!is_col_scaled_aggregate(i)) { push_column(i); } } for (size_t i = 0; i < col_cnt; ++i) { if (is_col_scaled_aggregate(i)) { push_column(i); } } } else { // If backed out, use same column order as before ( not topo sorted ) for ( size_t i = 0; i < col_cnt; ++i ) { push_column( i ); } } for (const auto& r : m_tree_unification_records) { if (!node_exists(r.m_sptidx)) { continue; } update_agg_table(r.m_sptidx, agg_update_info, r.m_daggidx, r.m_saggidx, r.m_nstrands, gstate); } } t_uindex t_stree::genidx() { return m_curidx++; } t_uidxvec t_stree::get_children(t_uindex idx) const { t_by_pidx_ipair iterators = m_nodes->get().equal_range(idx); t_uindex nchild = std::distance(iterators.first, iterators.second); t_uidxvec temp(nchild); t_index count = 0; for (iter_by_pidx iter = iterators.first; iter != iterators.second; ++iter) { temp[count] = iter->m_idx; ++count; } return temp; } t_uindex t_stree::size() const { return m_nodes->size(); } void t_stree::get_child_nodes(t_uindex idx, t_tnodevec& nodes) const { t_index num_children = get_num_children(idx); t_tnodevec temp(num_children); auto iterators = m_nodes->get().equal_range(idx); std::copy(iterators.first, iterators.second, temp.begin()); std::swap(nodes, temp); } t_uindex t_stree::get_num_children(t_uindex ptidx) const { auto iterators = m_nodes->get().equal_range(ptidx); return std::distance(iterators.first, iterators.second); } t_uindex t_stree::gen_aggidx() { if (!m_agg_freelist.empty()) { t_uindex rval = m_agg_freelist.back(); m_agg_freelist.pop_back(); return rval; } t_uindex cur_cap = m_aggregates->size(); t_uindex rval = m_cur_aggidx; ++m_cur_aggidx; if (rval >= cur_cap) { t_float64 nrows = ceil(.3 * t_float64(rval)); m_aggregates->extend(static_cast(nrows)); } return rval; } void t_stree::update_agg_table(t_uindex nidx, t_agg_update_info& info, t_uindex src_ridx, t_uindex dst_ridx, t_index nstrands, const t_gstate& gstate) { static bool const enable_sticky_nan_fix = true; for (t_uindex idx : info.m_dst_topo_sorted) { const t_column* src = info.m_src[idx]; t_column* dst = info.m_dst[idx]; const t_aggspec& spec = info.m_aggspecs[idx]; t_tscalar new_value = mknone(); t_tscalar old_value = mknone(); switch (spec.agg()) { case AGGTYPE_PCT_SUM_PARENT: case AGGTYPE_PCT_SUM_GRAND_TOTAL: case AGGTYPE_SUM: { t_tscalar src_scalar = src->get_scalar(src_ridx); t_tscalar dst_scalar = dst->get_scalar(dst_ridx); old_value.set(dst_scalar); new_value.set(dst_scalar.add(src_scalar)); if( enable_sticky_nan_fix && old_value.is_nan() ) // is_nan returns false for non-float types { // if we previously had a NaN, add can't make it finite again; recalculate entire sum in case it is now finite auto pkeys = get_pkeys(nidx); t_f64vec values; gstate.read_column(spec.get_dependencies()[0].name(), pkeys, values); new_value.set(std::accumulate(values.begin(), values.end(), t_float64(0))); } dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_COUNT: { if (nidx == 0) { new_value.set(nstrands - 1); } else { new_value.set(nstrands); } dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_MEAN: { auto pkeys = get_pkeys(nidx); t_f64vec values; gstate.read_column( spec.get_dependencies()[0].name(), pkeys, values); t_float64 nr = 0; t_float64 dr = 0; auto bit = values.begin(); auto eit = values.end(); for(; bit != eit; ++bit) { auto val = *bit; if (val != NULL) { nr += val; dr += 1; } } t_f64pair* dst_pair = dst->get_nth(dst_ridx); old_value.set(dst_pair->first / dst_pair->second); dst_pair->first = nr; dst_pair->second = dr; dst->set_valid(dst_ridx, true); new_value.set(nr / dr); } break; case AGGTYPE_WEIGHTED_MEAN: { auto pkeys = get_pkeys(nidx); t_f64vec values; t_f64vec weights; gstate.read_column( spec.get_dependencies()[0].name(), pkeys, values); gstate.read_column(spec.get_dependencies()[1].name(), pkeys, weights); t_float64 init_value = 0.0; auto nr = std::inner_product(weights.begin(), weights.end(), values.begin(), init_value); auto dr = std::accumulate( weights.begin(), weights.end(), t_float64(0)); t_f64pair* dst_pair = dst->get_nth(dst_ridx); old_value.set(dst_pair->first / dst_pair->second); dst_pair->first = nr; dst_pair->second = dr; dst->set_valid(dst_ridx, true); new_value.set(nr / dr); } break; case AGGTYPE_UNIQUE: { auto pkeys = get_pkeys(nidx); old_value.set(dst->get_scalar(dst_ridx)); t_bool is_unique = gstate.is_unique( pkeys, spec.get_dependencies()[0].name(), new_value); if (new_value.m_type == DTYPE_STR) { if (is_unique) { new_value = m_symtable.get_interned_tscalar( new_value); } else { new_value = m_symtable.get_interned_tscalar(""-""); } dst->set_scalar(dst_ridx, new_value); } else { if (is_unique) { dst->set_scalar(dst_ridx, new_value); } else { dst->set_valid(dst_ridx, false); new_value = old_value; } } } break; case AGGTYPE_OR: case AGGTYPE_ANY: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); gstate.apply(pkeys, spec.get_dependencies()[0].name(), new_value, [](const t_tscalar& row_value, t_tscalar& output) { if (row_value) { output.set(row_value); return true; } return false; }); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_MEDIAN: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); new_value.set(gstate.reduce< std::function>( pkeys, spec.get_dependencies()[0].name(), [](t_tscalvec& values) { if (values.size() == 0) { return t_tscalar(); } else if (values.size() == 1) { return values[0]; } else { t_tscalvec::iterator middle = values.begin() + (values.size() / 2); std::nth_element( values.begin(), middle, values.end()); return *middle; } })); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_JOIN: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); new_value.set(gstate.reduce< std::function>( pkeys, spec.get_dependencies()[0].name(), [this](t_tscalvec& values) { t_tscalset vset; for (const auto& v : values) { vset.insert(v); } std::stringstream ss; for (t_tscalset::const_iterator iter = vset.begin(); iter != vset.end(); ++iter) { ss << *iter << "", ""; } return m_symtable.get_interned_tscalar( ss.str().c_str()); })); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_SCALED_DIV: { const t_column* src_1 = info.m_dst[spec.get_agg_one_idx()]; const t_column* src_2 = info.m_dst[spec.get_agg_two_idx()]; t_column* dst = info.m_dst[idx]; old_value.set(dst->get_scalar(dst_ridx)); t_float64 agg1 = src_1->get_scalar(dst_ridx).to_double(); t_float64 agg2 = src_2->get_scalar(dst_ridx).to_double(); t_float64 w1 = spec.get_agg_one_weight(); t_float64 w2 = spec.get_agg_two_weight(); t_float64 v = (agg1 * w1) / (agg2 * w2); new_value.set(v); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_SCALED_ADD: { const t_column* src_1 = info.m_dst[spec.get_agg_one_idx()]; const t_column* src_2 = info.m_dst[spec.get_agg_two_idx()]; t_column* dst = info.m_dst[idx]; old_value.set(dst->get_scalar(dst_ridx)); t_float64 v = (src_1->get_scalar(dst_ridx).to_double() * spec.get_agg_one_weight()) + (src_2->get_scalar(dst_ridx).to_double() * spec.get_agg_two_weight()); new_value.set(v); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_SCALED_MUL: { const t_column* src_1 = info.m_dst[spec.get_agg_one_idx()]; const t_column* src_2 = info.m_dst[spec.get_agg_two_idx()]; t_column* dst = info.m_dst[idx]; old_value.set(dst->get_scalar(dst_ridx)); t_float64 v = (src_1->get_scalar(dst_ridx).to_double() * spec.get_agg_one_weight()) * (src_2->get_scalar(dst_ridx).to_double() * spec.get_agg_two_weight()); new_value.set(v); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_DOMINANT: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); new_value.set(gstate.reduce< std::function>( pkeys, spec.get_dependencies()[0].name(), [](t_tscalvec& values) { return get_dominant(values); })); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_FIRST: case AGGTYPE_LAST: { old_value.set(dst->get_scalar(dst_ridx)); new_value.set(first_last_helper(nidx, spec, gstate)); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_AND: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); new_value.set(gstate.reduce< std::function>( pkeys, spec.get_dependencies()[0].name(), [](t_tscalvec& values) { t_tscalar rval; rval.set(true); for (const auto& v : values) { if (!v) { rval.set(false); break; } } return rval; })); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_LAST_VALUE: { t_tscalar src_scalar = src->get_scalar(src_ridx); t_tscalar dst_scalar = dst->get_scalar(dst_ridx); old_value.set(dst_scalar); new_value.set(src_scalar); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_HIGH_WATER_MARK: { t_tscalar src_scalar = src->get_scalar(src_ridx); t_tscalar dst_scalar = dst->get_scalar(dst_ridx); old_value.set(dst_scalar); new_value.set(src_scalar); if (dst_scalar.is_valid()) { new_value.set(std::max(dst_scalar, src_scalar)); } dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_LOW_WATER_MARK: { t_tscalar src_scalar = src->get_scalar(src_ridx); t_tscalar dst_scalar = dst->get_scalar(dst_ridx); old_value.set(dst_scalar); new_value.set(src_scalar); if (dst_scalar.is_valid()) { new_value.set(std::min(dst_scalar, src_scalar)); } dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_UDF_COMBINER: case AGGTYPE_UDF_REDUCER: { // these will be filled in later } break; case AGGTYPE_SUM_NOT_NULL: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); new_value.set(gstate.reduce< std::function>( pkeys, spec.get_dependencies()[0].name(), [](t_tscalvec& values) { if (values.empty()) { return mknone(); } t_tscalar rval; rval.set(t_uint64(0)); rval.m_type = values[0].m_type; for (const auto& v : values) { if (rval.is_nan()) continue; rval = rval.add(v); } return rval; })); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_SUM_ABS: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); new_value.set(gstate.reduce< std::function>( pkeys, spec.get_dependencies()[0].name(), [](t_tscalvec& values) { if (values.empty()) { return mknone(); } t_tscalar rval; rval.set(t_uint64(0)); rval.m_type = values[0].m_type; for (const auto& v : values) { rval = rval.add(v.abs()); } return rval; })); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_MUL: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); new_value.set(gstate.reduce< std::function>( pkeys, spec.get_dependencies()[0].name(), [](t_tscalvec& values) { if (values.size() == 0) { return t_tscalar(); } else if (values.size() == 1) { return values[0]; } else { t_tscalar v = values[0]; for (t_uindex vidx = 1, vloop_end = values.size(); vidx < vloop_end; ++vidx) { v = v.mul(values[vidx]); } return v; } })); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_DISTINCT_COUNT: { old_value.set(dst->get_scalar(dst_ridx)); auto pkeys = get_pkeys(nidx); new_value.set( gstate .reduce>( pkeys, spec.get_dependencies()[0].name(), [this](t_tscalvec& values) { std::unordered_set vset; for (const auto& v : values) { vset.insert(v); } t_uint32 rv = vset.size(); return rv; })); dst->set_scalar(dst_ridx, new_value); } break; case AGGTYPE_DISTINCT_LEAF: { auto pkeys = get_pkeys(nidx); old_value.set(dst->get_scalar(dst_ridx)); t_bool skip = false; t_bool is_unique = gstate.is_unique( pkeys, spec.get_dependencies()[0].name(), new_value); if (is_leaf(nidx) && is_unique) { if (new_value.m_type == DTYPE_STR) { new_value = m_symtable.get_interned_tscalar( new_value); } } else { if (new_value.m_type == DTYPE_STR) { new_value = m_symtable.get_interned_tscalar(""""); } else { dst->set_valid(dst_ridx, false); new_value = old_value; skip = true; } } if (!skip) dst->set_scalar(dst_ridx, new_value); } break; default: { PSP_COMPLAIN_AND_ABORT(""Not implemented""); } } // end switch t_bool val_neq = old_value != new_value; m_has_delta = m_has_delta || val_neq; t_bool deltas_enabled = m_features.at(CTX_FEAT_DELTA); if (deltas_enabled && val_neq) { m_deltas->insert( t_tcdelta(nidx, idx, old_value, new_value)); } } // end for } t_uidxvec t_stree::zero_strands() const { auto iterators = m_nodes->get().equal_range(0); t_uidxvec rval; for (auto& iter = iterators.first; iter != iterators.second; ++iter) { rval.push_back(iter->m_idx); } return rval; } t_uidxset t_stree::non_zero_leaves(const t_uidxvec& zero_strands) const { return non_zero_ids(m_newleaves, zero_strands); } t_uidxset t_stree::non_zero_ids(const t_uidxvec& zero_strands) const { return non_zero_ids(m_newids, zero_strands); } t_uidxset t_stree::non_zero_ids(const t_uidxset& ptiset, const t_uidxvec& zero_strands) const { t_uidxset zeroset; for (auto idx : zero_strands) { zeroset.insert(idx); } t_uidxset rval; for (const auto& newid : ptiset) { if (zeroset.find(newid) == zeroset.end()) { rval.insert(newid); } } return rval; } t_uindex t_stree::get_parent_idx(t_uindex ptidx) const { iter_by_idx iter = m_nodes->get().find(ptidx); if (iter == m_nodes->get().end()) { std::cout << ""Failed in tree => "" << repr() << std::endl; PSP_VERBOSE_ASSERT(false, ""Did not find node""); } return iter->m_pidx; } t_uidxvec t_stree::get_ancestry(t_uindex idx) const { t_uindex rpidx = root_pidx(); t_uidxvec rval; while (idx != rpidx) { rval.push_back(idx); idx = get_parent_idx(idx); } std::reverse(rval.begin(), rval.end()); return rval; } t_index t_stree::get_sibling_idx(t_tvidx p_ptidx, t_index p_nchild, t_uindex c_ptidx) const { t_by_pidx_ipair iterators = m_nodes->get().equal_range(p_ptidx); iter_by_pidx c_iter = m_nodes->project( m_nodes->get().find(c_ptidx)); return std::distance(iterators.first, c_iter); } t_uindex t_stree::get_aggidx(t_uindex idx) const { iter_by_idx iter = m_nodes->get().find(idx); PSP_VERBOSE_ASSERT(iter != m_nodes->get().end(), ""Failed in get_aggidx""); return iter->m_aggidx; } t_table_csptr t_stree::get_aggtable() const { return m_aggregates; } t_table* t_stree::_get_aggtable() { return m_aggregates.get(); } t_stree::t_tnode t_stree::get_node(t_uindex idx) const { iter_by_idx iter = m_nodes->get().find(idx); PSP_VERBOSE_ASSERT(iter != m_nodes->get().end(), ""Failed in get_node""); return *iter; } void t_stree::get_path(t_uindex idx, t_tscalvec& rval) const { t_uindex curidx = idx; if (curidx == 0) return; while (1) { iter_by_idx iter = m_nodes->get().find(curidx); rval.push_back(iter->m_value); curidx = iter->m_pidx; if (curidx == 0) { break; } } return; } t_uindex t_stree::resolve_child(t_uindex root, const t_tscalar& datum) const { auto iter = m_nodes->get().find( boost::make_tuple(root, datum)); if (iter == m_nodes->get().end()) { return INVALID_INDEX; } return iter->m_idx; } void t_stree::clear_aggregates(const t_uidxvec& indices) { auto cols = m_aggregates->get_columns(); for (auto c : cols) { for (auto aggidx : indices) { c->set_valid(aggidx, false); } } m_agg_freelist.insert(std::end(m_agg_freelist), std::begin(indices), std::end(indices)); } void t_stree::drop_zero_strands() { auto iterators = m_nodes->get().equal_range(0); t_uidxvec leaves; auto lst = last_level(); t_uidxvec node_ids; for (auto iter = iterators.first; iter != iterators.second; ++iter) { if (iter->m_depth == lst) leaves.push_back(iter->m_idx); node_ids.push_back(iter->m_aggidx); } clear_aggregates(node_ids); for (auto nidx : leaves) { auto ancestry = get_ancestry(nidx); for (auto ancidx : ancestry) { if (ancidx == nidx) continue; remove_leaf(ancidx, nidx); } } auto iterators2 = m_nodes->get().equal_range(0); m_nodes->get().erase(iterators2.first, iterators2.second); } void t_stree::add_pkey(t_uindex idx, t_tscalar pkey) { t_stpkey s(idx, pkey); m_idxpkey->insert(s); } void t_stree::remove_pkey(t_uindex idx, t_tscalar pkey) { auto iter = m_idxpkey->get().find( boost::make_tuple(idx, pkey)); if (iter == m_idxpkey->get().end()) return; m_idxpkey->get().erase(iter); } void t_stree::add_leaf(t_uindex nidx, t_uindex lfidx) { t_stleaves s(nidx, lfidx); m_idxleaf->insert(s); } void t_stree::remove_leaf(t_uindex nidx, t_uindex lfidx) { auto iter = m_idxleaf->get().find( boost::make_tuple(nidx, lfidx)); if (iter == m_idxleaf->get().end()) return; m_idxleaf->get().erase(iter); } t_by_idx_pkey_ipair t_stree::get_pkeys_for_leaf(t_uindex idx) const { return m_idxpkey->get().equal_range(idx); } t_tscalvec t_stree::get_pkeys(t_uindex idx) const { t_tscalvec rval; t_uidxvec leaves = get_leaves(idx); for (auto leaf : leaves) { auto iters = get_pkeys_for_leaf(leaf); for (auto iter = iters.first; iter != iters.second; ++iter) { rval.push_back(iter->m_pkey); } } return rval; } t_uidxvec t_stree::get_leaves(t_uindex idx) const { t_uidxvec rval; if (is_leaf(idx)) { rval.push_back(idx); return rval; } auto iters = m_idxleaf->get().equal_range(idx); for (auto iter = iters.first; iter != iters.second; ++iter) { rval.push_back(iter->m_lfidx); } return rval; } t_depth t_stree::get_depth(t_uindex ptidx) const { auto iter = m_nodes->get().find(ptidx); return iter->m_depth; } void t_stree::get_drd_indices(t_uindex ridx, t_depth rel_depth, t_uidxvec& leaves) const { t_ptipairvec pending; if (rel_depth == 0) { leaves.push_back(ridx); return; } t_depth rdepth = get_depth(ridx); t_depth edepth = rdepth + rel_depth; pending.push_back(t_ptipair(ridx, rdepth)); while (!pending.empty()) { t_ptipair head = pending.back(); pending.pop_back(); if (head.second == edepth - 1) { auto children = get_child_idx(head.first); std::copy(children.begin(), children.end(), std::back_inserter(leaves)); } else { auto children = get_child_idx_depth(head.first); std::copy(children.begin(), children.end(), std::back_inserter(pending)); } } } t_uidxvec t_stree::get_child_idx(t_uindex idx) const { t_index num_children = get_num_children(idx); t_uidxvec children(num_children); auto iterators = m_nodes->get().equal_range(idx); t_index count = 0; while (iterators.first != iterators.second) { children[count] = iterators.first->m_idx; ++count; ++iterators.first; } return children; } t_ptipairvec t_stree::get_child_idx_depth(t_uindex idx) const { t_index num_children = get_num_children(idx); t_ptipairvec children(num_children); auto iterators = m_nodes->get().equal_range(idx); t_index count = 0; while (iterators.first != iterators.second) { children[count] = t_ptipair(iterators.first->m_idx, iterators.first->m_depth); ++count; ++iterators.first; } return children; } void t_stree::populate_leaf_index(const t_uidxset& leaves) { for (auto nidx : leaves) { t_uidxvec ancestry = get_ancestry(nidx); for (auto ancidx : ancestry) { if (ancidx == nidx) continue; add_leaf(ancidx, nidx); } } } t_uindex t_stree::last_level() const { return m_pivots.size(); } t_bool t_stree::is_leaf(t_uindex nidx) const { auto iter = m_nodes->get().find(nidx); PSP_VERBOSE_ASSERT(iter != m_nodes->get().end(), ""Did not find node""); return iter->m_depth == last_level(); } t_uidxvec t_stree::get_descendents(t_uindex nidx) const { t_uidxvec rval; t_uidxvec queue; queue.push_back(nidx); while (!queue.empty()) { auto h = queue.back(); queue.pop_back(); auto children = get_children(h); queue.insert(std::end(queue), std::begin(children), std::end(children)); rval.insert( std::end(rval), std::begin(children), std::end(children)); } return rval; } const t_pivotvec& t_stree::get_pivots() const { return m_pivots; } t_ptidx t_stree::resolve_path(t_uindex root, const t_tscalvec& path) const { t_ptidx curidx = root; if (path.empty()) return curidx; for (t_index i = path.size() - 1; i >= 0; i--) { iter_by_pidx_hash iter = m_nodes->get().find( boost::make_tuple(curidx, path[i])); if (iter == m_nodes->get().end()) { return INVALID_INDEX; } curidx = iter->m_idx; } return curidx; } // aggregates should be presized to be same size // as agg_indices void t_stree::get_aggregates_for_sorting(t_uindex nidx, const t_idxvec& agg_indices, t_tscalvec& aggregates, t_ctx2 * ctx2) const { t_uindex aggidx = get_aggidx(nidx); for (t_uindex idx = 0, loop_end = agg_indices.size(); idx < loop_end; ++idx) { auto which_agg = agg_indices[idx]; if(which_agg < 0) { aggregates[idx] = get_sortby_value(nidx); } else if( ctx2 || ( size_t(which_agg) >= m_aggcols.size() ) ) { aggregates[idx].set(t_none()); if(ctx2) { if( (ctx2->get_config().get_totals() == TOTALS_BEFORE) && (size_t(which_agg) < m_aggcols.size()) ) { aggregates[idx] = m_aggcols[which_agg]->get_scalar(aggidx); continue; } // two sided pivoted column // we don't have enough information here to work out the shape of the data // so we have to use ctx2 to resolve // fetch the row/column path from ctx2 t_tscalvec col_path = ctx2->get_column_path_userspace( which_agg+1 ); if( col_path.empty() ) { if( ctx2->get_config().get_totals() == TOTALS_AFTER ) { aggregates[idx] = m_aggcols[which_agg % m_aggcols.size()]->get_scalar(aggidx); } continue; } t_tscalvec row_path; get_path(nidx, row_path); auto target_tree = ctx2->get_trees()[ get_node(nidx).m_depth ]; t_ptidx target = target_tree->resolve_path( 0, row_path ); if( target != INVALID_INDEX ) target = target_tree->resolve_path( target, col_path ); if( target != INVALID_INDEX ) { aggregates[idx] = target_tree->get_aggregate( target, which_agg % m_aggcols.size() ); } } } else { aggregates[idx] = m_aggcols[which_agg]->get_scalar(aggidx); } } } t_tscalar t_stree::get_aggregate(t_ptidx idx, t_index aggnum) const { if (aggnum < 0) { return get_value(idx); } auto aggtable = get_aggtable(); auto c = aggtable->get_const_column(aggnum).get(); auto agg_ridx = get_aggidx(idx); t_ptidx pidx = get_parent_idx(idx); t_index agg_pridx = pidx == INVALID_INDEX ? INVALID_INDEX : get_aggidx(pidx); return extract_aggregate( m_aggspecs[aggnum], c, agg_ridx, agg_pridx); } void t_stree::get_child_indices(t_ptidx idx, t_ptivec& out_data) const { t_index num_children = get_num_children(idx); t_ptivec temp(num_children); t_by_pidx_ipair iterators = m_nodes->get().equal_range(idx); t_index count = 0; for (iter_by_pidx iter = iterators.first; iter != iterators.second; ++iter) { temp[count] = iter->m_idx; ++count; } std::swap(out_data, temp); } void t_stree::clear_deltas() { m_deltas->clear(); m_has_delta = false; } void t_stree::clear() { m_nodes->clear(); clear_deltas(); } void t_stree::set_alerts_enabled(bool enabled_state) { m_features[CTX_FEAT_ALERT] = enabled_state; } void t_stree::set_deltas_enabled(bool enabled_state) { m_features[CTX_FEAT_DELTA] = enabled_state; } void t_stree::set_minmax_enabled(bool enabled_state) { m_features[CTX_FEAT_MINMAX] = enabled_state; } void t_stree::set_feature_state(t_ctx_feature feature, t_bool state) { m_features[feature] = state; } t_minmax t_stree::get_agg_min_max(t_uindex aggidx, t_depth depth) const { auto iterators = m_nodes->get().equal_range(depth); return get_agg_min_max(iterators.first, iterators.second, aggidx); } t_minmaxvec t_stree::get_min_max() const { t_uindex naggs = m_aggspecs.size(); t_minmaxvec rval(naggs); for (t_uindex cidx = 0; cidx < naggs; ++cidx) { auto biter = m_nodes->get().begin(); auto eiter = m_nodes->get().end(); rval[cidx] = get_agg_min_max(biter, eiter, cidx); } return rval; } const t_sptr_tcdeltas& t_stree::get_deltas() const { return m_deltas; } t_tscalar t_stree::first_last_helper(t_uindex nidx, const t_aggspec& spec, const t_gstate& gstate) const { auto pkeys = get_pkeys(nidx); if (pkeys.empty()) return mknone(); t_tscalvec values; t_tscalvec sort_values; gstate.read_column( spec.get_dependencies()[0].name(), pkeys, values); gstate.read_column( spec.get_dependencies()[1].name(), pkeys, sort_values); auto minmax_idx = get_minmax_idx(sort_values, spec.get_sort_type()); switch (spec.get_sort_type()) { case SORTTYPE_ASCENDING: case SORTTYPE_ASCENDING_ABS: { if (spec.agg() == AGGTYPE_FIRST) { if (minmax_idx.m_min >= 0) { return values[minmax_idx.m_min]; } } else { if (minmax_idx.m_max >= 0) { return values[minmax_idx.m_max]; } } } break; case SORTTYPE_DESCENDING: case SORTTYPE_DESCENDING_ABS: { if (spec.agg() == AGGTYPE_FIRST) { if (minmax_idx.m_max >= 0) { return values[minmax_idx.m_max]; } } else { if (minmax_idx.m_min >= 0) { return values[minmax_idx.m_min]; } } } break; default: { // return none } } return mknone(); } t_bool t_stree::node_exists(t_uindex idx) { iter_by_idx iter = m_nodes->get().find(idx); return iter != m_nodes->get().end(); } t_table* t_stree::get_aggtable() { return m_aggregates.get(); } std::pair t_stree::insert_node(const t_tnode& node) { return m_nodes->insert(node); } t_bool t_stree::has_deltas() const { return m_has_delta; } void t_stree::get_sortby_path(t_uindex idx, t_tscalvec& rval) const { t_uindex curidx = idx; if (curidx == 0) return; while (1) { iter_by_idx iter = m_nodes->get().find(curidx); rval.push_back(iter->m_sort_value); curidx = iter->m_pidx; if (curidx == 0) { break; } } return; } void t_stree::set_has_deltas(t_bool v) { m_has_delta = v; } } // end namespace perspective ",16138,True,3156.1551485470122,median "== Writing HTTP servers and clients Vert.x allows you to easily write non blocking HTTP clients and servers. === Creating an HTTP Server The simplest way to create an HTTP server, using all default options is as follows: [source,java] ---- HttpServer server = vertx.createHttpServer(); ---- === Configuring an HTTP server If you don't want the default, a server can be configured by passing in a `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html[HttpServerOptions]` instance when creating it: [source,java] ---- HttpServerOptions options = new HttpServerOptions().setMaxWebsocketFrameSize(1000000); HttpServer server = vertx.createHttpServer(options); ---- === Start the Server Listening To tell the server to listen for incoming requests you use one of the `link:../../apidocs/io/vertx/core/http/HttpServer.html#listen--[listen]` alternatives. To tell the server to listen at the host and port as specified in the options: [source,java] ---- HttpServer server = vertx.createHttpServer(); server.listen(); ---- Or to specify the host and port in the call to listen, ignoring what is configured in the options: [source,java] ---- HttpServer server = vertx.createHttpServer(); server.listen(8080, ""myhost.com""); ---- The default host is `0.0.0.0` which means 'listen on all available addresses' and the default port is `80`. The actual bind is asynchronous so the server might not actually be listening until some time *after* the call to listen has returned. If you want to be notified when the server is actually listening you can provide a handler to the `listen` call. For example: [source,java] ---- HttpServer server = vertx.createHttpServer(); server.listen(8080, ""myhost.com"", res -> { if (res.succeeded()) { System.out.println(""Server is now listening!""); } else { System.out.println(""Failed to bind!""); } }); ---- === Getting notified of incoming requests To be notified when a request arrives you need to set a `link:../../apidocs/io/vertx/core/http/HttpServer.html#requestHandler-io.vertx.core.Handler-[requestHandler]`: [source,java] ---- HttpServer server = vertx.createHttpServer(); server.requestHandler(request -> { // Handle the request in here }); ---- === Handling requests When a request arrives, the request handler is called passing in an instance of `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html[HttpServerRequest]`. This object represents the server side HTTP request. The handler is called when the headers of the request have been fully read. If the request contains a body, that body will arrive at the server some time after the request handler has been called. The server request object allows you to retrieve the `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#uri--[uri]`, `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#path--[path]`, `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#params--[params]` and `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#headers--[headers]`, amongst other things. Each server request object is associated with one server response object. You use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#response--[response]` to get a reference to the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html[HttpServerResponse]` object. Here's a simple example of a server handling a request and replying with ""hello world"" to it. [source,java] ---- vertx.createHttpServer().requestHandler(request -> { request.response().end(""Hello world""); }).listen(8080); ---- ==== Request version The version of HTTP specified in the request can be retrieved with `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#version--[version]` ==== Request method Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#method--[method]` to retrieve the HTTP method of the request. (i.e. whether it's GET, POST, PUT, DELETE, HEAD, OPTIONS, etc). ==== Request URI Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#uri--[uri]` to retrieve the URI of the request. Note that this is the actual URI as passed in the HTTP request, and it's almost always a relative URI. The URI is as defined in http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html[Section 5.1.2 of the HTTP specification - Request-URI] ==== Request path Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#path--[path]` to return the path part of the URI For example, if the request URI was: a/b/c/page.html?param1=abc¶m2=xyz Then the path would be /a/b/c/page.html ==== Request query Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#query--[query]` to return the query part of the URI For example, if the request URI was: a/b/c/page.html?param1=abc¶m2=xyz Then the query would be param1=abc¶m2=xyz ==== Request headers Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#headers--[headers]` to return the headers of the HTTP request. This returns an instance of `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]` - which is like a normal Map or Hash but allows multiple values for the same key - this is because HTTP allows multiple header values with the same key. It also has case-insensitive keys, that means you can do the following: [source,java] ---- MultiMap headers = request.headers(); // Get the User-Agent: System.out.println(""User agent is "" + headers.get(""user-agent"")); // You can also do this and get the same result: System.out.println(""User agent is "" + headers.get(""User-Agent"")); ---- ==== Request parameters Use `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#params--[params]` to return the parameters of the HTTP request. Just like `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#headers--[headers]` this returns an instance of `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]` as there can be more than one parameter with the same name. Request parameters are sent on the request URI, after the path. For example if the URI was: /page.html?param1=abc¶m2=xyz Then the parameters would contain the following: ---- param1: 'abc' param2: 'xyz ---- Note that these request parameters are retrieved from the URL of the request. If you have form attributes that have been sent as part of the submission of an HTML form submitted in the body of a `multi-part/form-data` request then they will not appear in the params here. ==== Remote address The address of the sender of the request can be retrieved with `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#remoteAddress--[remoteAddress]`. ==== Absolute URI The URI passed in an HTTP request is usually relative. If you wish to retrieve the absolute URI corresponding to the request, you can get it with `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#absoluteURI--[absoluteURI]` ==== End handler The `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#endHandler-io.vertx.core.Handler-[endHandler]` of the request is invoked when the entire request, including any body has been fully read. ==== Reading Data from the Request Body Often an HTTP request contains a body that we want to read. As previously mentioned the request handler is called when just the headers of the request have arrived so the request object does not have a body at that point. This is because the body may be very large (e.g. a file upload) and we don't generally want to buffer the entire body in memory before handing it to you, as that could cause the server to exhaust available memory. To receive the body, you can use the `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#handler-io.vertx.core.Handler-[handler]` on the request, this will get called every time a chunk of the request body arrives. Here's an example: [source,java] ---- request.handler(buffer -> { System.out.println(""I have received a chunk of the body of length "" + buffer.length()); }); ---- The object passed into the handler is a `link:../../apidocs/io/vertx/core/buffer/Buffer.html[Buffer]`, and the handler can be called multiple times as data arrives from the network, depending on the size of the body. In some cases (e.g. if the body is small) you will want to aggregate the entire body in memory, so you could do the aggregation yourself as follows: [source,java] ---- Buffer totalBuffer = Buffer.buffer(); request.handler(buffer -> { System.out.println(""I have received a chunk of the body of length "" + buffer.length()); totalBuffer.appendBuffer(buffer); }); request.endHandler(v -> { System.out.println(""Full body received, length = "" + totalBuffer.length()); }); ---- This is such a common case, that Vert.x provides a `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#bodyHandler-io.vertx.core.Handler-[bodyHandler]` to do this for you. The body handler is called once when all the body has been received: [source,java] ---- request.bodyHandler(totalBuffer -> { System.out.println(""Full body received, length = "" + totalBuffer.length()); }); ---- ==== Pumping requests The request object is a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` so you can pump the request body to any `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` instance. See the chapter on <> for a detailed explanation. ==== Handling HTML forms HTML forms can be submitted with either a content type of `application/x-www-form-urlencoded` or `multipart/form-data`. For url encoded forms, the form attributes are encoded in the url, just like normal query parameters. For multi-part forms they are encoded in the request body, and as such are not available until the entire body has been read from the wire. Multi-part forms can also contain file uploads. If you want to retrieve the attributes of a multi-part form you should tell Vert.x that you expect to receive such a form *before* any of the body is read by calling `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#setExpectMultipart-boolean-[setExpectMultipart]` with true, and then you should retrieve the actual attributes using `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#formAttributes--[formAttributes]` once the entire body has been read: [source,java] ---- server.requestHandler(request -> { request.setExpectMultipart(true); request.endHandler(v -> { // The body has now been fully read, so retrieve the form attributes MultiMap formAttributes = request.formAttributes(); }); }); ---- ==== Handling form file uploads Vert.x can also handle file uploads which are encoded in a multi-part request body. To receive file uploads you tell Vert.x to expect a multi-part form and set an `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#uploadHandler-io.vertx.core.Handler-[uploadHandler]` on the request. This handler will be called once for every upload that arrives on the server. The object passed into the handler is a `link:../../apidocs/io/vertx/core/http/HttpServerFileUpload.html[HttpServerFileUpload]` instance. [source,java] ---- server.requestHandler(request -> { request.setExpectMultipart(true); request.uploadHandler(upload -> { System.out.println(""Got a file upload "" + upload.name()); }); }); ---- File uploads can be large we don't provide the entire upload in a single buffer as that might result in memory exhaustion, instead, the upload data is received in chunks: [source,java] ---- request.uploadHandler(upload -> { upload.handler(chunk -> { System.out.println(""Received a chunk of the upload of length "" + chunk.length()); }); }); ---- The upload object is a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` so you can pump the request body to any `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` instance. See the chapter on <> for a detailed explanation. If you just want to upload the file to disk somewhere you can use `link:../../apidocs/io/vertx/core/http/HttpServerFileUpload.html#streamToFileSystem-java.lang.String-[streamToFileSystem]`: [source,java] ---- request.uploadHandler(upload -> { upload.streamToFileSystem(""myuploads_directory/"" + upload.filename()); }); ---- WARNING: Make sure you check the filename in a production system to avoid malicious clients uploading files to arbitrary places on your filesystem. See <> for more information. === Sending back responses The server response object is an instance of `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html[HttpServerResponse]` and is obtained from the request with `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#response--[response]`. You use the response object to write a response back to the HTTP client. ==== Setting status code and message The default HTTP status code for a response is `200`, representing `OK`. Use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#setStatusCode-int-[setStatusCode]` to set a different code. You can also specify a custom status message with `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#setStatusMessage-java.lang.String-[setStatusMessage]`. If you don't specify a status message, the default one corresponding to the status code will be used. ==== Writing HTTP responses To write data to an HTTP response, you use one the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#write-io.vertx.core.buffer.Buffer-[write]` operations. These can be invoked multiple times before the response is ended. They can be invoked in a few ways: With a single buffer: [source,java] ---- HttpServerResponse response = request.response(); response.write(buffer); ---- With a string. In this case the string will encoded using UTF-8 and the result written to the wire. [source,java] ---- HttpServerResponse response = request.response(); response.write(""hello world!""); ---- With a string and an encoding. In this case the string will encoded using the specified encoding and the result written to the wire. [source,java] ---- HttpServerResponse response = request.response(); response.write(""hello world!"", ""UTF-16""); ---- Writing to a response is asynchronous and always returns immediately after the write has been queued. If you are just writing a single string or buffer to the HTTP response you can write it and end the response in a single call to the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#end-java.lang.String-[end]` The first call to write results in the response header being being written to the response. Consequently, if you are not using HTTP chunking then you must set the `Content-Length` header before writing to the response, since it will be too late otherwise. If you are using HTTP chunking you do not have to worry. ==== Ending HTTP responses Once you have finished with the HTTP response you should `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#end-java.lang.String-[end]` it. This can be done in several ways: With no arguments, the response is simply ended. [source,java] ---- HttpServerResponse response = request.response(); response.write(""hello world!""); response.end(); ---- It can also be called with a string or buffer in the same way `write` is called. In this case it's just the same as calling write with a string or buffer followed by calling end with no arguments. For example: [source,java] ---- HttpServerResponse response = request.response(); response.end(""hello world!""); ---- ==== Closing the underlying connection You can close the underlying TCP connection with `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#close--[close]`. Non keep-alive connections will be automatically closed by Vert.x when the response is ended. Keep-alive connections are not automatically closed by Vert.x by default. If you want keep-alive connections to be closed after an idle time, then you configure `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setIdleTimeout-int-[setIdleTimeout]`. ==== Setting response headers HTTP response headers can be added to the response by adding them directly to the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#headers--[headers]`: [source,java] ---- HttpServerResponse response = request.response(); MultiMap headers = response.headers(); headers.set(""content-type"", ""text/html""); headers.set(""other-header"", ""wibble""); ---- Or you can use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#putHeader-java.lang.String-java.lang.String-[putHeader]` [source,java] ---- HttpServerResponse response = request.response(); response.putHeader(""content-type"", ""text/html"").putHeader(""other-header"", ""wibble""); ---- Headers must all be added before any parts of the response body are written. ==== Chunked HTTP responses and trailers Vert.x supports http://en.wikipedia.org/wiki/Chunked_transfer_encoding[HTTP Chunked Transfer Encoding]. This allows the HTTP response body to be written in chunks, and is normally used when a large response body is being streamed to a client and the total size is not known in advance. You put the HTTP response into chunked mode as follows: [source,java] ---- HttpServerResponse response = request.response(); response.setChunked(true); ---- Default is non-chunked. When in chunked mode, each call to one of the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#write-io.vertx.core.buffer.Buffer-[write]` methods will result in a new HTTP chunk being written out. When in chunked mode you can also write HTTP response trailers to the response. These are actually written in the final chunk of the response. To add trailers to the response, add them directly to the `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#trailers--[trailers]`. [source,java] ---- HttpServerResponse response = request.response(); response.setChunked(true); MultiMap trailers = response.trailers(); trailers.set(""X-wibble"", ""woobble"").set(""X-quux"", ""flooble""); ---- Or use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#putTrailer-java.lang.String-java.lang.String-[putTrailer]`. [source,java] ---- HttpServerResponse response = request.response(); response.setChunked(true); response.putTrailer(""X-wibble"", ""woobble"").putTrailer(""X-quux"", ""flooble""); ---- ==== Serving files directly from disk If you were writing a web server, one way to serve a file from disk would be to open it as an `link:../../apidocs/io/vertx/core/file/AsyncFile.html[AsyncFile]` and pump it to the HTTP response. Or you could load it it one go using `link:../../apidocs/io/vertx/core/file/FileSystem.html#readFile-java.lang.String-io.vertx.core.Handler-[readFile]` and write it straight to the response. Alternatively, Vert.x provides a method which allows you to serve a file from disk to an HTTP response in one operation. Where supported by the underlying operating system this may result in the OS directly transferring bytes from the file to the socket without being copied through user-space at all. This is done by using `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#sendFile-java.lang.String-[sendFile]`, and is usually more efficient for large files, but may be slower for small files. Here's a very simple web server that serves files from the file system using sendFile: [source,java] ---- vertx.createHttpServer().requestHandler(request -> { String file = """"; if (request.path().equals(""/"")) { file = ""index.html""; } else if (!request.path().contains("".."")) { file = request.path(); } request.response().sendFile(""web/"" + file); }).listen(8080); ---- Sending a file is asynchronous and may not complete until some time after the call has returned. If you want to be notified when the file has been writen you can use `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#sendFile-java.lang.String-io.vertx.core.Handler-[sendFile]` NOTE: If you use `sendFile` while using HTTPS it will copy through user-space, since if the kernel is copying data directly from disk to socket it doesn't give us an opportunity to apply any encryption. WARNING: If you're going to write web servers directly using Vert.x be careful that users cannot exploit the path to access files outside the directory from which you want to serve them. It may be safer instead to use Vert.x Web. When there is a need to serve just a segment of a file, say starting from a given byte, you can achieve this by doing: [source,java] ---- vertx.createHttpServer().requestHandler(request -> { long offset = 0; try { offset = Long.parseLong(request.getParam(""start"")); } catch (NumberFormatException e) { // error handling... } long end = Long.MAX_VALUE; try { end = Long.parseLong(request.getParam(""end"")); } catch (NumberFormatException e) { // error handling... } request.response().sendFile(""web/mybigfile.txt"", offset, end); }).listen(8080); ---- You are not required to supply the length if you want to send a file starting from an offset until the end, in this case you can just do: [source,java] ---- vertx.createHttpServer().requestHandler(request -> { long offset = 0; try { offset = Long.parseLong(request.getParam(""start"")); } catch (NumberFormatException e) { // error handling... } request.response().sendFile(""web/mybigfile.txt"", offset); }).listen(8080); ---- ==== Pumping responses The server response is a `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` instance so you can pump to it from any `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]`, e.g. `link:../../apidocs/io/vertx/core/file/AsyncFile.html[AsyncFile]`, `link:../../apidocs/io/vertx/core/net/NetSocket.html[NetSocket]`, `link:../../apidocs/io/vertx/core/http/WebSocket.html[WebSocket]` or `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html[HttpServerRequest]`. Here's an example which echoes the request body back in the response for any PUT methods. It uses a pump for the body, so it will work even if the HTTP request body is much larger than can fit in memory at any one time: [source,java] ---- vertx.createHttpServer().requestHandler(request -> { HttpServerResponse response = request.response(); if (request.method() == HttpMethod.PUT) { response.setChunked(true); Pump.pump(request, response).start(); request.endHandler(v -> response.end()); } else { response.setStatusCode(400).end(); } }).listen(8080); ---- === HTTP Compression Vert.x comes with support for HTTP Compression out of the box. This means you are able to automatically compress the body of the responses before they are sent back to the client. If the client does not support HTTP compression the responses are sent back without compressing the body. This allows to handle Client that support HTTP Compression and those that not support it at the same time. To enable compression use can configure it with `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setCompressionSupported-boolean-[setCompressionSupported]`. By default compression is not enabled. When HTTP compression is enabled the server will check if the client includes an `Accept-Encoding` header which includes the supported compressions. Commonly used are deflate and gzip. Both are supported by Vert.x. If such a header is found the server will automatically compress the body of the response with one of the supported compressions and send it back to the client. Be aware that compression may be able to reduce network traffic but is more CPU-intensive. === Creating an HTTP client You create an `link:../../apidocs/io/vertx/core/http/HttpClient.html[HttpClient]` instance with default options as follows: [source,java] ---- HttpClient client = vertx.createHttpClient(); ---- If you want to configure options for the client, you create it as follows: [source,java] ---- HttpClientOptions options = new HttpClientOptions().setKeepAlive(false); HttpClient client = vertx.createHttpClient(options); ---- === Making requests The http client is very flexible and there are various ways you can make requests with it. Often you want to make many requests to the same host/port with an http client. To avoid you repeating the host/port every time you make a request you can configure the client with a default host/port: [source,java] ---- HttpClientOptions options = new HttpClientOptions().setDefaultHost(""wibble.com""); // Can also set default port if you want... HttpClient client = vertx.createHttpClient(options); client.getNow(""/some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); ---- Alternatively if you find yourself making lots of requests to different host/ports with the same client you can simply specify the host/port when doing the request. [source,java] ---- HttpClient client = vertx.createHttpClient(); // Specify both port and host name client.getNow(8080, ""myserver.mycompany.com"", ""/some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); // This time use the default port 80 but specify the host name client.getNow(""foo.othercompany.com"", ""/other-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); ---- Both methods of specifying host/port are supported for all the different ways of making requests with the client. ==== Simple requests with no request body Often, you'll want to make HTTP requests with no request body. This is usually the case with HTTP GET, OPTIONS and HEAD requests. The simplest way to do this with the Vert.x http client is using the methods prefixed with `Now`. For example `link:../../apidocs/io/vertx/core/http/HttpClient.html#getNow-int-java.lang.String-java.lang.String-io.vertx.core.Handler-[getNow]`. These methods create the http request and send it in a single method call and allow you to provide a handler that will be called with the http response when it comes back. [source,java] ---- HttpClient client = vertx.createHttpClient(); // Send a GET request client.getNow(""/some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); // Send a GET request client.headNow(""/other-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); ---- ==== Writing general requests At other times you don't know the request method you want to send until run-time. For that use case we provide general purpose request methods such as `link:../../apidocs/io/vertx/core/http/HttpClient.html#request-io.vertx.core.http.HttpMethod-int-java.lang.String-java.lang.String-[request]` which allow you to specify the HTTP method at run-time: [source,java] ---- HttpClient client = vertx.createHttpClient(); client.request(HttpMethod.GET, ""some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }).end(); client.request(HttpMethod.POST, ""foo-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }).end(""some-data""); ---- ==== Writing request bodies Sometimes you'll want to write requests which have a body, or perhaps you want to write headers to a request before sending it. To do this you can call one of the specific request methods such as `link:../../apidocs/io/vertx/core/http/HttpClient.html#post-int-java.lang.String-java.lang.String-[post]` or one of the general purpose request methods such as `link:../../apidocs/io/vertx/core/http/HttpClient.html#request-io.vertx.core.http.HttpMethod-int-java.lang.String-java.lang.String-[request]`. These methods don't send the request immediately, but instead return an instance of `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` which can be used to write to the request body or write headers. Here are some examples of writing a POST request with a body: m [source,java] ---- HttpClient client = vertx.createHttpClient(); HttpClientRequest request = client.post(""some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); // Now do stuff with the request request.putHeader(""content-length"", ""1000""); request.putHeader(""content-type"", ""text/plain""); request.write(body); // Make sure the request is ended when you're done with it request.end(); // Or fluently: client.post(""some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }).putHeader(""content-length"", ""1000"").putHeader(""content-type"", ""text/plain"").write(body).end(); // Or event more simply: client.post(""some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }).putHeader(""content-type"", ""text/plain"").end(body); ---- Methods exist to write strings in UTF-8 encoding and in any specific encoding and to write buffers: [source,java] ---- request.write(""some data""); // Write string encoded in specific encoding request.write(""some other data"", ""UTF-16""); // Write a buffer Buffer buffer = Buffer.buffer(); buffer.appendInt(123).appendLong(245l); request.write(buffer); ---- If you are just writing a single string or buffer to the HTTP request you can write it and end the request in a single call to the `end` function. [source,java] ---- request.end(""some simple data""); // Write buffer and end the request (send it) in a single call Buffer buffer = Buffer.buffer().appendDouble(12.34d).appendLong(432l); request.end(buffer); ---- When you're writing to a request, the first call to `write` will result in the request headers being written out to the wire. The actual write is asynchronous and might not occur until some time after the call has returned. Non-chunked HTTP requests with a request body require a `Content-Length` header to be provided. Consequently, if you are not using chunked HTTP then you must set the `Content-Length` header before writing to the request, as it will be too late otherwise. If you are calling one of the `end` methods that take a string or buffer then Vert.x will automatically calculate and set the `Content-Length` header before writing the request body. If you are using HTTP chunking a a `Content-Length` header is not required, so you do not have to calculate the size up-front. ==== Writing request headers You can write headers to a request using the `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#headers--[headers]` multi-map as follows: [source,java] ---- MultiMap headers = request.headers(); headers.set(""content-type"", ""application/json"").set(""other-header"", ""foo""); ---- The headers are an instance of `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]` which provides operations for adding, setting and removing entries. Http headers allow more than one value for a specific key. You can also write headers using `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#putHeader-java.lang.String-java.lang.String-[putHeader]` [source,java] ---- request.putHeader(""content-type"", ""application/json"").putHeader(""other-header"", ""foo""); ---- If you wish to write headers to the request you must do so before any part of the request body is written. ==== Ending HTTP requests Once you have finished with the HTTP request you must end it with one of the `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#end-java.lang.String-[end]` operations. Ending a request causes any headers to be written, if they have not already been written and the request to be marked as complete. Requests can be ended in several ways. With no arguments the request is simply ended: [source,java] ---- request.end(); ---- Or a string or buffer can be provided in the call to `end`. This is like calling `write` with the string or buffer before calling `end` with no arguments [source,java] ---- request.end(""some-data""); // End it with a buffer Buffer buffer = Buffer.buffer().appendFloat(12.3f).appendInt(321); request.end(buffer); ---- ==== Chunked HTTP requests Vert.x supports http://en.wikipedia.org/wiki/Chunked_transfer_encoding[HTTP Chunked Transfer Encoding] for requests. This allows the HTTP request body to be written in chunks, and is normally used when a large request body is being streamed to the server, whose size is not known in advance. You put the HTTP request into chunked mode using `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#setChunked-boolean-[setChunked]`. In chunked mode each call to write will cause a new chunk to be written to the wire. In chunked mode there is no need to set the `Content-Length` of the request up-front. [source,java] ---- request.setChunked(true); // Write some chunks for (int i = 0; i < 10; i++) { request.write(""this-is-chunk-"" + i); } request.end(); ---- ==== Request timeouts You can set a timeout for a specific http request using `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#setTimeout-long-[setTimeout]`. If the request does not return any data within the timeout period an exception will be passed to the exception handler (if provided) and the request will be closed. ==== Handling exceptions You can handle exceptions corresponding to a request by setting an exception handler on the `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` instance: [source,java] ---- HttpClientRequest request = client.post(""some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); request.exceptionHandler(e -> { System.out.println(""Received exception: "" + e.getMessage()); e.printStackTrace(); }); ---- This does not handle non _2xx_ response that need to be handled in the `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html[HttpClientResponse]` code: [source, java] ---- HttpClientRequest request = client.post(""some-uri"", response -> { if (response.statusCode() == 200) { System.out.println(""Everything fine""); return; } if (response.statusCode() == 500) { System.out.println(""Unexpected behavior on the server side""); return; } }); request.end(); ---- IMPORTANT: `XXXNow` methods cannot receive an exception handler. ==== Specifying a handler on the client request Instead of providing a response handler in the call to create the client request object, alternatively, you can not provide a handler when the request is created and set it later on the request object itself, using `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#handler-io.vertx.core.Handler-[handler]`, for example: [source,java] ---- HttpClientRequest request = client.post(""some-uri""); request.handler(response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); ---- ==== Using the request as a stream The `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` instance is also a `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` which means you can pump to it from any `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` instance. For, example, you could pump a file on disk to a http request body as follows: [source,java] ---- request.setChunked(true); Pump pump = Pump.pump(file, request); file.endHandler(v -> request.end()); pump.start(); ---- === Handling http responses You receive an instance of `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html[HttpClientResponse]` into the handler that you specify in of the request methods or by setting a handler directly on the `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html[HttpClientRequest]` object. You can query the status code and the status message of the response with `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#statusCode--[statusCode]` and `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#statusMessage--[statusMessage]`. [source,java] ---- client.getNow(""some-uri"", response -> { // the status code - e.g. 200 or 404 System.out.println(""Status code is "" + response.statusCode()); // the status message e.g. ""OK"" or ""Not Found"". System.out.println(""Status message is "" + response.statusMessage()); }); ---- ==== Using the response as a stream The `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html[HttpClientResponse]` instance is also a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` which means you can pump it to any `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` instance. ==== Response headers and trailers Http responses can contain headers. Use `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#headers--[headers]` to get the headers. The object returned is a `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]` as HTTP headers can contain multiple values for single keys. [source,java] ---- String contentType = response.headers().get(""content-type""); String contentLength = response.headers().get(""content-lengh""); ---- Chunked HTTP responses can also contain trailers - these are sent in the last chunk of the response body. You use `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#trailers--[trailers]` to get the trailers. Trailers are also a `link:../../apidocs/io/vertx/core/MultiMap.html[MultiMap]`. ==== Reading the request body The response handler is called when the headers of the response have been read from the wire. If the response has a body this might arrive in several pieces some time after the headers have been read. We don't wait for all the body to arrive before calling the response handler as the response could be very large and we might be waiting a long time, or run out of memory for large responses. As parts of the response body arrive, the `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#handler-io.vertx.core.Handler-[handler]` is called with a `link:../../apidocs/io/vertx/core/buffer/Buffer.html[Buffer]` representing the piece of the body: [source,java] ---- client.getNow(""some-uri"", response -> { response.handler(buffer -> { System.out.println(""Received a part of the response body: "" + buffer); }); }); ---- If you know the response body is not very large and want to aggregate it all in memory before handling it, you can either aggregate it yourself: [source,java] ---- client.getNow(""some-uri"", response -> { // Create an empty buffer Buffer totalBuffer = Buffer.buffer(); response.handler(buffer -> { System.out.println(""Received a part of the response body: "" + buffer.length()); totalBuffer.appendBuffer(buffer); }); response.endHandler(v -> { // Now all the body has been read System.out.println(""Total response body length is "" + totalBuffer.length()); }); }); ---- Or you can use the convenience `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#bodyHandler-io.vertx.core.Handler-[bodyHandler]` which is called with the entire body when the response has been fully read: [source,java] ---- client.getNow(""some-uri"", response -> { response.bodyHandler(totalBuffer -> { // Now all the body has been read System.out.println(""Total response body length is "" + totalBuffer.length()); }); }); ---- ==== Response end handler The response `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#endHandler-io.vertx.core.Handler-[endHandler]` is called when the entire response body has been read or immediately after the headers have been read and the response handler has been called if there is no body. ==== Reading cookies from the response You can retrieve the list of cookies from a response using `link:../../apidocs/io/vertx/core/http/HttpClientResponse.html#cookies--[cookies]`. Alternatively you can just parse the `Set-Cookie` headers yourself in the response. ==== 100-Continue handling According to the http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html[HTTP 1.1 specification] a client can set a header `Expect: 100-Continue` and send the request header before sending the rest of the request body. The server can then respond with an interim response status `Status: 100 (Continue)` to signify to the client that it is ok to send the rest of the body. The idea here is it allows the server to authorise and accept/reject the request before large amounts of data are sent. Sending large amounts of data if the request might not be accepted is a waste of bandwidth and ties up the server in reading data that it will just discard. Vert.x allows you to set a `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#continueHandler-io.vertx.core.Handler-[continueHandler]` on the client request object This will be called if the server sends back a `Status: 100 (Continue)` response to signify that it is ok to send the rest of the request. This is used in conjunction with `link:../../apidocs/io/vertx/core/http/HttpClientRequest.html#sendHead--[sendHead]`to send the head of the request. Here's an example: [source,java] ---- HttpClientRequest request = client.put(""some-uri"", response -> { System.out.println(""Received response with status code "" + response.statusCode()); }); request.putHeader(""Expect"", ""100-Continue""); request.continueHandler(v -> { // OK to send rest of body request.write(""Some data""); request.write(""Some more data""); request.end(); }); ---- On the server side a Vert.x http server can be configured to automatically send back 100 Continue interim responses when it receives an `Expect: 100-Continue` header. This is done by setting the option `link:../../apidocs/io/vertx/core/http/HttpServerOptions.html#setHandle100ContinueAutomatically-boolean-[setHandle100ContinueAutomatically]`. If you'd prefer to decide whether to send back continue responses manually, then this property should be set to `false` (the default), then you can inspect the headers and call `link:../../apidocs/io/vertx/core/http/HttpServerResponse.html#writeContinue--[writeContinue]` if you wish the client to continue sending the body or you can reject the request by sending back a failure status code if you don't want it to send the body. For example: === Enabling compression on the client The http client comes with support for HTTP Compression out of the box. This means the client can let the remote http server know that it supports compression, and will be able to handle compressed response bodies. An http server is free to either compress with one of the supported compression algorithms or to send the body back without compressing it at all. So this is only a hint for the Http server which it may ignore at will. To tell the http server which compression is supported by the client it will include an `Accept-Encoding` header with the supported compression algorithm as value. Multiple compression algorithms are supported. In case of Vert.x this will result in the following header added: Accept-Encoding: gzip, deflate The server will choose then from one of these. You can detect if a server ompressed the body by checking for the `Content-Encoding` header in the response sent back from it. If the body of the response was compressed via gzip it will include for example the following header: Content-Encoding: gzip To enable compression set `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setTryUseCompression-boolean-[setTryUseCompression]` on the options used when creating the client. By default compression is disabled. === Pooling and keep alive Http keep alive allows http connections to be used for more than one request. This can be a more efficient use of connections when you're making multiple requests to the same server. The http client supports pooling of connections, allowing you to reuse connections between requests. For pooling to work, keep alive must be true using `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setKeepAlive-boolean-[setKeepAlive]` on the options used when configuring the client. The default value is true. When keep alive is enabled. Vert.x will add a `Connection: Keep-Alive` header to each HTTP/1.0 request sent. When keep alive is disabled. Vert.x will add a `Connection: Close` header to each HTTP/1.1 request sent to signal that the connection will be closed after completion of the response. The maximum number of connections to pool *for each server* is configured using `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setMaxPoolSize-int-[setMaxPoolSize]` When making a request with pooling enabled, Vert.x will create a new connection if there are less than the maximum number of connections already created for that server, otherwise it will add the request to a queue. Keep alive connections will not be closed by the client automatically. To close them you can close the client instance. Alternatively you can set idle timeout using `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setIdleTimeout-int-[setIdleTimeout]` - any connections not used within this timeout will be closed. Please note the idle timeout value is in seconds not milliseconds. === Pipe-lining The client also supports pipe-lining of requests on a connection. Pipe-lining means another request is sent on the same connection before the response from the preceding one has returned. Pipe-lining is not appropriate for all requests. To enable pipe-lining, it must be enabled using `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setPipelining-boolean-[setPipelining]`. By default pipe-lining is disabled. When pipe-lining is enabled requests will be written to connections without waiting for previous responses to return. === Server sharing When several HTTP servers listen on the same port, vert.x orchestrates the request handling using a round-robin strategy. Let's take a verticle creating a HTTP server such as: .io.vertx.examples.http.sharing.HttpServerVerticle [source,java] ---- vertx.createHttpServer().requestHandler(request -> { request.response().end(""Hello from server "" + this); }).listen(8080); ---- This service is listening on the port 8080. So, when this verticle is instantiated multiple times as with: `vertx run io.vertx.examples.http.sharing.HttpServerVerticle -instances 2`, what's happening ? If both verticles would bind to the same port, you would receive a socket exception. Fortunately, vert.x is handling this case for you. When you deploy another server on the same host and port as an existing server it doesn't actually try and create a new server listening on the same host/port. It binds only once to the socket. When receiving a request it calls the server handlers following a round robin strategy. Let's now imagine a client such as: [source,java] ---- vertx.setPeriodic(100, (l) -> { vertx.createHttpClient().getNow(8080, ""localhost"", ""/"", resp -> { resp.bodyHandler(body -> { System.out.println(body.toString(""ISO-8859-1"")); }); }); }); ---- Vert.x delegates the requests to one of the server sequentially: [source] ---- Hello from i.v.e.h.s.HttpServerVerticle@1 Hello from i.v.e.h.s.HttpServerVerticle@2 Hello from i.v.e.h.s.HttpServerVerticle@1 Hello from i.v.e.h.s.HttpServerVerticle@2 ... ---- Consequently the servers can scale over available cores while each Vert.x verticle instance remains strictly single threaded, and you don't have to do any special tricks like writing load-balancers in order to scale your server on your multi-core machine. === Using HTTPS with Vert.x Vert.x http servers and clients can be configured to use HTTPS in exactly the same way as net servers. Please see <> for more information. === WebSockets http://en.wikipedia.org/wiki/WebSocket[WebSockets] are a web technology that allows a full duplex socket-like connection between HTTP servers and HTTP clients (typically browsers). Vert.x supports WebSockets on both the client and server-side. ==== WebSockets on the server There are two ways of handling WebSockets on the server side. ===== WebSocket handler The first way involves providing a `link:../../apidocs/io/vertx/core/http/HttpServer.html#websocketHandler-io.vertx.core.Handler-[websocketHandler]` on the server instance. When a WebSocket connection is made to the server, the handler will be called, passing in an instance of `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html[ServerWebSocket]`. [source,java] ---- server.websocketHandler(websocket -> { System.out.println(""Connected!""); }); ---- You can choose to reject the WebSocket by calling `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html#reject--[reject]`. [source,java] ---- server.websocketHandler(websocket -> { if (websocket.path().equals(""/myapi"")) { websocket.reject(); } else { // Do something } }); ---- ===== Upgrading to WebSocket The second way of handling WebSockets is to handle the HTTP Upgrade request that was sent from the client, and call `link:../../apidocs/io/vertx/core/http/HttpServerRequest.html#upgrade--[upgrade]` on the server request. [source,java] ---- server.requestHandler(request -> { if (request.path().equals(""/myapi"")) { ServerWebSocket websocket = request.upgrade(); // Do something } else { // Reject request.response().setStatusCode(400).end(); } }); ---- ===== The server WebSocket The `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html[ServerWebSocket]` instance enables you to retrieve the `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html#headers--[headers]`, `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html#path--[path]`, `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html#query--[query]` and `link:../../apidocs/io/vertx/core/http/ServerWebSocket.html#uri--[URI]` of the HTTP request of the WebSocket handshake. ==== WebSockets on the client The Vert.x `link:../../apidocs/io/vertx/core/http/HttpClient.html[HttpClient]` supports WebSockets. You can connect a WebSocket to a server using one of the `link:../../apidocs/io/vertx/core/http/HttpClient.html#websocket-int-java.lang.String-java.lang.String-io.vertx.core.Handler-[websocket]` operations and providing a handler. The handler will be called with an instance of `link:../../apidocs/io/vertx/core/http/WebSocket.html[WebSocket]` when the connection has been made: [source,java] ---- client.websocket(""/some-uri"", websocket -> { System.out.println(""Connected!""); }); ---- ==== Writing messages to WebSockets If you wish to write a single binary WebSocket message to the WebSocket you can do this with `link:../../apidocs/io/vertx/core/http/WebSocket.html#writeBinaryMessage-io.vertx.core.buffer.Buffer-[writeBinaryMessage]`: [source,java] ---- Buffer buffer = Buffer.buffer().appendInt(123).appendFloat(1.23f); websocket.writeBinaryMessage(buffer); ---- If the WebSocket message is larger than the maximum websocket frame size as configured with `link:../../apidocs/io/vertx/core/http/HttpClientOptions.html#setMaxWebsocketFrameSize-int-[setMaxWebsocketFrameSize]` then Vert.x will split it into multiple WebSocket frames before sending it on the wire. ==== Writing frames to WebSockets A WebSocket message can be composed of multiple frames. In this case the first frame is either a _binary_ or _text_ frame followed by zero or more _continuation_ frames. The last frame in the message is marked as _final_. To send a message consisting of multiple frames you create frames using `link:../../apidocs/io/vertx/core/http/WebSocketFrame.html#binaryFrame-io.vertx.core.buffer.Buffer-boolean-[WebSocketFrame.binaryFrame]` , `link:../../apidocs/io/vertx/core/http/WebSocketFrame.html#textFrame-java.lang.String-boolean-[WebSocketFrame.textFrame]` or `link:../../apidocs/io/vertx/core/http/WebSocketFrame.html#continuationFrame-io.vertx.core.buffer.Buffer-boolean-[WebSocketFrame.continuationFrame]` and write them to the WebSocket using `link:../../apidocs/io/vertx/core/http/WebSocket.html#writeFrame-io.vertx.core.http.WebSocketFrame-[writeFrame]`. Here's an example for binary frames: [source,java] ---- WebSocketFrame frame1 = WebSocketFrame.binaryFrame(buffer1, false); websocket.writeFrame(frame1); WebSocketFrame frame2 = WebSocketFrame.continuationFrame(buffer2, false); websocket.writeFrame(frame2); // Write the final frame WebSocketFrame frame3 = WebSocketFrame.continuationFrame(buffer2, true); websocket.writeFrame(frame3); ---- In many cases you just want to send a websocket message that consists of a single final frame, so we provide a couple of shortcut methods to do that with `link:../../apidocs/io/vertx/core/http/WebSocket.html#writeFinalBinaryFrame-io.vertx.core.buffer.Buffer-[writeFinalBinaryFrame]` and `link:../../apidocs/io/vertx/core/http/WebSocket.html#writeFinalTextFrame-java.lang.String-[writeFinalTextFrame]`. Here's an example: [source,java] ---- websocket.writeFinalTextFrame(""Geronimo!""); // Send a websocket messages consisting of a single final binary frame: Buffer buff = Buffer.buffer().appendInt(12).appendString(""foo""); websocket.writeFinalBinaryFrame(buff); ---- ==== Reading frames from WebSockets To read frames from a WebSocket you use the `link:../../apidocs/io/vertx/core/http/WebSocket.html#frameHandler-io.vertx.core.Handler-[frameHandler]`. The frame handler will be called with instances of `link:../../apidocs/io/vertx/core/http/WebSocketFrame.html[WebSocketFrame]` when a frame arrives, for example: [source,java] ---- websocket.frameHandler(frame -> { System.out.println(""Received a frame of size!""); }); ---- ==== Closing WebSockets Use `link:../../apidocs/io/vertx/core/http/WebSocketBase.html#close--[close]` to close the WebSocket connection when you have finished with it. ==== Streaming WebSockets The `link:../../apidocs/io/vertx/core/http/WebSocket.html[WebSocket]` instance is also a `link:../../apidocs/io/vertx/core/streams/ReadStream.html[ReadStream]` and a `link:../../apidocs/io/vertx/core/streams/WriteStream.html[WriteStream]` so it can be used with pumps. When using a WebSocket as a write stream or a read stream it can only be used with WebSockets connections that are used with binary frames that are no split over multiple frames. === Automatic clean-up in verticles If you're creating http servers and clients from inside verticles, those servers and clients will be automatically closed when the verticle is undeployed.",12486,True,2585.566872154012,median "= Runtime Component Operator This generic Operator is capable of deploying any application image and can be imported into any runtime-specific Operator as library of application capabilities. This architecture ensures compatibility and consistency between all runtime Operators, allowing everyone to benefit from the functionality added in this project. This documentation refers to the latest codebase. For documentation and samples of older releases, please check out the link:++https://github.com/application-stacks/runtime-component-operator/releases++[main releases] page and navigate the corresponding tag. == Operator installation Use the instructions for one of the link:++../deploy/releases++[releases] to install the operator into a Kubernetes cluster. The Runtime Component Operator can be installed to: * watch own namespace * watch another namespace * watch multiple namespaces * watch all namespaces in the cluster Appropriate cluster roles and bindings are required to watch another namespace, watch multiple namespaces or watch all namespaces. NOTE: The Runtime Component Operator can only interact with resources it is given permission to interact through link:++https://kubernetes.io/docs/reference/access-authn-authz/rbac/++[Role-based access control (RBAC)]. Some of the operator features described in this document require interacting with resources in other namespaces. In that case, the operator must be installed with correct `ClusterRole` definitions. == Overview The architecture of the Runtime Component Operator follows the basic controller pattern: the Operator container with the controller is deployed into a Pod and listens for incoming resources with `Kind: RuntimeComponent`. Creating a `RuntimeComponent` custom resource (CR) triggers the Runtime Component Operator to create, update or delete Kubernetes resources needed by the application to run on your cluster. Each instance of `RuntimeComponent` CR represents the application to be deployed on the cluster: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 service: type: ClusterIP port: 9080 expose: true statefulSet: storage: size: 2Gi mountPath: ""/logs"" ---- == Configuration === Custom Resource Definition (CRD) The following table lists configurable parameters of the `RuntimeComponent` CRD. For complete OpenAPI v3 representation of these values please see link:++../deploy/crds/app.stacks_runtimecomponents_crd.yaml++[`RuntimeComponent` CRD]. Each `RuntimeComponent` CR must at least specify the `applicationImage` parameter. Specifying other parameters is optional. .Runtime Component Resource Definition |=== | Parameter | Description | `version` | The current version of the application. Label `app.kubernetes.io/version` will be added to all resources when the version is defined. | `serviceAccountName` | The name of the OpenShift service account to be used during deployment. | `applicationImage` | The Docker image name to be deployed. On OpenShift, it can also be set to `/[:]` to reference an image from an image stream. If `` and `` values are not defined, they default to the namespace of the CR and the value of `latest`, respectively. | `applicationName` | The name of the application this resource is part of. If not specified, it defaults to the name of the CR. | `createAppDefinition` | A boolean to toggle the automatic configuration of Kubernetes resources for the `RuntimeComponent` CR to allow creation of an application definition by link:++https://kappnav.io++[kAppNav]. The default value is `true`. See link:++#kubernetes-application-navigator-kappnav-support++[Application Navigator] for more information. | `pullPolicy` | The policy used when pulling the image. One of: `Always`, `Never`, and `IfNotPresent`. | `pullSecret` | If using a registry that requires authentication, the name of the secret containing credentials. | `initContainers` | The list of link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#container-v1-core++[Init Container] definitions. | `sidecarContainers` | The list of `sidecar` containers. These are additional containers to be added to the pods. Note: Sidecar containers should not be named `app`. | `architecture` | An array of architectures to be considered for deployment. Their position in the array indicates preference. | `bindings.embedded` | A YAML object that represents a `ServiceBindingRequest` custom resource. | `bindings.autoDetect` | A boolean to toggle whether the operator should automatically detect and use a `ServiceBindingRequest` resource with `-binding` naming format. The default value for this parameter is `true`. | `bindings.resourceRef` | The name of a `ServiceBindingRequest` custom resource created manually in the same namespace as the application. | `bindings.expose.enabled` | A boolean to toggle whether the operator expose the application as a bindable service. The default value for this parameter is `false`. | `service.port` | The port exposed by the container. | `service.targetPort` | The port that the operator assigns to containers inside pods. Defaults to the value of `service.port`. | `service.portName` | The name for the port exposed by the container. | `service.ports` | An array consisting of service ports. | `service.type` | The Kubernetes link:++https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types++[Service Type]. | `service.nodePort` | Node proxies this port into your service. Please note once this port is set to a non-zero value it cannot be reset to zero. | `service.annotations` | Annotations to be added to the service. | `service.certificate` | A YAML object that represents a link:++https://cert-manager.io/docs/reference/api-docs/#cert-manager.io/v1alpha2.CertificateSpec++[Certificate]. | `service.certificateSecretRef` | A name of a secret that already contains TLS key, certificate and CA to be mounted in the pod. | `service.provides.category` | Service binding type to be provided by this CR. At this time, the only allowed value is `openapi`. | `service.provides.protocol` | Protocol of the provided service. Defauts to `http`. | `service.provides.context` | Specifies context root of the service. | `service.provides.auth.username` | Optional value to specify username as link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#secretkeyselector-v1-core++[SecretKeySelector]. | `service.provides.auth.password` | Optional value to specify password as link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#secretkeyselector-v1-core++[SecretKeySelector]. | `service.consumes` | An array consisting of services to be consumed by the `RuntimeComponent`. | `service.consumes[].category` | The type of service binding to be consumed. At this time, the only allowed value is `openapi`. | `service.consumes[].name` | The name of the service to be consumed. If binding to a `RuntimeComponent`, then this would be the provider's CR name. | `service.consumes[].namespace` | The namespace of the service to be consumed. If binding to a `RuntimeComponent`, then this would be the provider's CR namespace. | `service.consumes[].mountPath` | Optional field to specify which location in the pod, service binding secret should be mounted. If not specified, the secret keys would be injected as environment variables. | `createKnativeService` | A boolean to toggle the creation of Knative resources and usage of Knative serving. | `expose` | A boolean that toggles the external exposure of this deployment via a Route or a Knative Route resource. | `deployment.updateStrategy` | A field to specify the update strategy of the deployment. For more information, see link:++https://kubernetes.io/docs/concepts/workloads/controllers/deployment/#strategy++[updateStrategy] | `deployment.updateStrategy.type` | The type of update strategy of the deployment. The type can be set to `RollingUpdate` or `Recreate`, where `RollingUpdate` is the default update strategy. | `deployment.annotations` | Annotations to be added only to the deployment and resources owned by the deployment. | `statefulSet.updateStrategy` | A field to specify the update strategy of the StatefulSet. For more information, see link:++https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#update-strategies++[updateStrategy] | `statefulSet.updateStrategy.type` | The type of update strategy of the StatefulSet. The type can be set to `RollingUpdate` or `OnDelete`, where `RollingUpdate` is the default update strategy. | `statefulSet.annotations` | Annotations to be added only to the StatefulSet and resources owned by the StatefulSet. | `replicas` | The static number of desired replica pods that run simultaneously. | `autoscaling.maxReplicas` | Required field for autoscaling. Upper limit for the number of pods that can be set by the autoscaler. It cannot be lower than the minimum number of replicas. | `autoscaling.minReplicas` | Lower limit for the number of pods that can be set by the autoscaler. | `autoscaling.targetCPUUtilizationPercentage` | Target average CPU utilization (represented as a percentage of requested CPU) over all the pods. | `resourceConstraints.requests.cpu` | The minimum required CPU core. Specify integers, fractions (e.g. 0.5), or millicore values(e.g. 100m, where 100m is equivalent to .1 core). Required field for autoscaling. | `resourceConstraints.requests.memory` | The minimum memory in bytes. Specify integers with one of these suffixes: E, P, T, G, M, K, or power-of-two equivalents: Ei, Pi, Ti, Gi, Mi, Ki. | `resourceConstraints.limits.cpu` | The upper limit of CPU core. Specify integers, fractions (e.g. 0.5), or millicores values(e.g. 100m, where 100m is equivalent to .1 core). | `resourceConstraints.limits.memory` | The memory upper limit in bytes. Specify integers with suffixes: E, P, T, G, M, K, or power-of-two equivalents: Ei, Pi, Ti, Gi, Mi, Ki. | `env` | An array of environment variables following the format of `{name, value}`, where value is a simple string. It may also follow the format of `{name, valueFrom}`, where valueFrom refers to a value in a `ConfigMap` or `Secret` resource. See link:++#environment-variables++[Environment variables] for more info. | `envFrom` | An array of references to `ConfigMap` or `Secret` resources containing environment variables. Keys from `ConfigMap` or `Secret` resources become environment variable names in your container. See link:++#environment-variables++[Environment variables] for more info. | `readinessProbe` | A YAML object configuring the link:++https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-readiness-probes++[Kubernetes readiness probe] that controls when the pod is ready to receive traffic. | `livenessProbe` | A YAML object configuring the link:++https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-liveness-http-request++[Kubernetes liveness probe] that controls when Kubernetes needs to restart the pod. | `startupProbe` | A YAML object configuring the link:++https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-startup-probes++[Kubernetes startup probe] that controls when Kubernetes needs to startup the pod on its first initialization. | `volumes` | A YAML object that represents a link:++https://kubernetes.io/docs/concepts/storage/volumes++[pod volume]. | `volumeMounts` | A YAML object that represents a link:++https://kubernetes.io/docs/concepts/storage/volumes/++[pod volumeMount]. | `statefulSet.storage.size` | A convenient field to set the size of the persisted storage. Can be overridden by the `storage.volumeClaimTemplate` property. | `statefulSet.storage.mountPath` | The directory inside the container where this persisted storage will be bound to. | `statefulSet.storage.volumeClaimTemplate` | A YAML object that represents a link:++https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#components++[volumeClaimTemplate] component of a `StatefulSet`. | `monitoring.labels` | Labels to set on link:++https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#servicemonitor++[ServiceMonitor]. | `monitoring.endpoints` | A YAML snippet representing an array of link:++https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#endpoint++[Endpoint] component from ServiceMonitor. | `route.annotations` | Annotations to be added to the Route. | `route.host` | Hostname to be used for the Route. | `route.path` | Path to be used for Route. | `route.termination` | TLS termination policy. Can be one of `edge`, `reencrypt` and `passthrough`. | `route.insecureEdgeTerminationPolicy` | HTTP traffic policy with TLS enabled. Can be one of `Allow`, `Redirect` and `None`. | `route.certificate` | A YAML object that represents a link:++https://cert-manager.io/docs/reference/api-docs/#cert-manager.io/v1alpha2.CertificateSpec++[Certificate]. | `route.certificateSecretRef` | A name of a secret that already contains TLS key, certificate and CA to be used in the route. Also can contain destination CA certificate. | `affinity.nodeAffinity` | A YAML object that represents a link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#nodeaffinity-v1-core++[NodeAffinity]. | `affinity.nodeAffinityLabels` | A YAML object that contains set of required labels and their values. | `affinity.podAffinity` | A YAML object that represents a link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#podaffinity-v1-core++[PodAffinity]. | `affinity.podAntiAffinity` | A YAML object that represents a link:++https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17/#podantiaffinity-v1-core++[PodAntiAffinity]. |=== === Basic usage To deploy a Docker image that contains a runtime component to a Kubernetes environment, you can use the following CR: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 ---- The `applicationImage` value must be defined in the `RuntimeComponent` CR. On OpenShift, the operator tries to find an image stream name with the `applicationImage` value. The operator falls back to the registry lookup if it is not able to find any image stream that matches the value. If you want to distinguish an image stream called `my-company/my-app` (project: `my-company`, image stream name: `my-app`) from the Docker Hub `my-company/my-app` image, you can use the full image reference as `docker.io/my-company/my-app`. To get information on the deployed CR, use either of the following: [source,sh] ---- oc get runtimecomponent my-app oc get comp my-app ---- The short name for `runtimecomponent` is `comp`. === Image Streams To deploy an image from an image stream, use the following CR: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: my-namespace/my-image-stream:1.0 ---- The previous example looks up the `1.0` tag from the `my-image-stream` image stream in the `my-namespace` project and populates the CR `.status.imageReference` field with the exact referenced image similar to the following one: `image-registry.openshift-image-registry.svc:5000/my-namespace/my-image-stream@sha256:8a829d579b114a9115c0a7172d089413c5d5dd6120665406aae0600f338654d8`. The operator watches the specified image stream and deploys new images as new ones are available for the specified tag. To reference an image stream, the `applicationImage` parameter must follow the `/[:]` format. If `` or `` is not specified, the operator defaults the values to the namespace of the CR and the value of `latest`, respectively. For example, the `applicationImage: my-image-stream` configuration is the same as the `applicationImage: my-namespace/my-image-stream:latest` configuration. The Operator tries to find an image stream name first with the `/[:]` format and falls back to the registry lookup if it is not able to find any image stream that matches the value. _This feature is only available if you are running on OKD or OpenShift._ NOTE: The operator requires `ClusterRole` permissions if the image stream resource is in another namespace. === Service account The operator can create a `ServiceAccount` resource when deploying a `RuntimeComponent` custom resource (CR). If `serviceAccountName` is not specified in a CR, the operator creates a service account with the same name as the CR (e.g. `my-app`). Users can also specify `serviceAccountName` when they want to create a service account manually. If applications require specific permissions but still want the operator to create a `ServiceAccount`, users can still manually create a role binding to bind a role to the service account created by the operator. To learn more about Role-based access control (RBAC), see Kubernetes link:++https://kubernetes.io/docs/reference/access-authn-authz/rbac/++[documentation]. === Labels By default, the operator adds the following labels into all resources created for a `RuntimeComponent` CR: .Default Labels |=== | Label | Default | Description | `app.kubernetes.io/instance` | `metadata.name` | A unique name or identifier for this component. This cannot be modified. | `app.kubernetes.io/name` | `metadata.name` | A name that represents this component. | `app.kubernetes.io/managed-by` | `runtime-component-operator` | The tool being used to manage this component. | `app.kubernetes.io/component` | `backend` | The type of component being created. See OpenShift link:++https://github.com/gorkem/app-labels/blob/master/labels-annotation-for-openshift.adoc#labels++[documentation] for full list. | `app.kubernetes.io/part-of` | `applicationName` | The name of the higher-level application this component is a part of. Configure this if the component is not a standalone application. | `app.kubernetes.io/version` | `version` | The version of the component. |=== You can set new labels in addition to the pre-existing ones or overwrite them, excluding the `app.kubernetes.io/instance` label. To set labels, specify them in your CR as key/value pairs. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app labels: my-label-key: my-label-value spec: applicationImage: quay.io/my-repo/my-app:1.0 ---- _After the initial deployment of `RuntimeComponent`, any changes to its labels would be applied only when one of the parameters from `spec` is updated._ ==== OpenShift Recommended Labels When running in OpenShift, there are additional labels and annotations that are standard on the platform. It is recommended that you overwrite our defaults where applicable and add any labels from the list that are not set by default using the above instructions. See link:++https://github.com/gorkem/app-labels/blob/master/labels-annotation-for-openshift.adoc#labels++[documentation] for a full list. === Annotations To add new annotations into all resources created for a `RuntimeComponent`, specify them in your CR as key/value pairs. Annotations specified in CR would override any annotations specified on a resource, except for the annotations set on `Service` using `service.annotations`. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app annotations: my-annotation-key: my-annotation-value spec: applicationImage: quay.io/my-repo/my-app:1.0 ---- _After the initial deployment of `RuntimeComponent`, any changes to its annotations would be applied only when one of the parameters from `spec` is updated._ ==== OpenShift Recommended Annotations When running in OpenShift, there are additional annotations that are standard on the platform. It is recommended that you overwrite our defaults where applicable and add any annotations from the list that are not set by default using the above instructions. See link:++https://github.com/gorkem/app-labels/blob/master/labels-annotation-for-openshift.adoc#labels++[documentation] for a full list. === Environment variables You can set environment variables for your application container. To set environment variables, specify `env` and/or `envFrom` fields in your CR. The environment variables can come directly from key/value pairs, `ConfigMap`s or `Secret`s. The environment variables set using the `env` or `envFrom` fields will override any environment variables specified in the container image. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 env: - name: DB_NAME value: ""database"" - name: DB_PORT valueFrom: configMapKeyRef: name: db-config key: db-port - name: DB_USERNAME valueFrom: secretKeyRef: name: db-credential key: adminUsername - name: DB_PASSWORD valueFrom: secretKeyRef: name: db-credential key: adminPassword envFrom: - configMapRef: name: env-configmap - secretRef: name: env-secrets ---- Use `envFrom` to define all data in a `ConfigMap` or a `Secret` as environment variables in a container. Keys from `ConfigMap` or `Secret` resources become environment variable name in your container. === High availability Run multiple instances of your application for high availability using one of the following mechanisms: - specify a static number of instances to run at all times using `replicas` parameter. __OR__ - configure auto-scaling to create (and delete) instances based on resource consumption using the `autoscaling` parameter. - Parameters `autoscaling.maxReplicas` and `resourceConstraints.requests.cpu` MUST be specified for auto-scaling. === Service ports Runtime Component Operator allows you to provide multiple service ports in addition to the primary service port. The primary port is exposed from the container running the application and it's values are used to configure the Route (or Ingress), Service binding and Knative service. The primary service port can be configured using `service.port`, `service.targetPort`, `service.portName`, and `service.nodePort` parameters. You can also specify an alternative port for Service Monitor using the `monitoring.endpoints` parameter and specifying either the `port` or `targetPort` field, otherwise it defaults to the primary port. The primary port is under the `service` field and the additional ports can be specified using the `ports` field as shown below. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 service: type: NodePort port: 9080 portName: http targetPort: 9080 nodePort: 30008 ports: - port: 9443 name: https monitoring: endpoints: - basicAuth: password: key: password name: metrics-secret username: key: username name: metrics-secret interval: 5s port: https scheme: HTTPS tlsConfig: insecureSkipVerify: true labels: app-monitoring: 'true' ---- === Persistence Runtime Component Operator is capable of creating a `StatefulSet` and `PersistentVolumeClaim` for each pod if storage is specified in the `RuntimeComponent` CR. Users also can provide mount points for their application. There are 2 ways to enable storage. ==== Basic storage With the `RuntimeComponent` CR definition below the operator will create `PersistentVolumeClaim` called `pvc` with the size of `1Gi` and `ReadWriteOnce` access mode. The operator will also create a volume mount for the `StatefulSet` mounting to `/data` folder. You can use `volumeMounts` field instead of `statefulSet.storage.mountPath` if you require to persist more then one folder. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 statefulSet: storage: size: 1Gi mountPath: ""/data"" ---- ==== Advanced storage Runtime Component Operator allows users to provide entire `volumeClaimTemplate` for full control over automatically created `PersistentVolumeClaim`. It is also possible to create multiple volume mount points for persistent volume using `volumeMounts` field as shown below. You can still use `statefulSet.storage.mountPath` if you require only a single mount point. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 volumeMounts: - name: pvc mountPath: /data_1 subPath: data_1 - name: pvc mountPath: /data_2 subPath: data_2 statefulSet: storage: volumeClaimTemplate: metadata: name: pvc spec: accessModes: - ""ReadWriteMany"" storageClassName: 'glusterfs' resources: requests: storage: 1Gi ---- === Service binding ==== Service Binding Operator The link:++https://github.com/redhat-developer/service-binding-operator++[Service Binding Operator] enables application developers to bind applications together with operator-managed backing services. This can be achieved by creating a `ServiceBindingRequest` custom resource. For the Runtime Component Operator to pass the binding information to the application, define your `ServiceBindingRequest` custom resource in one of the following two ways: . Define the `ServiceBindingRequest` custom resource YAML within the `bindings.embedded` parameter in your `RuntimeComponent` custom resource. . Create the `ServiceBindingRequest` custom resource manually and either refer to it explicitly in your `RuntimeComponent` custom resource or let the operator detect it automatically. The auto-detection mechanism works only if the `ServiceBindingRequest` custom resource follows the `-binding` naming convention. ===== Embedding the Service Binding resource Define your `ServiceBindingRequest` custom resource within your `RuntimeComponent` custom resource: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 bindings: embedded: apiVersion: apps.openshift.io/v1alpha1 kind: ServiceBindingRequest spec: backingServiceSelectors: - group: kafka.strimzi.io kind: Kafka resourceRef: my-cluster version: v1beta1 ---- After the Runtime Component Operator processes the `RuntimeComponent` custom resource, it creates a `ServiceBindingRequest` custom resource named `my-app-binding`. After the Service Binding Operator processes the `my-app` custom resource of the `ServiceBindingRequest` type, it creates a `Secret` object. The `Secret` resource contains binding information that the backing service provides. The Runtime Component Operator injects the `Secret` resource as an environment variable into application pods. The YAML definition specified in the `bindings.embedded` parameter must not include a `metadata` section because the Runtime Component operator adds a `metadata` section. If the YAML definition does not include an `apiVersion` field or a `kind` field, the Runtime Component operator uses the default `GroupVersionKind` value specified in the Operator Config Map. ===== Creating the Service Binding resource externally Create your `ServiceBindingRequest` custom resource in a separate YAML definition and then refer to the resource within your `RuntimeComponent` custom resource: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 bindings: resourceRef: my-binding ---- After the Service Binding Operator, as defined previously, processes the `my-binding` custom resource of the `ServiceBindingRequest` type, it creates a `Secret` object. The `Secret` resource contains binding information that the backing service provides. The Runtime Component Operator injects the `Secret` resource as an environment variable into application pods. The Runtime Component Operator can also _automatically detect_ if a `ServiceBindingRequest` custom resource exists in the application namespace and is named `-binding` (e.g. `my-app-binding`). If the operator detects the custom resource, it injects the binding secret into the application container. Users can turn off the auto-detection mechanism by setting the `bindings.autoDetect` parameter to a value of `false`. The `bindings.resourceRef` parameter takes precedence over the `bindings.autoDetect` parameter. In other words, the Runtime Component Operator, injects secrets from the `my-binding` resource, even if a `ServiceBindingRequest` resource named `my-app-binding` exists: [source,yaml] ---- bindings: autoDetect: true resourceRef: my-binding ---- _This feature is only available if you have Service Binding Operator installed on your cluster._ ==== Exposing `RuntimeComponent` applications as Provisioned Services A `RuntimeComponent` application can be configured to behave as a link:++https://github.com/k8s-service-bindings/spec#provisioned-service++[Provisioned Service] defined by the link:++https://github.com/k8s-service-bindings/spec++[Service Binding Specification]. According to the specification, a Provisioned Service resource must define a `.status.binding.name` which is a reference to a Secret. To expose your application as a Provisioned Service, set the `.spec.bindings.expose.enabled` parameter to a value of `true`. The Runtime Component Operator creates a *binding secret* named `-expose-binding` and adds the following entries to the secret: `host`, `port`, `protocol`, `basePath` and `uri`. To override the default values for the entries in the binding secret or to add new entries to the secret, create an *override secret* named `-expose-binding-override` and add any entries to the secret. The operator reads the content of the override secret and overrides the default values in the binding secret. Once a `RuntimeComponent` application is exposed as a Provisioned Service, a service binding request can refer to the application as a backing service. ==== Binding to `RuntimeComponent` applications Runtime Component Operator can be used to help with service binding in a cluster. The operator creates a secret on behalf of the **provider** `RuntimeComponent` and injects the secret into pods of the **consumer** `RuntimeComponent` as either environment variable or mounted files. See link:++https://docs.google.com/document/d/1riOX0iTnBBJpTKAHcQShYVMlgkaTNKb4m8fY7W1GqMA/edit++[Runtime Component Operator Design for Service Binding] for more information on the architecture. At this time, the only supported service binding type is `openapi`. The provider lists information about the REST API it provides: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-provider namespace: pro-namespace spec: applicationImage: quay.io/my-repo/my-provider:1.0 service: port: 3000 provides: category: openapi context: /my-context auth: password: name: my-secret key: password username: name: my-secret key: username --- kind: Secret apiVersion: v1 metadata: name: my-secret namespace: pro-namespace data: password: bW9vb29vb28= username: dGhlbGF1Z2hpbmdjb3c= type: Opaque ---- And the consumer lists the services it is intending to consume: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-consumer namespace: con-namespace spec: applicationImage: quay.io/my-repo/my-consumer:1.0 expose: true service: port: 9080 consumes: - category: openapi name: my-provider namespace: pro-namespace mountPath: /sample ---- In the above example, the operator creates a secret named `pro-namespace-my-provider` and adds the following key-value pairs: `username`, `password`, `url`, `context`, `protocol` and `hostname`. The `url` value format is `://..svc.cluster.local:/`. Since the provider and the consumer are in two different namespaces, the operator copies the provider secret into consumer's namespace. The operator then mounts the provider secret into a directory with the pattern `//` on application container within pods. In the above example, the secret will be serialized into `/sample/pro-namespace/my-provider`, which means we will have a file for each key, where the filename is the key and the content is the key's value. If the `namespace` is not provided in the above example under `consumes`, then the operator mounts the provider secret into a directory with pattern `/`. If consumer's CR does not include `mountPath`, the secret will be bound to environment variables with the pattern `__`, and the value of that env var is the key’s value. Due to syntax restrictions for Kubernetes environment variables, the string representing the namespace and the string representing the service name will have to be normalized by turning any non-`[azAZ09]` characters to become an underscore `(_)` character. NOTE: The operator requires `ClusterRole` permissions if the provider application is in another namespace. === Monitoring Runtime Component Operator can create a `ServiceMonitor` resource to integrate with `Prometheus Operator`. _This feature does not support integration with Knative Service. Prometheus Operator is required to use ServiceMonitor._ ==== Basic monitoring specification At minimum, a label needs to be provided that Prometheus expects to be set on `ServiceMonitor` objects. In this case, it is `apps-prometheus`. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 monitoring: labels: apps-prometheus: '' ---- ==== Advanced monitoring specification For advanced scenarios, it is possible to set many `ServicerMonitor` settings such as authentication secret using link:++https://github.com/coreos/prometheus-operator/blob/master/Documentation/api.md#endpoint++[Prometheus Endpoint] [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 monitoring: labels: app-prometheus: '' endpoints: - interval: '30s' basicAuth: username: key: username name: metrics-secret password: key: password name: metrics-secret tlsConfig: insecureSkipVerify: true ---- === Knative support Runtime Component Operator can deploy serverless applications with link:++https://knative.dev/docs/++[Knative] on a Kubernetes cluster. To achieve this, the operator creates a link:++https://github.com/knative/serving/blob/master/docs/spec/spec.md#service++[Knative `Service`] resource which manages the whole life cycle of a workload. To create Knative service, set `createKnativeService` to `true`: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 createKnativeService: true ---- By setting this parameter, the operator creates a Knative service in the cluster and populates the resource with applicable `RuntimeComponent` fields. Also, it ensures non-Knative resources including Kubernetes `Service`, `Route`, `Deployment` and etc. are deleted. The CRD fields which are used to populate the Knative service resource include `applicationImage`, `serviceAccountName`, `livenessProbe`, `readinessProbe`, `service.Port`, `volumes`, `volumeMounts`, `env`, `envFrom`, `pullSecret` and `pullPolicy`. `startupProbe` is not fully supported by Knative and it will not apply when Knative service is enabled. For more details on how to configure Knative for tasks such as enabling HTTPS connections and setting up a custom domain, checkout link:++https://knative.dev/docs/serving/++[Knative Documentation]. _Autoscaling related fields in `RuntimeComponent` are not used to configure Knative Pod Autoscaler (KPA). To learn more about how to configure KPA, see link:++https://knative.dev/docs/serving/configuring-the-autoscaler/++[Configuring the Autoscaler]._ _This feature is only available if you have Knative installed on your cluster._ === Exposing service externally ==== Non-Knative deployment (Route) To expose your application externally, set `expose` to `true`: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true ---- By setting this parameter, the operator creates an unsecured route based on your application service. Setting this parameter is the same as running `oc expose service `. To create a secured HTTPS route, see the link:++#certificate-manager-integration++[Certificate Manager Integration] section for more information. _This feature is only available if you are running on OKD or OpenShift._ ==== Non-Knative deployment (Ingress) Before you can use the Ingress resource to expose your cluster, you must install an ingress controller, such a Nginx or Traefik. _The Ingress resource is created only if the `Route` resource is not available._ To use the Ingress resource, set the `defaultHostName` variable in the _runtime-component-operator_ ConfigMap object to a host name such as _mycompany.com_ ===== Simple Ingress that uses `defaultHostName` and no `TLS`: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: backend spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true ---- With default hostname of _mycompany.com_, the application is available at the http://my-app-backend.mycompany.com URL. ===== Enable TLS and generate a certificate by using the cert-manager controller: _Note: You must install the cert-manager controller to automatically generate a custom certificate for the ingress controller._ [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: backend spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: certificate: {} ---- ===== Advanced Ingress configuration: Most of the Ingress configuraiton is achieved through annotations. Annotations such as Nginx, HAProxy, Traefik, and others are specific to the ingress controller implementation. You can provide an existing TLS secret and set a custom hostname. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: backend spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: annotations: # You can use this annotation to specify the name of the ingress controller to use. # You can install multiple ingress controllers to address different types of incoming traffic such as an external or internal DNS. kubernetes.io/ingress.class: ""nginx"" # The following nginx annotation enables a secure pod connection: nginx.ingress.kubernetes.io/ssl-redirect: true nginx.ingress.kubernetes.io/backend-protocol: ""HTTPS"" # The following traefik annotation enables a secure pod connection: traefik.ingress.kubernetes.io/service.serversscheme: https # Use a custom hostname for the Ingress host: app-v1.mycompany.com # Reference a pre-existing TLS secret: certificateSecretRef: mycompany-tls ---- ==== Knative deployment To expose your application as a Knative service externally, set `expose` to `true`: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app spec: applicationImage: quay.io/my-repo/my-app:1.0 createKnativeService: true expose: true ---- When `expose` is **not** set to `true`, the Knative service is labeled with `serving.knative.dev/visibility=cluster-local` which makes the Knative route to only be available on the cluster-local network (and not on the public Internet). However, if `expose` is set `true`, the Knative route would be accessible externally. To configure secure HTTPS connections for your Knative deployment, see link:++https://knative.dev/docs/serving/using-a-tls-cert/++[Configuring HTTPS with TLS certificates] for more information. === Kubernetes Application Navigator (kAppNav) support By default, Runtime Component Operator configures the Kubernetes resources it generates to allow automatic creation of an link:++https://github.com/kubernetes-sigs/application++[Application definition] with the `applicationName` parameter as the `Application` CR name. The automatic creation is done by the link:++https://kappnav.io/++[Kubernetes Application Navigator (kAppNav)]. You can easily view and manage the deployed resources that comprise your application by using kAppNav. You can disable auto-creation by setting the `createAppDefinition` parameter to a value of `false`. To join an existing application definition in the `RuntimeComponent` CR namespace, ensure that the `applicationName` parameter is set to the name of the `Application` CR that you want to join. To join an existing application definition in another namespace, ensure that the `createAppDefinition` parameter is set to `false` and that the `applicationName` parameter is set to the name of the existing `Application` CR that you want to join. First, the operator searches in the `RuntimeComponent` CR namespace to find an `Application` CR named as the `applicationName` parameter. If it fails to find any, it searches the whole cluster to find `Application` CRs that meet the following criteria: - The `Application` CRs have the same name as the value of the `applicationName` parameter. - The `RuntimeComponent` CR namespace is listed in the value of the `kappnav.component.namespaces` annotation. After the operator finds any `Application` CRs in the previous steps, it adds labels to the `RuntimeComponent` CR. These labels are listed in the `spec.selector.matchLabels` parameter. However, if the operator fails to find any `Application` CRs, and if the `createAppDefinition` parameter is not set to `false`, the operator configures the Kubernetes resources it generates. These Kubernetes resources are configured to allow automatic creation of an `Application` definition. _This feature is only available if you have kAppNav installed on your cluster. Auto creation of an application definition is not supported when Knative service is created_ NOTE: The operator requires `ClusterRole` permissions when joining an existing `Application` custom resource in another namespace. === Certificate Manager Integration Runtime Component Operator is enabled to take advantage of link:++https://cert-manager.io/++[cert-manager] tool, if it is installed on the cluster. This allows to automatically provision TLS certificates for pods as well as routes. Cert-manager installation instruction can be found link:++https://cert-manager.io/docs/installation/++[here]. When creating certificates via the RuntimeComponent CR the user can specify a particular issuer name and toggle the scopes between `ClusterIssuer` (cluster scoped) and `Issuer` (namespace scoped). If not specified, these values are retrieved from a ConfigMap called `runtime-component-operator`, with keys `defaultIssuer` (default value of `self-signed`) and `useClusterIssuer` (default value of `""true""`). _This feature does not support integration with Knative Service._ ==== Create an ClusterIssuer or Issuer Self signed: [source,yaml] ---- apiVersion: cert-manager.io/v1alpha2 kind: ClusterIssuer metadata: name: self-signed spec: selfSigned: {} ---- Using custom CA key: [source,yaml] ---- apiVersion: cert-manager.io/v1alpha2 kind: ClusterIssuer metadata: name: mycompany-ca spec: ca: secretName: mycompany-ca-tls ---- ==== Simple scenario (Pods certificate) [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 .... service: port: 9080 certificate: {} ---- In this scenario the operator generates a `Certificate` resource with a common name of `my-app.test.svc` that can be used for service to service communication. After this certificate request is resolved by the certificate manager, the resulting `my-app-svc-tls` secret is mounted onto each pod inside the `/etc/x509/certs` folder. Mounted files are always up to date with a secret. It will contain private key, certificate and CA certificate. It is up to the application container to consume these artifacts, applying any needed transformation or modification. ==== Simple scenario (Route certificate) [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: host: myapp.mycompany.com termination: reencrypt certificate: {} ---- In this scenario the operator generates a `Certificate` resource with the common name of `myapp.mycompany.com` that will be injected into the `Route` resource. ==== Advanced scenario In this example we are overriding Issuer to be used for application. Certificate will be generated for specific organization and duration. Extra properties can be added as well. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: host: myapp.mycompany.com termination: reencrypt certificate: duration: 8760h0m0s organization: - My Company issuerRef: name: myComanyIssuer kind: ClusterIssuer ---- ==== Use existing certificates It is possible to bring your own certificates to be used in a pod and the route. In this case the cert-manager is not required. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 expose: true route: host: myapp.mycompany.com termination: reencrypt certificateSecretRef: my-app-rt-tls service: port: 9443 ---- Example of the manually provided route secret [source, yaml] ---- kind: Secret apiVersion: v1 metadata: name: my-app-rt-tls data: ca.crt: >- Certificate Authority public certificate...(base64) tls.crt: >- Route public certificate...(base64) tls.key: >- Route private key...(base64) destCA.crt: >- Pod/Service certificate Certificate Authority (base64). Might be required when using reencrypt termination policy. type: kubernetes.io/tls ---- === Affinity Using affinity you can constrain a Pod to only be able to run on particular Node(s), or to prefer to run on particular nodes. ==== Node Affinity ===== Basic node affinity Use `nodeAffinityLabels` field to set required labels for pod scheduling on specific nodes: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 affinity: nodeAffinityLabels: customNodeLabel: label1, label2 customNodeLabel2: label3 ---- ===== Advanced node affinity example: The following example requires a node type of _Large_ and preferences for two zones, which are named _zoneA_ and _zoneB_ [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: my-app namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: node.kubernetes.io/instance-type operator: In values: - large preferredDuringSchedulingIgnoredDuringExecution: - weight: 60 preference: matchExpressions: - key: failure-domain.beta.kubernetes.io/zone operator: In values: - zoneA - weight: 20 preference: matchExpressions: - key: failure-domain.beta.kubernetes.io/zone operator: In values: - zoneB ---- ==== Pod Affinity and Anti-Affinity Pod affinity and anti-affinity allow you to constrain which nodes your pod is eligible to be scheduled based on labels on pods that are already running on the node rather than based on labels on node. The following example shows that pod affinity is required and that the pods for _Service-A_ and _Service-B_ must be in the same zone. Through pod anti-affinity, it is preferred not to schedule _Service_B_ and _Service_C_ on the same host. [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeComponent metadata: name: Service-B namespace: test spec: applicationImage: quay.io/my-repo/my-app:1.0 affinity: podAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: service operator: In values: - Service-A topologyKey: failure-domain.beta.kubernetes.io/zone podAntiAffinity: preferredDuringSchedulingIgnoredDuringExecution: - weight: 100 podAffinityTerm: labelSelector: matchExpressions: - key: service operator: In values: - Service-C topologyKey: kubernetes.io/hostname ---- See link:++https://github.com/application-stacks/runtime-component-operator/blob/master/examples/affinity/README.adocd++[Affinity Example] for more details === Day-2 Operations You can easily perform day-2 operations using the `RuntimeOperation` custom resource (CR), which allows you to specify the commands to run on a container within a Pod. .Configurable Parameters |=== | Parameter | Description | `podName` | The name of the Pod, which must be in the same namespace as the `RuntimeOperation` CR. | `containerName` | The name of the container within the Pod. The default value is the name of the main container, which is `app`. | `command` | Command to run. The command doesn't run in a shell. |=== Example: [source,yaml] ---- apiVersion: app.stacks/v1beta1 kind: RuntimeOperation metadata: name: example-runtime-operation spec: # Specify the name of the pod. The pod must be in the same namespace as this RuntimeOperation CR. podName: Specify_Pod_Name_Here # Specify the name of the container. The default value is the name of the main container, which is `app`. containerName: app # Run the following command. The command does not run in a shell. command: - /bin/sh - '-c' - echo ""Hello"" > /tmp/runtime-operation.log ---- You can check the status of a runtime operation by using the `status` field inside the CR YAML file. You can also run the `oc get runtimeop -o wide` command to see the status of all operations in the current namespace. The operator will retry to run the `RuntimeOperation` when it fails to start due to specified pod or container not being found or when the pod is not in running state. The retry interval will be doubled with each failed attempt. NOTE: The `RuntimeOperation` CR must be created in the same namespace as the Pod to operate on. After the `RuntimeOperation` CR starts, the CR cannot be reused for more operations. A new CR needs to be created for each day-2 operation. The operator can process only one `RuntimeOperation` instance at a time. Long running commands can cause other runtime operations to wait before they start. === Troubleshooting See the link:++troubleshooting.adoc++[troubleshooting guide] for information on how to investigate and resolve deployment problems. ",12150,False,2228.052659320536,median "//// DO NOT EDIT THIS FILE. IT WAS GENERATED. Manual changes to this file will be lost when it is generated again. Edit the files in the src/main/asciidoc/ directory instead. //// = Spring Cloud Kubernetes :doctype: book :idprefix: :idseparator: - :toc: left :toclevels: 4 :tabsize: 4 :numbered: :sectanchors: :sectnums: :icons: font :hide-uri-scheme: :docinfo: shared,private :sc-ext: java :project-full-name: Spring Cloud Kubernetes :all: {asterisk}{asterisk} This reference guide covers how to use Spring Cloud Kubernetes. == Why do you need Spring Cloud Kubernetes? Spring Cloud Kubernetes provides implementations of well known Spring Cloud interfaces allowing developers to build and run Spring Cloud applications on Kubernetes. While this project may be useful to you when building a cloud native application, it is also not a requirement in order to deploy a Spring Boot app on Kubernetes. If you are just getting started in your journey to running your Spring Boot app on Kubernetes you can accomplish a lot with nothing more than a basic Spring Boot app and Kubernetes itself. To learn more, you can get started by reading the https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#cloud-deployment-kubernetes[Spring Boot reference documentation for deploying to Kubernetes ] and also working through the workshop material https://hackmd.io/@ryanjbaxter/spring-on-k8s-workshop[Spring and Kubernetes]. == Starters Starters are convenient dependency descriptors you can include in your application. Include a starter to get the dependencies and Spring Boot auto-configuration for a feature set. [cols=""a,d""] |=== | Starter | Features | [source,xml] ---- org.springframework.cloud spring-cloud-starter-kubernetes ---- | <> implementation that resolves service names to Kubernetes Services. | [source,xml] ---- org.springframework.cloud spring-cloud-starter-kubernetes-config ---- | Load application properties from Kubernetes <> and <>. <> application properties when a ConfigMap or Secret changes. | [source,xml] ---- org.springframework.cloud spring-cloud-starter-kubernetes-all ---- | All Spring Cloud Kubernetes features. |=== == DiscoveryClient for Kubernetes This project provides an implementation of https://github.com/spring-cloud/spring-cloud-commons/blob/master/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/DiscoveryClient.java[Discovery Client] for https://kubernetes.io[Kubernetes]. This client lets you query Kubernetes endpoints (see https://kubernetes.io/docs/user-guide/services/[services]) by name. A service is typically exposed by the Kubernetes API server as a collection of endpoints that represent `http` and `https` addresses and that a client can access from a Spring Boot application running as a pod. This is something that you get for free by adding the following dependency inside your project: ==== [source,xml] ---- org.springframework.cloud spring-cloud-starter-kubernetes ---- ==== To enable loading of the `DiscoveryClient`, add `@EnableDiscoveryClient` to the according configuration or application class, as the following example shows: ==== [source,java] ---- @SpringBootApplication @EnableDiscoveryClient public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ---- ==== Then you can inject the client in your code simply by autowiring it, as the following example shows: ==== [source,java] ---- @Autowired private DiscoveryClient discoveryClient; ---- ==== You can choose to enable `DiscoveryClient` from all namespaces by setting the following property in `application.properties`: ==== [source] ---- spring.cloud.kubernetes.discovery.all-namespaces=true ---- ==== If, for any reason, you need to disable the `DiscoveryClient`, you can set the following property in `application.properties`: ==== [source] ---- spring.cloud.kubernetes.discovery.enabled=false ---- ==== Some Spring Cloud components use the `DiscoveryClient` in order to obtain information about the local service instance. For this to work, you need to align the Kubernetes service name with the `spring.application.name` property. NOTE: `spring.application.name` has no effect as far as the name registered for the application within Kubernetes Spring Cloud Kubernetes can also watch the Kubernetes service catalog for changes and update the `DiscoveryClient` implementation accordingly. In order to enable this functionality you need to add `@EnableScheduling` on a configuration class in your application. == Kubernetes native service discovery Kubernetes itself is capable of (server side) service discovery (see: https://kubernetes.io/docs/concepts/services-networking/service/#discovering-services). Using native kubernetes service discovery ensures compatibility with additional tooling, such as Istio (https://istio.io), a service mesh that is capable of load balancing, circuit breaker, failover, and much more. The caller service then need only refer to names resolvable in a particular Kubernetes cluster. A simple implementation might use a spring `RestTemplate` that refers to a fully qualified domain name (FQDN), such as `https://{service-name}.{namespace}.svc.{cluster}.local:{service-port}`. Additionally, you can use Hystrix for: * Circuit breaker implementation on the caller side, by annotating the spring boot application class with `@EnableCircuitBreaker` * Fallback functionality, by annotating the respective method with `@HystrixCommand(fallbackMethod=` == Kubernetes PropertySource implementations The most common approach to configuring your Spring Boot application is to create an `application.properties` or `application.yaml` or an `application-profile.properties` or `application-profile.yaml` file that contains key-value pairs that provide customization values to your application or Spring Boot starters. You can override these properties by specifying system properties or environment variables. [[configmap-propertysource]] === Using a `ConfigMap` `PropertySource` Kubernetes provides a resource named https://kubernetes.io/docs/user-guide/configmap/[`ConfigMap`] to externalize the parameters to pass to your application in the form of key-value pairs or embedded `application.properties` or `application.yaml` files. The link:./spring-cloud-kubernetes-config[Spring Cloud Kubernetes Config] project makes Kubernetes `ConfigMap` instances available during application bootstrapping and triggers hot reloading of beans or Spring context when changes are detected on observed `ConfigMap` instances. The default behavior is to create a `ConfigMapPropertySource` based on a Kubernetes `ConfigMap` that has a `metadata.name` value of either the name of your Spring application (as defined by its `spring.application.name` property) or a custom name defined within the `bootstrap.properties` file under the following key: `spring.cloud.kubernetes.config.name`. However, more advanced configuration is possible where you can use multiple `ConfigMap` instances. The `spring.cloud.kubernetes.config.sources` list makes this possible. For example, you could define the following `ConfigMap` instances: ==== [source,yaml] ---- spring: application: name: cloud-k8s-app cloud: kubernetes: config: name: default-name namespace: default-namespace sources: # Spring Cloud Kubernetes looks up a ConfigMap named c1 in namespace default-namespace - name: c1 # Spring Cloud Kubernetes looks up a ConfigMap named default-name in whatever namespace n2 - namespace: n2 # Spring Cloud Kubernetes looks up a ConfigMap named c3 in namespace n3 - namespace: n3 name: c3 ---- ==== In the preceding example, if `spring.cloud.kubernetes.config.namespace` had not been set, the `ConfigMap` named `c1` would be looked up in the namespace that the application runs. Any matching `ConfigMap` that is found is processed as follows: * Apply individual configuration properties. * Apply as `yaml` the content of any property named `application.yaml`. * Apply as a properties file the content of any property named `application.properties`. The single exception to the aforementioned flow is when the `ConfigMap` contains a *single* key that indicates the file is a YAML or properties file. In that case, the name of the key does NOT have to be `application.yaml` or `application.properties` (it can be anything) and the value of the property is treated correctly. This features facilitates the use case where the `ConfigMap` was created by using something like the following: ==== [source] ---- kubectl create configmap game-config --from-file=/path/to/app-config.yaml ---- ==== Assume that we have a Spring Boot application named `demo` that uses the following properties to read its thread pool configuration. * `pool.size.core` * `pool.size.maximum` This can be externalized to config map in `yaml` format as follows: ==== [source,yaml] ---- kind: ConfigMap apiVersion: v1 metadata: name: demo data: pool.size.core: 1 pool.size.max: 16 ---- ==== Individual properties work fine for most cases. However, sometimes, embedded `yaml` is more convenient. In this case, we use a single property named `application.yaml` to embed our `yaml`, as follows: ==== [source,yaml] ---- kind: ConfigMap apiVersion: v1 metadata: name: demo data: application.yaml: |- pool: size: core: 1 max:16 ---- ==== The following example also works: ==== [source,yaml] ---- kind: ConfigMap apiVersion: v1 metadata: name: demo data: custom-name.yaml: |- pool: size: core: 1 max:16 ---- ==== You can also configure Spring Boot applications differently depending on active profiles that are merged together when the `ConfigMap` is read. You can provide different property values for different profiles by using an `application.properties` or `application.yaml` property, specifying profile-specific values, each in their own document (indicated by the `---` sequence), as follows: ==== [source,yaml] ---- kind: ConfigMap apiVersion: v1 metadata: name: demo data: application.yml: |- greeting: message: Say Hello to the World farewell: message: Say Goodbye --- spring: profiles: development greeting: message: Say Hello to the Developers farewell: message: Say Goodbye to the Developers --- spring: profiles: production greeting: message: Say Hello to the Ops ---- ==== In the preceding case, the configuration loaded into your Spring Application with the `development` profile is as follows: ==== [source,yaml] ---- greeting: message: Say Hello to the Developers farewell: message: Say Goodbye to the Developers ---- ==== However, if the `production` profile is active, the configuration becomes: ==== [source,yaml] ---- greeting: message: Say Hello to the Ops farewell: message: Say Goodbye ---- ==== If both profiles are active, the property that appears last within the `ConfigMap` overwrites any preceding values. Another option is to create a different config map per profile and spring boot will automatically fetch it based on active profiles ==== [source,yaml] ---- kind: ConfigMap apiVersion: v1 metadata: name: demo data: application.yml: |- greeting: message: Say Hello to the World farewell: message: Say Goodbye ---- ==== ==== [source,yaml] ---- kind: ConfigMap apiVersion: v1 metadata: name: demo-development data: application.yml: |- spring: profiles: development greeting: message: Say Hello to the Developers farewell: message: Say Goodbye to the Developers ---- ==== ==== [source,yaml] ---- kind: ConfigMap apiVersion: v1 metadata: name: demo-production data: application.yml: |- spring: profiles: production greeting: message: Say Hello to the Ops farewell: message: Say Goodbye ---- ==== To tell Spring Boot which `profile` should be enabled at bootstrap, you can pass `SPRING_PROFILES_ACTIVE` environment variable. To do so, you can launch your Spring Boot application with an environment variable that you can define it in the PodSpec at the container specification. Deployment resource file, as follows: ==== [source,yaml] ---- apiVersion: apps/v1 kind: Deployment metadata: name: deployment-name labels: app: deployment-name spec: replicas: 1 selector: matchLabels: app: deployment-name template: metadata: labels: app: deployment-name spec: containers: - name: container-name image: your-image env: - name: SPRING_PROFILES_ACTIVE value: ""development"" ---- ==== NOTE: You should check the security configuration section. To access config maps from inside a pod you need to have the correct Kubernetes service accounts, roles and role bindings. Another option for using `ConfigMap` instances is to mount them into the Pod by running the Spring Cloud Kubernetes application and having Spring Cloud Kubernetes read them from the file system. This behavior is controlled by the `spring.cloud.kubernetes.config.paths` property. You can use it in addition to or instead of the mechanism described earlier. You can specify multiple (exact) file paths in `spring.cloud.kubernetes.config.paths` by using the `,` delimiter. NOTE: You have to provide the full exact path to each property file, because directories are not being recursively parsed. NOTE: If you use `spring.cloud.kubernetes.config.paths` or `spring.cloud.kubernetes.secrets.path` the automatic reload functionality will not work. You will need to make a `POST` request to the `/actuator/refresh` endpoint or restart/redeploy the application. .Properties: [options=""header,footer""] |=== | Name | Type | Default | Description | `spring.cloud.kubernetes.config.enabled` | `Boolean` | `true` | Enable ConfigMaps `PropertySource` | `spring.cloud.kubernetes.config.name` | `String` | `${spring.application.name}` | Sets the name of `ConfigMap` to look up | `spring.cloud.kubernetes.config.namespace` | `String` | Client namespace | Sets the Kubernetes namespace where to lookup | `spring.cloud.kubernetes.config.paths` | `List` | `null` | Sets the paths where `ConfigMap` instances are mounted | `spring.cloud.kubernetes.config.enableApi` | `Boolean` | `true` | Enable or disable consuming `ConfigMap` instances through APIs |=== === Secrets PropertySource Kubernetes has the notion of https://kubernetes.io/docs/concepts/configuration/secret/[Secrets] for storing sensitive data such as passwords, OAuth tokens, and so on. This project provides integration with `Secrets` to make secrets accessible by Spring Boot applications. You can explicitly enable or disable This feature by setting the `spring.cloud.kubernetes.secrets.enabled` property. When enabled, the `SecretsPropertySource` looks up Kubernetes for `Secrets` from the following sources: . Reading recursively from secrets mounts . Named after the application (as defined by `spring.application.name`) . Matching some labels *Note:* By default, consuming Secrets through the API (points 2 and 3 above) *is not enabled* for security reasons. The permission 'list' on secrets allows clients to inspect secrets values in the specified namespace. Further, we recommend that containers share secrets through mounted volumes. If you enable consuming Secrets through the API, we recommend that you limit access to Secrets by using an authorization policy, such as RBAC. For more information about risks and best practices when consuming Secrets through the API refer to https://kubernetes.io/docs/concepts/configuration/secret/#best-practices[this doc]. If the secrets are found, their data is made available to the application. Assume that we have a spring boot application named `demo` that uses properties to read its database configuration. We can create a Kubernetes secret by using the following command: ==== [source] ---- kubectl create secret generic db-secret --from-literal=username=user --from-literal=password=p455w0rd ---- ==== The preceding command would create the following secret (which you can see by using `kubectl get secrets db-secret -o yaml`): ==== [source,yaml] ---- apiVersion: v1 data: password: cDQ1NXcwcmQ= username: dXNlcg== kind: Secret metadata: creationTimestamp: 2017-07-04T09:15:57Z name: db-secret namespace: default resourceVersion: ""357496"" selfLink: /api/v1/namespaces/default/secrets/db-secret uid: 63c89263-6099-11e7-b3da-76d6186905a8 type: Opaque ---- ==== Note that the data contains Base64-encoded versions of the literal provided by the `create` command. Your application can then use this secret -- for example, by exporting the secret's value as environment variables: ==== [source,yaml] ---- apiVersion: v1 kind: Deployment metadata: name: ${project.artifactId} spec: template: spec: containers: - env: - name: DB_USERNAME valueFrom: secretKeyRef: name: db-secret key: username - name: DB_PASSWORD valueFrom: secretKeyRef: name: db-secret key: password ---- ==== You can select the Secrets to consume in a number of ways: . By listing the directories where secrets are mapped: + ==== [source,bash] ---- -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets/db-secret,etc/secrets/postgresql ---- ==== + If you have all the secrets mapped to a common root, you can set them like: + ==== [source,bash] ---- -Dspring.cloud.kubernetes.secrets.paths=/etc/secrets ---- ==== . By setting a named secret: + ==== [source,bash] ---- -Dspring.cloud.kubernetes.secrets.name=db-secret ---- ==== . By defining a list of labels: + ==== [source,bash] ---- -Dspring.cloud.kubernetes.secrets.labels.broker=activemq -Dspring.cloud.kubernetes.secrets.labels.db=postgresql ---- ==== As the case with `ConfigMap`, more advanced configuration is also possible where you can use multiple `Secret` instances. The `spring.cloud.kubernetes.secrets.sources` list makes this possible. For example, you could define the following `Secret` instances: ==== [source,yaml] ---- spring: application: name: cloud-k8s-app cloud: kubernetes: secrets: name: default-name namespace: default-namespace sources: # Spring Cloud Kubernetes looks up a Secret named s1 in namespace default-namespace - name: s1 # Spring Cloud Kubernetes looks up a Secret named default-name in whatever namespace n2 - namespace: n2 # Spring Cloud Kubernetes looks up a Secret named s3 in namespace n3 - namespace: n3 name: s3 ---- ==== In the preceding example, if `spring.cloud.kubernetes.secrets.namespace` had not been set, the `Secret` named `s1` would be looked up in the namespace that the application runs. .Properties: [options=""header,footer""] |=== | Name | Type | Default | Description | `spring.cloud.kubernetes.secrets.enabled` | `Boolean` | `true` | Enable Secrets `PropertySource` | `spring.cloud.kubernetes.secrets.name` | `String` | `${spring.application.name}` | Sets the name of the secret to look up | `spring.cloud.kubernetes.secrets.namespace` | `String` | Client namespace | Sets the Kubernetes namespace where to look up | `spring.cloud.kubernetes.secrets.labels` | `Map` | `null` | Sets the labels used to lookup secrets | `spring.cloud.kubernetes.secrets.paths` | `List` | `null` | Sets the paths where secrets are mounted (example 1) | `spring.cloud.kubernetes.secrets.enableApi` | `Boolean` | `false` | Enables or disables consuming secrets through APIs (examples 2 and 3) |=== Notes: * The `spring.cloud.kubernetes.secrets.labels` property behaves as defined by https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding#map-based-binding[Map-based binding]. * The `spring.cloud.kubernetes.secrets.paths` property behaves as defined by https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding#collection-based-binding[Collection-based binding]. * Access to secrets through the API may be restricted for security reasons. The preferred way is to mount secrets to the Pod. You can find an example of an application that uses secrets (though it has not been updated to use the new `spring-cloud-kubernetes` project) at https://github.com/fabric8-quickstarts/spring-boot-camel-config[spring-boot-camel-config] === `PropertySource` Reload WARNING: This functionality has been deprecated in the 2020.0 release. Please see the <> controller for an alternative way to achieve the same functionality. Some applications may need to detect changes on external property sources and update their internal status to reflect the new configuration. The reload feature of Spring Cloud Kubernetes is able to trigger an application reload when a related `ConfigMap` or `Secret` changes. By default, this feature is disabled. You can enable it by using the `spring.cloud.kubernetes.reload.enabled=true` configuration property (for example, in the `application.properties` file). The following levels of reload are supported (by setting the `spring.cloud.kubernetes.reload.strategy` property): * `refresh` (default): Only configuration beans annotated with `@ConfigurationProperties` or `@RefreshScope` are reloaded. This reload level leverages the refresh feature of Spring Cloud Context. * `restart_context`: the whole Spring `ApplicationContext` is gracefully restarted. Beans are recreated with the new configuration. In order for the restart context functionality to work properly you must enable and expose the restart actuator endpoint [source,yaml] ==== ---- management: endpoint: restart: enabled: true endpoints: web: exposure: include: restart ---- ==== * `shutdown`: the Spring `ApplicationContext` is shut down to activate a restart of the container. When you use this level, make sure that the lifecycle of all non-daemon threads is bound to the `ApplicationContext` and that a replication controller or replica set is configured to restart the pod. Assuming that the reload feature is enabled with default settings (`refresh` mode), the following bean is refreshed when the config map changes: ==== [java, source] ---- @Configuration @ConfigurationProperties(prefix = ""bean"") public class MyConfig { private String message = ""a message that can be changed live""; // getter and setters } ---- ==== To see that changes effectively happen, you can create another bean that prints the message periodically, as follows ==== [source,java] ---- @Component public class MyBean { @Autowired private MyConfig config; @Scheduled(fixedDelay = 5000) public void hello() { System.out.println(""The message is: "" + config.getMessage()); } } ---- ==== You can change the message printed by the application by using a `ConfigMap`, as follows: ==== [source,yaml] ---- apiVersion: v1 kind: ConfigMap metadata: name: reload-example data: application.properties: |- bean.message=Hello World! ---- ==== Any change to the property named `bean.message` in the `ConfigMap` associated with the pod is reflected in the output. More generally speaking, changes associated to properties prefixed with the value defined by the `prefix` field of the `@ConfigurationProperties` annotation are detected and reflected in the application. <> is explained earlier in this chapter. The full example is available in https://github.com/fabric8io/spring-cloud-kubernetes/tree/master/spring-cloud-kubernetes-examples/kubernetes-reload-example[`spring-cloud-kubernetes-reload-example`]. The reload feature supports two operating modes: * Event (default): Watches for changes in config maps or secrets by using the Kubernetes API (web socket). Any event produces a re-check on the configuration and, in case of changes, a reload. The `view` role on the service account is required in order to listen for config map changes. A higher level role (such as `edit`) is required for secrets (by default, secrets are not monitored). * Polling: Periodically re-creates the configuration from config maps and secrets to see if it has changed. You can configure the polling period by using the `spring.cloud.kubernetes.reload.period` property and defaults to 15 seconds. It requires the same role as the monitored property source. This means, for example, that using polling on file-mounted secret sources does not require particular privileges. .Properties: [options=""header,footer""] |=== | Name | Type | Default | Description | `spring.cloud.kubernetes.reload.enabled` | `Boolean` | `false` | Enables monitoring of property sources and configuration reload | `spring.cloud.kubernetes.reload.monitoring-config-maps` | `Boolean` | `true` | Allow monitoring changes in config maps | `spring.cloud.kubernetes.reload.monitoring-secrets` | `Boolean` | `false` | Allow monitoring changes in secrets | `spring.cloud.kubernetes.reload.strategy` | `Enum` | `refresh` | The strategy to use when firing a reload (`refresh`, `restart_context`, or `shutdown`) | `spring.cloud.kubernetes.reload.mode` | `Enum` | `event` | Specifies how to listen for changes in property sources (`event` or `polling`) | `spring.cloud.kubernetes.reload.period` | `Duration`| `15s` | The period for verifying changes when using the `polling` strategy |=== Notes: * You should not use properties under `spring.cloud.kubernetes.reload` in config maps or secrets. Changing such properties at runtime may lead to unexpected results. * Deleting a property or the whole config map does not restore the original state of the beans when you use the `refresh` level. == Kubernetes Ecosystem Awareness All of the features described earlier in this guide work equally well, regardless of whether your application is running inside Kubernetes. This is really helpful for development and troubleshooting. From a development point of view, this lets you start your Spring Boot application and debug one of the modules that is part of this project. You need not deploy it in Kubernetes, as the code of the project relies on the https://github.com/fabric8io/kubernetes-client[Fabric8 Kubernetes Java client], which is a fluent DSL that can communicate by using `http` protocol to the REST API of the Kubernetes Server. To disable the integration with Kubernetes you can set `spring.cloud.kubernetes.enabled` to `false`. Please be aware that when `spring-cloud-kubernetes-config` is on the classpath, `spring.cloud.kubernetes.enabled` should be set in `bootstrap.{properties|yml}` (or the profile specific one) otherwise it should be in `application.{properties|yml}` (or the profile specific one). Also note that these properties: `spring.cloud.kubernetes.config.enabled` and `spring.cloud.kubernetes.secrets.enabled` only take effect when set in `bootstrap.{properties|yml}` === Kubernetes Profile Autoconfiguration When the application runs as a pod inside Kubernetes, a Spring profile named `kubernetes` automatically gets activated. This lets you customize the configuration, to define beans that are applied when the Spring Boot application is deployed within the Kubernetes platform (for example, different development and production configuration). === Istio Awareness When you include the `spring-cloud-kubernetes-istio` module in the application classpath, a new profile is added to the application, provided the application is running inside a Kubernetes Cluster with https://istio.io[Istio] installed. You can then use spring `@Profile(""istio"")` annotations in your Beans and `@Configuration` classes. The Istio awareness module uses `me.snowdrop:istio-client` to interact with Istio APIs, letting us discover traffic rules, circuit breakers, and so on, making it easy for our Spring Boot applications to consume this data to dynamically configure themselves according to the environment. == Pod Health Indicator Spring Boot uses https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthEndpoint.java[`HealthIndicator`] to expose info about the health of an application. That makes it really useful for exposing health-related information to the user and makes it a good fit for use as https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/[readiness probes]. The Kubernetes health indicator (which is part of the core module) exposes the following info: * Pod name, IP address, namespace, service account, node name, and its IP address * A flag that indicates whether the Spring Boot application is internal or external to Kubernetes == Leader Election == LoadBalancer for Kubernetes This project includes Spring Cloud Load Balancer for load balancing based on Kubernetes Endpoints and provides implementation of load balancer based on Kubernetes Service. To include it to your project add the following dependency. ==== [source,xml] ---- org.springframework.cloud spring-cloud-starter-kubernetes-loadbalancer ---- ==== To enable load balancing based on Kubernetes Service name use the following property. Then load balancer would try to call application using address, for example `service-a.default.svc.cluster.local` ==== [source] ---- spring.cloud.kubernetes.loadbalancer.mode=SERVICE ---- ==== To enabled load balancing across all namespaces use the following property. Property from `spring-cloud-kubernetes-discovery` module is respected. ==== [source] ---- spring.cloud.kubernetes.discovery.all-namespaces=true ---- ==== == Security Configurations Inside Kubernetes === Namespace Most of the components provided in this project need to know the namespace. For Kubernetes (1.3+), the namespace is made available to the pod as part of the service account secret and is automatically detected by the client. For earlier versions, it needs to be specified as an environment variable to the pod. A quick way to do this is as follows: ==== [source] ---- env: - name: ""KUBERNETES_NAMESPACE"" valueFrom: fieldRef: fieldPath: ""metadata.namespace"" ---- ==== === Service Account For distributions of Kubernetes that support more fine-grained role-based access within the cluster, you need to make sure a pod that runs with `spring-cloud-kubernetes` has access to the Kubernetes API. For any service accounts you assign to a deployment or pod, you need to make sure they have the correct roles. Depending on the requirements, you'll need `get`, `list` and `watch` permission on the following resources: .Kubernetes Resource Permissions |=== |Dependency | Resources |spring-cloud-starter-kubernetes |pods, services, endpoints |spring-cloud-starter-kubernetes-config |configmaps, secrets |=== For development purposes, you can add `cluster-reader` permissions to your `default` service account. On a production system you'll likely want to provide more granular permissions. The following Role and RoleBinding are an example for namespaced permissions for the `default` account: ==== [source,yaml] ---- kind: Role apiVersion: rbac.authorization.k8s.io/v1 metadata: namespace: YOUR-NAME-SPACE name: namespace-reader rules: - apiGroups: ["""", ""extensions"", ""apps""] resources: [""configmaps"", ""pods"", ""services"", ""endpoints"", ""secrets""] verbs: [""get"", ""list"", ""watch""] --- kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: namespace-reader-binding namespace: YOUR-NAME-SPACE subjects: - kind: ServiceAccount name: default apiGroup: """" roleRef: kind: Role name: namespace-reader apiGroup: """" ---- ==== == Service Registry Implementation In Kubernetes service registration is controlled by the platform, the application itself does not control registration as it may do in other platforms. For this reason using `spring.cloud.service-registry.auto-registration.enabled` or setting `@EnableDiscoveryClient(autoRegister=false)` will have no effect in Spring Cloud Kubernetes. [#spring-cloud-kubernetes-configuration-watcher] ## Spring Cloud Kubernetes Configuration Watcher Kubernetes provides the ability to https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#add-configmap-data-to-a-volume[mount a ConfigMap or Secret as a volume] in the container of your application. When the contents of the ConfigMap or Secret changes, the https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#mounted-configmaps-are-updated-automatically[mounted volume will be updated with those changes]. However, Spring Boot will not automatically update those changes unless you restart the application. Spring Cloud provides the ability refresh the application context without restarting the application by either hitting the actuator endpoint `/refresh` or via publishing a `RefreshRemoteApplicationEvent` using Spring Cloud Bus. To achieve this configuration refresh of a Spring Cloud app running on Kubernetes, you can deploy the Spring Cloud Kubernetes Configuration Watcher controller into your Kubernetes cluster. The application is published as a container and is available on https://hub.docker.com/repository/docker/springcloud/spring-cloud-kubernetes-configuration-watcher[Docker Hub]. Spring Cloud Kubernetes Configuration Watcher can send refresh notifications to applications in two ways. 1. Over HTTP in which case the application being notified must of the `/refresh` actuator endpoint exposed and accessible from within the cluster 2. Using Spring Cloud Bus, in which case you will need a message broker deployed to your custer for the application to use. ### Deployment YAML Below is a sample deployment YAML you can use to deploy the Kubernetes Configuration Watcher to Kubernetes. ==== [source,yaml] ---- --- apiVersion: v1 kind: List items: - apiVersion: v1 kind: Service metadata: labels: app: spring-cloud-kubernetes-configuration-watcher name: spring-cloud-kubernetes-configuration-watcher spec: ports: - name: http port: 8888 targetPort: 8888 selector: app: spring-cloud-kubernetes-configuration-watcher type: ClusterIP - apiVersion: v1 kind: ServiceAccount metadata: labels: app: spring-cloud-kubernetes-configuration-watcher name: spring-cloud-kubernetes-configuration-watcher - apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: labels: app: spring-cloud-kubernetes-configuration-watcher name: spring-cloud-kubernetes-configuration-watcher:view roleRef: kind: Role apiGroup: rbac.authorization.k8s.io name: namespace-reader subjects: - kind: ServiceAccount name: spring-cloud-kubernetes-configuration-watcher - apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: default name: namespace-reader rules: - apiGroups: ["""", ""extensions"", ""apps""] resources: [""configmaps"", ""pods"", ""services"", ""endpoints"", ""secrets""] verbs: [""get"", ""list"", ""watch""] - apiVersion: apps/v1 kind: Deployment metadata: name: spring-cloud-kubernetes-configuration-watcher-deployment spec: selector: matchLabels: app: spring-cloud-kubernetes-configuration-watcher template: metadata: labels: app: spring-cloud-kubernetes-configuration-watcher spec: serviceAccount: spring-cloud-kubernetes-configuration-watcher containers: - name: spring-cloud-kubernetes-configuration-watcher image: springcloud/spring-cloud-kubernetes-configuration-watcher:2.0.0-SNAPSHOT imagePullPolicy: IfNotPresent readinessProbe: httpGet: port: 8888 path: /actuator/health/readiness livenessProbe: httpGet: port: 8888 path: /actuator/health/liveness ports: - containerPort: 8888 ---- ==== The Service Account and associated Role Binding is important for Spring Cloud Kubernetes Configuration to work properly. The controller needs access to read data about ConfigMaps, Pods, Services, Endpoints and Secrets in the Kubernetes cluster. ### Monitoring ConfigMaps and Secrets Spring Cloud Kubernetes Configuration Watcher will react to changes in ConfigMaps with a label of `spring.cloud.kubernetes.config` with the value `true` or any Secret with a label of `spring.cloud.kubernetes.secret` with the value `true`. If the ConfigMap or Secret does not have either of those labels or the values of those labels is not `true` then any changes will be ignored. The labels Spring Cloud Kubernetes Configuration Watcher looks for on ConfigMaps and Secrets can be changed by setting `spring.cloud.kubernetes.configuration.watcher.configLabel` and `spring.cloud.kubernetes.configuration.watcher.secretLabel` respectively. If a change is made to a ConfigMap or Secret with valid labels then Spring Cloud Kubernetes Configuration Watcher will take the name of the ConfigMap or Secret and send a notification to the application with that name. ### HTTP Implementation The HTTP implementation is what is used by default. When this implementation is used Spring Cloud Kubernetes Configuration Watcher and a change to a ConfigMap or Secret occurs then the HTTP implementation will use the Spring Cloud Kubernetes Discovery Client to fetch all instances of the application which match the name of the ConfigMap or Secret and send an HTTP POST request to the application's actuator `/refresh` endpoint. By default it will send the post request to `/actuator/refresh` using the port registered in the discovery client. #### Non-Default Management Port and Actuator Path If the application is using a non-default actuator path and/or using a different port for the management endpoints, the Kubernetes service for the application can add an annotation called `boot.spring.io/actuator` and set its value to the path and port used by the application. For example ==== [source,yaml] ---- apiVersion: v1 kind: Service metadata: labels: app: config-map-demo name: config-map-demo annotations: boot.spring.io/actuator: http://:9090/myactuator/home spec: ports: - name: http port: 8080 targetPort: 8080 selector: app: config-map-demo ---- ==== Another way you can choose to configure the actuator path and/or management port is by setting `spring.cloud.kubernetes.configuration.watcher.actuatorPath` and `spring.cloud.kubernetes.configuration.watcher.actuatorPort`. ### Messaging Implementation The messaging implementation can be enabled by setting the profile `bus` when the Spring Cloud Kubernetes Configuration Watcher application is deployed to Kubernetes. WARNING: Currently the only supported message broker is RabbitMQ ### Configuring RabbitMQ When the `bus` profile is enabled you will need to configure Spring RabbitMQ to point it to the location of the RabbitMQ instance you would like to use as well as any credentials necessary to authenticate. This can be done by setting the standard Spring RabbitMQ properties, for example ==== [source,yaml] ---- spring: rabbitmq: username: user password: password host: rabbitmq ---- ==== == Examples Spring Cloud Kubernetes tries to make it transparent for your applications to consume Kubernetes Native Services by following the Spring Cloud interfaces. In your applications, you need to add the `spring-cloud-kubernetes-discovery` dependency to your classpath and remove any other dependency that contains a `DiscoveryClient` implementation (that is, a Eureka discovery client). The same applies for `PropertySourceLocator`, where you need to add to the classpath the `spring-cloud-kubernetes-config` and remove any other dependency that contains a `PropertySourceLocator` implementation (that is, a configuration server client). The following projects highlight the usage of these dependencies and demonstrate how you can use these libraries from any Spring Boot application: * https://github.com/spring-cloud/spring-cloud-kubernetes/tree/master/spring-cloud-kubernetes-examples[Spring Cloud Kubernetes Examples]: the ones located inside this repository. * Spring Cloud Kubernetes Full Example: Minions and Boss ** https://github.com/salaboy/spring-cloud-k8s-minion[Minion] ** https://github.com/salaboy/spring-cloud-k8s-boss[Boss] * Spring Cloud Kubernetes Full Example: https://github.com/salaboy/s1p_docs[SpringOne Platform Tickets Service] * https://github.com/salaboy/s1p_gateway[Spring Cloud Gateway with Spring Cloud Kubernetes Discovery and Config] * https://github.com/salaboy/showcase-admin-tool[Spring Boot Admin with Spring Cloud Kubernetes Discovery and Config] == Other Resources This section lists other resources, such as presentations (slides) and videos about Spring Cloud Kubernetes. * https://salaboy.com/2018/09/27/the-s1p-experience/[S1P Spring Cloud on PKS] * https://salaboy.com/2018/07/18/ljc-july-18-spring-cloud-docker-k8s/[Spring Cloud, Docker, Kubernetes -> London Java Community July 2018] Please feel free to submit other resources through pull requests to https://github.com/spring-cloud/spring-cloud-kubernetes[this repository]. == Configuration properties To see the list of all Sleuth related configuration properties please check link:appendix.html[the Appendix page]. == Building :jdkversion: 1.7 === Basic Compile and Test To build the source you will need to install JDK {jdkversion}. Spring Cloud uses Maven for most build-related activities, and you should be able to get off the ground quite quickly by cloning the project you are interested in and typing ---- $ ./mvnw install ---- NOTE: You can also install Maven (>=3.3.3) yourself and run the `mvn` command in place of `./mvnw` in the examples below. If you do that you also might need to add `-P spring` if your local Maven settings do not contain repository declarations for spring pre-release artifacts. NOTE: Be aware that you might need to increase the amount of memory available to Maven by setting a `MAVEN_OPTS` environment variable with a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in the `.mvn` configuration, so if you find you have to do it to make a build succeed, please raise a ticket to get the settings added to source control. For hints on how to build the project look in `.travis.yml` if there is one. There should be a ""script"" and maybe ""install"" command. Also look at the ""services"" section to see if any services need to be running locally (e.g. mongo or rabbit). Ignore the git-related bits that you might find in ""before_install"" since they're related to setting git credentials and you already have those. The projects that require middleware generally include a `docker-compose.yml`, so consider using https://docs.docker.com/compose/[Docker Compose] to run the middeware servers in Docker containers. See the README in the https://github.com/spring-cloud-samples/scripts[scripts demo repository] for specific instructions about the common cases of mongo, rabbit and redis. NOTE: If all else fails, build with the command from `.travis.yml` (usually `./mvnw install`). === Documentation The spring-cloud-build module has a ""docs"" profile, and if you switch that on it will try to build asciidoc sources from `src/main/asciidoc`. As part of that process it will look for a `README.adoc` and process it by loading all the includes, but not parsing or rendering it, just copying it to `${main.basedir}` (defaults to `${basedir}`, i.e. the root of the project). If there are any changes in the README it will then show up after a Maven build as a modified file in the correct place. Just commit it and push the change. === Working with the code If you don't have an IDE preference we would recommend that you use https://www.springsource.com/developer/sts[Spring Tools Suite] or https://eclipse.org[Eclipse] when working with the code. We use the https://eclipse.org/m2e/[m2eclipse] eclipse plugin for maven support. Other IDEs and tools should also work without issue as long as they use Maven 3.3.3 or better. ==== Activate the Spring Maven profile Spring Cloud projects require the 'spring' Maven profile to be activated to resolve the spring milestone and snapshot repositories. Use your preferred IDE to set this profile to be active, or you may experience build errors. ==== Importing into eclipse with m2eclipse We recommend the https://eclipse.org/m2e/[m2eclipse] eclipse plugin when working with eclipse. If you don't already have m2eclipse installed it is available from the ""eclipse marketplace"". NOTE: Older versions of m2e do not support Maven 3.3, so once the projects are imported into Eclipse you will also need to tell m2eclipse to use the right profile for the projects. If you see many different errors related to the POMs in the projects, check that you have an up to date installation. If you can't upgrade m2e, add the ""spring"" profile to your `settings.xml`. Alternatively you can copy the repository settings from the ""spring"" profile of the parent pom into your `settings.xml`. ==== Importing into eclipse without m2eclipse If you prefer not to use m2eclipse you can generate eclipse project metadata using the following command: [indent=0] ---- $ ./mvnw eclipse:eclipse ---- The generated eclipse projects can be imported by selecting `import existing projects` from the `file` menu. == Contributing :spring-cloud-build-branch: master Spring Cloud is released under the non-restrictive Apache 2.0 license, and follows a very standard Github development process, using Github tracker for issues and merging pull requests into master. If you want to contribute even something trivial please do not hesitate, but follow the guidelines below. === Sign the Contributor License Agreement Before we accept a non-trivial patch or pull request we will need you to sign the https://cla.pivotal.io/sign/spring[Contributor License Agreement]. Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests. === Code of Conduct This project adheres to the Contributor Covenant https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc[code of conduct]. By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io. === Code Conventions and Housekeeping None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge. * Use the Spring Framework code format conventions. If you use Eclipse you can import formatter settings using the `eclipse-code-formatter.xml` file from the https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-dependencies-parent/eclipse-code-formatter.xml[Spring Cloud Build] project. If using IntelliJ, you can use the https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter Plugin] to import the same file. * Make sure all new `.java` files to have a simple Javadoc class comment with at least an `@author` tag identifying you, and preferably at least a paragraph on what the class is for. * Add the ASF license header comment to all new `.java` files (copy from existing files in the project) * Add yourself as an `@author` to the .java files that you modify substantially (more than cosmetic changes). * Add some Javadocs and, if you change the namespace, some XSD doc elements. * A few unit tests would help a lot as well -- someone has to do it. * If no-one else is using your branch, please rebase it against the current master (or other target branch in the main project). * When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit message (where XXXX is the issue number). === Checkstyle Spring Cloud Build comes with a set of checkstyle rules. You can find them in the `spring-cloud-build-tools` module. The most notable files under the module are: .spring-cloud-build-tools/ ---- └── src    ├── checkstyle    │   └── checkstyle-suppressions.xml <3>    └── main    └── resources    ├── checkstyle-header.txt <2>    └── checkstyle.xml <1> ---- <1> Default Checkstyle rules <2> File header setup <3> Default suppression rules ==== Checkstyle configuration Checkstyle rules are *disabled by default*. To add checkstyle to your project just define the following properties and plugins. .pom.xml ---- true <1> true <2> true <3> <4> io.spring.javaformat spring-javaformat-maven-plugin <5> org.apache.maven.plugins maven-checkstyle-plugin <5> org.apache.maven.plugins maven-checkstyle-plugin ---- <1> Fails the build upon Checkstyle errors <2> Fails the build upon Checkstyle violations <3> Checkstyle analyzes also the test sources <4> Add the Spring Java Format plugin that will reformat your code to pass most of the Checkstyle formatting rules <5> Add checkstyle plugin to your build and reporting phases If you need to suppress some rules (e.g. line length needs to be longer), then it's enough for you to define a file under `${project.root}/src/checkstyle/checkstyle-suppressions.xml` with your suppressions. Example: .projectRoot/src/checkstyle/checkstyle-suppresions.xml ---- ---- It's advisable to copy the `${spring-cloud-build.rootFolder}/.editorconfig` and `${spring-cloud-build.rootFolder}/.springformat` to your project. That way, some default formatting rules will be applied. You can do so by running this script: ```bash $ curl https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/.editorconfig -o .editorconfig $ touch .springformat ``` === IDE setup ==== Intellij IDEA In order to setup Intellij you should import our coding conventions, inspection profiles and set up the checkstyle plugin. The following files can be found in the https://github.com/spring-cloud/spring-cloud-build/tree/master/spring-cloud-build-tools[Spring Cloud Build] project. .spring-cloud-build-tools/ ---- └── src    ├── checkstyle    │   └── checkstyle-suppressions.xml <3>    └── main    └── resources    ├── checkstyle-header.txt <2>    ├── checkstyle.xml <1>    └── intellij       ├── Intellij_Project_Defaults.xml <4>       └── Intellij_Spring_Boot_Java_Conventions.xml <5> ---- <1> Default Checkstyle rules <2> File header setup <3> Default suppression rules <4> Project defaults for Intellij that apply most of Checkstyle rules <5> Project style conventions for Intellij that apply most of Checkstyle rules .Code style image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-code-style.png[Code style] Go to `File` -> `Settings` -> `Editor` -> `Code style`. There click on the icon next to the `Scheme` section. There, click on the `Import Scheme` value and pick the `Intellij IDEA code style XML` option. Import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Spring_Boot_Java_Conventions.xml` file. .Inspection profiles image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-inspections.png[Code style] Go to `File` -> `Settings` -> `Editor` -> `Inspections`. There click on the icon next to the `Profile` section. There, click on the `Import Profile` and import the `spring-cloud-build-tools/src/main/resources/intellij/Intellij_Project_Defaults.xml` file. .Checkstyle To have Intellij work with Checkstyle, you have to install the `Checkstyle` plugin. It's advisable to also install the `Assertions2Assertj` to automatically convert the JUnit assertions image::https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/{spring-cloud-build-branch}/docs/src/main/asciidoc/images/intellij-checkstyle.png[Checkstyle] Go to `File` -> `Settings` -> `Other settings` -> `Checkstyle`. There click on the `+` icon in the `Configuration file` section. There, you'll have to define where the checkstyle rules should be picked from. In the image above, we've picked the rules from the cloned Spring Cloud Build repository. However, you can point to the Spring Cloud Build's GitHub repository (e.g. for the `checkstyle.xml` : `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle.xml`). We need to provide the following variables: - `checkstyle.header.file` - please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/main/resources/checkstyle-header.txt` URL. - `checkstyle.suppressions.file` - default suppressions. Please point it to the Spring Cloud Build's, `spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` file either in your cloned repo or via the `https://raw.githubusercontent.com/spring-cloud/spring-cloud-build/master/spring-cloud-build-tools/src/checkstyle/checkstyle-suppressions.xml` URL. - `checkstyle.additional.suppressions.file` - this variable corresponds to suppressions in your local project. E.g. you're working on `spring-cloud-contract`. Then point to the `project-root/src/checkstyle/checkstyle-suppressions.xml` folder. Example for `spring-cloud-contract` would be: `/home/username/spring-cloud-contract/src/checkstyle/checkstyle-suppressions.xml`. IMPORTANT: Remember to set the `Scan Scope` to `All sources` since we apply checkstyle rules for production and test sources. ",12523,False,1874.5791467215213,median "#include ""Validation/RecoEgamma/plugins/EgammaObjects.h"" #include ""FWCore/Utilities/interface/Exception.h"" #include ""FWCore/MessageLogger/interface/MessageLogger.h"" #include ""DataFormats/Common/interface/Handle.h"" #include ""DataFormats/EgammaReco/interface/BasicCluster.h"" #include ""DataFormats/EgammaReco/interface/SuperCluster.h"" #include ""DataFormats/EgammaReco/interface/ClusterShape.h"" #include ""DataFormats/EgammaCandidates/interface/Photon.h"" #include ""DataFormats/EgammaCandidates/interface/PhotonFwd.h"" #include ""DataFormats/EgammaCandidates/interface/GsfElectron.h"" #include ""DataFormats/EgammaCandidates/interface/GsfElectronFwd.h"" #include ""SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"" #include ""TF1.h"" EgammaObjects::EgammaObjects( const edm::ParameterSet& ps ) { particleID = ps.getParameter(""particleID""); EtCut = ps.getParameter(""EtCut""); if( particleID == 22 ) particleString = ""Photon""; else if( particleID == 11 ) particleString = ""Electron""; else throw(std::runtime_error(""\\n\\nEgammaObjects: Only 11 = Photon and 22 = Electron are acceptable parictleIDs! Exiting...\\n\\n"")); loadCMSSWObjects(ps); loadHistoParameters(ps); rootFile_ = TFile::Open(ps.getParameter(""outputFile"").c_str(),""RECREATE""); hist_EtaEfficiency_ = 0 ; hist_EtaNumRecoOverNumTrue_ = 0 ; hist_deltaEtaVsEt_ = 0 ; hist_deltaEtaVsE_ = 0 ; hist_deltaEtaVsEta_ = 0 ; hist_deltaEtaVsPhi_ = 0 ; hist_resolutionEtaVsEt_ = 0 ; hist_resolutionEtaVsE_ = 0 ; hist_resolutionEtaVsEta_ = 0 ; hist_resolutionEtaVsPhi_ = 0 ; hist_Phi_ = 0 ; hist_PhiOverTruth_ = 0 ; hist_PhiEfficiency_ = 0 ; hist_PhiNumRecoOverNumTrue_ = 0 ; hist_deltaPhiVsEt_ = 0 ; hist_deltaPhiVsE_ = 0 ; hist_deltaPhiVsEta_ = 0 ; hist_deltaPhiVsPhi_ = 0 ; hist_resolutionPhiVsEt_ = 0 ; hist_resolutionPhiVsE_ = 0 ; hist_resolutionPhiVsEta_ = 0 ; hist_resolutionPhiVsPhi_ = 0 ; hist_All_recoMass_ = 0 ; hist_BarrelOnly_recoMass_ = 0 ; hist_EndcapOnly_recoMass_ = 0 ; hist_Mixed_recoMass_ = 0 ; hist_recoMass_withBackgroud_NoEtCut_ = 0 ; hist_recoMass_withBackgroud_5EtCut_ = 0 ; hist_recoMass_withBackgroud_10EtCut_ = 0 ; hist_recoMass_withBackgroud_20EtCut_ = 0 ; _TEMP_scatterPlot_EtOverTruthVsEt_ = 0 ; _TEMP_scatterPlot_EtOverTruthVsE_ = 0 ; _TEMP_scatterPlot_EtOverTruthVsEta_ = 0 ; _TEMP_scatterPlot_EtOverTruthVsPhi_ = 0 ; _TEMP_scatterPlot_EOverTruthVsEt_ = 0 ; _TEMP_scatterPlot_EOverTruthVsE_ = 0 ; _TEMP_scatterPlot_EOverTruthVsEta_ = 0 ; _TEMP_scatterPlot_EOverTruthVsPhi_ = 0 ; _TEMP_scatterPlot_deltaEtaVsEt_ = 0 ; _TEMP_scatterPlot_deltaEtaVsE_ = 0 ; _TEMP_scatterPlot_deltaEtaVsEta_ = 0 ; _TEMP_scatterPlot_deltaEtaVsPhi_ = 0 ; _TEMP_scatterPlot_deltaPhiVsEt_ = 0 ; _TEMP_scatterPlot_deltaPhiVsE_ = 0 ; _TEMP_scatterPlot_deltaPhiVsEta_ = 0 ; _TEMP_scatterPlot_deltaPhiVsPhi_ = 0 ; } void EgammaObjects::loadCMSSWObjects(const edm::ParameterSet& ps) { MCTruthCollectionT_ = consumes( ps.getParameter(""MCTruthCollection"")); RecoCollectionT_ = consumes( ps.getParameter(""RecoCollection"")); } void EgammaObjects::loadHistoParameters(const edm::ParameterSet& ps) { hist_min_Et_ = ps.getParameter(""hist_min_Et""); hist_max_Et_ = ps.getParameter(""hist_max_Et""); hist_bins_Et_ = ps.getParameter (""hist_bins_Et""); hist_min_E_ = ps.getParameter(""hist_min_E""); hist_max_E_ = ps.getParameter(""hist_max_E""); hist_bins_E_ = ps.getParameter (""hist_bins_E""); hist_min_Eta_ = ps.getParameter(""hist_min_Eta""); hist_max_Eta_ = ps.getParameter(""hist_max_Eta""); hist_bins_Eta_ = ps.getParameter (""hist_bins_Eta""); hist_min_Phi_ = ps.getParameter(""hist_min_Phi""); hist_max_Phi_ = ps.getParameter(""hist_max_Phi""); hist_bins_Phi_ = ps.getParameter (""hist_bins_Phi""); hist_min_EtOverTruth_ = ps.getParameter(""hist_min_EtOverTruth""); hist_max_EtOverTruth_ = ps.getParameter(""hist_max_EtOverTruth""); hist_bins_EtOverTruth_ = ps.getParameter (""hist_bins_EtOverTruth""); hist_min_EOverTruth_ = ps.getParameter(""hist_min_EOverTruth""); hist_max_EOverTruth_ = ps.getParameter(""hist_max_EOverTruth""); hist_bins_EOverTruth_ = ps.getParameter (""hist_bins_EOverTruth""); hist_min_EtaOverTruth_ = ps.getParameter(""hist_min_EtaOverTruth""); hist_max_EtaOverTruth_ = ps.getParameter(""hist_max_EtaOverTruth""); hist_bins_EtaOverTruth_ = ps.getParameter (""hist_bins_EtaOverTruth""); hist_min_PhiOverTruth_ = ps.getParameter(""hist_min_PhiOverTruth""); hist_max_PhiOverTruth_ = ps.getParameter(""hist_max_PhiOverTruth""); hist_bins_PhiOverTruth_ = ps.getParameter (""hist_bins_PhiOverTruth""); hist_min_deltaEta_ = ps.getParameter(""hist_min_deltaEta""); hist_max_deltaEta_ = ps.getParameter(""hist_max_deltaEta""); hist_bins_deltaEta_ = ps.getParameter (""hist_bins_deltaEta""); hist_min_deltaPhi_ = ps.getParameter(""hist_min_deltaPhi""); hist_max_deltaPhi_ = ps.getParameter(""hist_max_deltaPhi""); hist_bins_deltaPhi_ = ps.getParameter (""hist_bins_deltaPhi""); hist_min_recoMass_ = ps.getParameter(""hist_min_recoMass""); hist_max_recoMass_ = ps.getParameter(""hist_max_recoMass""); hist_bins_recoMass_ = ps.getParameter (""hist_bins_recoMass""); } EgammaObjects::~EgammaObjects() { delete rootFile_; } void EgammaObjects::beginJob() { TH1::SetDefaultSumw2(true); createBookedHistoObjects(); createTempHistoObjects(); } void EgammaObjects::createBookedHistoObjects() { hist_Et_ = new TH1D(""hist_Et_"",(""Et Distribution of ""+particleString).c_str(), hist_bins_Et_,hist_min_Et_,hist_max_Et_); hist_EtOverTruth_ = new TH1D(""hist_EtOverTruth_"",(""Reco Et over True Et of ""+particleString).c_str(), hist_bins_EtOverTruth_,hist_min_EtOverTruth_,hist_max_EtOverTruth_); hist_EtEfficiency_ = new TH1D(""hist_EtEfficiency_"",(""# of True ""+particleString+"" Reconstructed over # of True ""+particleString+"" VS Et of ""+particleString).c_str(), hist_bins_Et_,hist_min_Et_,hist_max_Et_); hist_EtNumRecoOverNumTrue_ = new TH1D(""hist_EtNumRecoOverNumTrue_"",(""# of Reco ""+particleString+"" over # of True ""+particleString+"" VS Et of ""+particleString).c_str(), hist_bins_Et_,hist_min_Et_,hist_max_Et_); hist_E_ = new TH1D(""hist_E_"",(""E Distribution of ""+particleString).c_str(), hist_bins_E_,hist_min_E_,hist_max_E_); hist_EOverTruth_ = new TH1D(""hist_EOverTruth_"",(""Reco E over True E of ""+particleString).c_str(), hist_bins_EOverTruth_,hist_min_EOverTruth_,hist_max_EOverTruth_); hist_EEfficiency_ = new TH1D(""hist_EEfficiency_"",(""# of True ""+particleString+"" Reconstructed over # of True ""+particleString+"" VS E of ""+particleString).c_str(), hist_bins_E_,hist_min_E_,hist_max_E_); hist_ENumRecoOverNumTrue_ = new TH1D(""hist_ENumRecoOverNumTrue_"",(""# of Reco ""+particleString+"" over # of True ""+particleString+"" VS E of ""+particleString).c_str(), hist_bins_E_,hist_min_E_,hist_max_E_); hist_Eta_ = new TH1D(""hist_Eta_"",(""Eta Distribution of ""+particleString).c_str(), hist_bins_Eta_,hist_min_Eta_,hist_max_Eta_); hist_EtaOverTruth_ = new TH1D(""hist_EtaOverTruth_"",(""Reco Eta over True Eta of ""+particleString).c_str(), hist_bins_EtaOverTruth_,hist_min_EtaOverTruth_,hist_max_EtaOverTruth_); hist_EtaEfficiency_ = new TH1D(""hist_EtaEfficiency_"",(""# of True ""+particleString+"" Reconstructed over # of True ""+particleString+"" VS Eta of ""+particleString).c_str(), hist_bins_Eta_,hist_min_Eta_,hist_max_Eta_); hist_EtaNumRecoOverNumTrue_ = new TH1D(""hist_EtaNumRecoOverNumTrue_"",(""# of Reco ""+particleString+"" over # of True ""+particleString+"" VS Eta of ""+particleString).c_str(), hist_bins_Eta_,hist_min_Eta_,hist_max_Eta_); hist_Phi_ = new TH1D(""hist_Phi_"",(""Phi Distribution of ""+particleString).c_str(), hist_bins_Phi_,hist_min_Phi_,hist_max_Phi_); hist_PhiOverTruth_ = new TH1D(""hist_PhiOverTruth_"",(""Reco Phi over True Phi of ""+particleString).c_str(), hist_bins_PhiOverTruth_,hist_min_PhiOverTruth_,hist_max_PhiOverTruth_); hist_PhiEfficiency_ = new TH1D(""hist_PhiEfficiency_"",(""# of True ""+particleString+"" Reconstructed over # of True ""+particleString+"" VS Phi of ""+particleString).c_str(), hist_bins_Phi_,hist_min_Phi_,hist_max_Phi_); hist_PhiNumRecoOverNumTrue_ = new TH1D(""hist_PhiNumRecoOverNumTrue_"",(""# of Reco ""+particleString+"" over # of True ""+particleString+"" VS Phi of ""+particleString).c_str(), hist_bins_Phi_,hist_min_Phi_,hist_max_Phi_); std::string recoParticleName; if( particleID == 22 ) recoParticleName = ""Higgs""; else if( particleID == 11 ) recoParticleName = ""Z""; hist_All_recoMass_ = new TH1D(""hist_All_recoMass_"",(recoParticleName+"" Mass from ""+particleString+"" in All Regions"").c_str(), hist_bins_recoMass_,hist_min_recoMass_,hist_max_recoMass_); hist_BarrelOnly_recoMass_ = new TH1D(""hist_BarrelOnly_recoMass_"",(recoParticleName+"" Mass from ""+particleString+"" in Barrel"").c_str(), hist_bins_recoMass_,hist_min_recoMass_,hist_max_recoMass_); hist_EndcapOnly_recoMass_ = new TH1D(""hist_EndcapOnly_recoMass_"",(recoParticleName+"" Mass from ""+particleString+"" in EndCap"").c_str(), hist_bins_recoMass_,hist_min_recoMass_,hist_max_recoMass_); hist_Mixed_recoMass_ = new TH1D(""hist_Mixed_recoMass_"",(recoParticleName+"" Mass from ""+particleString+"" in Split Detectors"").c_str(), hist_bins_recoMass_,hist_min_recoMass_,hist_max_recoMass_); hist_recoMass_withBackgroud_NoEtCut_ = new TH1D(""hist_recoMass_withBackgroud_NoEtCut_"",(recoParticleName+"" Mass from ""+particleString+"" with Background, No Et Cut"").c_str(), hist_bins_recoMass_,hist_min_recoMass_,hist_max_recoMass_); hist_recoMass_withBackgroud_5EtCut_ = new TH1D(""hist_recoMass_withBackgroud_5EtCut_"",(recoParticleName+"" Mass from ""+particleString+"" with Background, 5 Et Cut"").c_str(), hist_bins_recoMass_,hist_min_recoMass_,hist_max_recoMass_); hist_recoMass_withBackgroud_10EtCut_ = new TH1D(""hist_recoMass_withBackgroud_10EtCut_"",(recoParticleName+"" Mass from ""+particleString+"" with Background, 10 Et Cut"").c_str(), hist_bins_recoMass_,hist_min_recoMass_,hist_max_recoMass_); hist_recoMass_withBackgroud_20EtCut_ = new TH1D(""hist_recoMass_withBackgroud_20EtCut_"",(recoParticleName+"" Mass from ""+particleString+"" with Background, 20 Et Cut"").c_str(), hist_bins_recoMass_,hist_min_recoMass_,hist_max_recoMass_); } void EgammaObjects::createTempHistoObjects() { _TEMP_scatterPlot_EtOverTruthVsEt_ = new TH2D(""_TEMP_scatterPlot_EtOverTruthVsEt_"",""_TEMP_scatterPlot_EtOverTruthVsEt_"", hist_bins_Et_,hist_min_Et_,hist_max_Et_,hist_bins_EtOverTruth_,hist_min_EtOverTruth_,hist_max_EtOverTruth_); _TEMP_scatterPlot_EtOverTruthVsE_ = new TH2D(""_TEMP_scatterPlot_EtOverTruthVsE_"",""_TEMP_scatterPlot_EtOverTruthVsE_"", hist_bins_E_,hist_min_E_,hist_max_E_,hist_bins_EtOverTruth_,hist_min_EtOverTruth_,hist_max_EtOverTruth_); _TEMP_scatterPlot_EtOverTruthVsEta_ = new TH2D(""_TEMP_scatterPlot_EtOverTruthVsEta_"",""_TEMP_scatterPlot_EtOverTruthVsEta_"", hist_bins_Eta_,hist_min_Eta_,hist_max_Eta_,hist_bins_EtOverTruth_,hist_min_EtOverTruth_,hist_max_EtOverTruth_); _TEMP_scatterPlot_EtOverTruthVsPhi_ = new TH2D(""_TEMP_scatterPlot_EtOverTruthVsPhi_"",""_TEMP_scatterPlot_EtOverTruthVsPhi_"", hist_bins_Phi_,hist_min_Phi_,hist_max_Phi_,hist_bins_EtOverTruth_,hist_min_EtOverTruth_,hist_max_EtOverTruth_); _TEMP_scatterPlot_EOverTruthVsEt_ = new TH2D(""_TEMP_scatterPlot_EOverTruthVsEt_"",""_TEMP_scatterPlot_EOverTruthVsEt_"", hist_bins_Et_,hist_min_Et_,hist_max_Et_,hist_bins_EOverTruth_,hist_min_EOverTruth_,hist_max_EOverTruth_); _TEMP_scatterPlot_EOverTruthVsE_ = new TH2D(""_TEMP_scatterPlot_EOverTruthVsE_"",""_TEMP_scatterPlot_EOverTruthVsE_"", hist_bins_E_,hist_min_E_,hist_max_E_,hist_bins_EOverTruth_,hist_min_EOverTruth_,hist_max_EOverTruth_); _TEMP_scatterPlot_EOverTruthVsEta_ = new TH2D(""_TEMP_scatterPlot_EOverTruthVsEta_"",""_TEMP_scatterPlot_EOverTruthVsEta_"", hist_bins_Eta_,hist_min_Eta_,hist_max_Eta_,hist_bins_EOverTruth_,hist_min_EOverTruth_,hist_max_EOverTruth_); _TEMP_scatterPlot_EOverTruthVsPhi_ = new TH2D(""_TEMP_scatterPlot_EOverTruthVsPhi_"",""_TEMP_scatterPlot_EOverTruthVsPhi_"", hist_bins_Phi_,hist_min_Phi_,hist_max_Phi_,hist_bins_EOverTruth_,hist_min_EOverTruth_,hist_max_EOverTruth_); _TEMP_scatterPlot_deltaEtaVsEt_ = new TH2D(""_TEMP_scatterPlot_deltaEtaVsEt_"",""_TEMP_scatterPlot_deltaEtaVsEt_"", hist_bins_Et_,hist_min_Et_,hist_max_Et_,hist_bins_deltaEta_,hist_min_deltaEta_,hist_max_deltaEta_); _TEMP_scatterPlot_deltaEtaVsE_ = new TH2D(""_TEMP_scatterPlot_deltaEtaVsE_"",""_TEMP_scatterPlot_deltaEtaVsE_"", hist_bins_E_,hist_min_E_,hist_max_E_,hist_bins_deltaEta_,hist_min_deltaEta_,hist_max_deltaEta_); _TEMP_scatterPlot_deltaEtaVsEta_ = new TH2D(""_TEMP_scatterPlot_deltaEtaVsEta_"",""_TEMP_scatterPlot_deltaEtaVsEta_"", hist_bins_Eta_,hist_min_Eta_,hist_max_Eta_,hist_bins_deltaEta_,hist_min_deltaEta_,hist_max_deltaEta_); _TEMP_scatterPlot_deltaEtaVsPhi_ = new TH2D(""_TEMP_scatterPlot_deltaEtaVsPhi_"",""_TEMP_scatterPlot_deltaEtaVsPhi_"", hist_bins_Phi_,hist_min_Phi_,hist_max_Phi_,hist_bins_deltaEta_,hist_min_deltaEta_,hist_max_deltaEta_); _TEMP_scatterPlot_deltaPhiVsEt_ = new TH2D(""_TEMP_scatterPlot_deltaPhiVsEt_"",""_TEMP_scatterPlot_deltaPhiVsEt_"", hist_bins_Et_,hist_min_Et_,hist_max_Et_,hist_bins_deltaPhi_,hist_min_deltaPhi_,hist_max_deltaPhi_); _TEMP_scatterPlot_deltaPhiVsE_ = new TH2D(""_TEMP_scatterPlot_deltaPhiVsE_"",""_TEMP_scatterPlot_deltaPhiVsE_"", hist_bins_E_,hist_min_E_,hist_max_E_,hist_bins_deltaPhi_,hist_min_deltaPhi_,hist_max_deltaPhi_); _TEMP_scatterPlot_deltaPhiVsEta_ = new TH2D(""_TEMP_scatterPlot_deltaPhiVsEta_"",""_TEMP_scatterPlot_deltaPhiVsEta_"", hist_bins_Eta_,hist_min_Eta_,hist_max_Eta_,hist_bins_deltaPhi_,hist_min_deltaPhi_,hist_max_deltaPhi_); _TEMP_scatterPlot_deltaPhiVsPhi_ = new TH2D(""_TEMP_scatterPlot_deltaPhiVsPhi_"",""_TEMP_scatterPlot_deltaPhiVsPhi_"", hist_bins_Phi_,hist_min_Phi_,hist_max_Phi_,hist_bins_deltaPhi_,hist_min_deltaPhi_,hist_max_deltaPhi_); } void EgammaObjects::analyze( const edm::Event& evt, const edm::EventSetup& es ) { if( particleID == 22 ) analyzePhotons(evt, es); else if( particleID == 11 ) analyzeElectrons(evt, es); } void EgammaObjects::analyzePhotons( const edm::Event& evt, const edm::EventSetup& es ) { edm::Handle pPhotons; evt.getByToken(RecoCollectionT_, pPhotons); if (!pPhotons.isValid()) { Labels l; labelsForToken(RecoCollectionT_, l); edm::LogError(""EgammaObjects"") << ""Error! can't get collection with label "" << l.module; } const reco::PhotonCollection* photons = pPhotons.product(); std::vector photonsMCMatched; for(reco::PhotonCollection::const_iterator aClus = photons->begin(); aClus != photons->end(); aClus++) { if(aClus->et() >= EtCut) { hist_Et_->Fill(aClus->et()); hist_E_->Fill(aClus->energy()); hist_Eta_->Fill(aClus->eta()); hist_Phi_->Fill(aClus->phi()); } } for(int firstPhoton = 0, numPhotons = photons->size(); firstPhoton < numPhotons - 1; firstPhoton++) for(int secondPhoton = firstPhoton + 1; secondPhoton < numPhotons; secondPhoton++) { reco::Photon pOne = (*photons)[firstPhoton]; reco::Photon pTwo = (*photons)[secondPhoton]; double recoMass = findRecoMass(pOne, pTwo); hist_recoMass_withBackgroud_NoEtCut_->Fill(recoMass); if(pOne.et() >= 5 && pTwo.et() >= 5) hist_recoMass_withBackgroud_5EtCut_->Fill(recoMass); if(pOne.et() >= 10 && pTwo.et() >= 10) hist_recoMass_withBackgroud_10EtCut_->Fill(recoMass); if(pOne.et() >= 20 && pTwo.et() >= 20) hist_recoMass_withBackgroud_20EtCut_->Fill(recoMass); } edm::Handle pMCTruth ; evt.getByToken(MCTruthCollectionT_, pMCTruth); if (!pMCTruth.isValid()) { Labels l; labelsForToken(MCTruthCollectionT_, l); edm::LogError(""EgammaObjects"") << ""Error! can't get collection with label "" << l.module; } const HepMC::GenEvent* genEvent = pMCTruth->GetEvent(); for(HepMC::GenEvent::particle_const_iterator currentParticle = genEvent->particles_begin(); currentParticle != genEvent->particles_end(); currentParticle++ ) { if(abs((*currentParticle)->pdg_id())==22 && (*currentParticle)->status()==1 && (*currentParticle)->momentum().e()/cosh(ecalEta((*currentParticle)->momentum().eta(), (*currentParticle)->production_vertex()->position().z()/10., (*currentParticle)->production_vertex()->position().perp()/10.)) >= EtCut) { HepMC::FourVector vtx = (*currentParticle)->production_vertex()->position(); double phiTrue = (*currentParticle)->momentum().phi(); double etaTrue = ecalEta((*currentParticle)->momentum().eta(), vtx.z()/10., vtx.perp()/10.); double eTrue = (*currentParticle)->momentum().e(); double etTrue = (*currentParticle)->momentum().e()/cosh(etaTrue); double etaCurrent, etaFound = -999; double phiCurrent, phiFound = -999; double etCurrent, etFound = -999; double eCurrent, eFound = -999; reco::Photon bestMatchPhoton; double closestParticleDistance = 999; for(reco::PhotonCollection::const_iterator aClus = photons->begin(); aClus != photons->end(); aClus++) { if(aClus->et() > EtCut) { etaCurrent = aClus->eta(); phiCurrent = aClus->phi(); etCurrent = aClus->et(); eCurrent = aClus->energy(); double deltaPhi = phiCurrent-phiTrue; if(deltaPhi > Geom::pi()) deltaPhi -= 2.*Geom::pi(); if(deltaPhi < -Geom::pi()) deltaPhi += 2.*Geom::pi(); double deltaR = std::sqrt(std::pow(etaCurrent-etaTrue,2)+std::pow(deltaPhi,2)); if(deltaR < closestParticleDistance) { etFound = etCurrent; eFound = eCurrent; etaFound = etaCurrent; phiFound = phiCurrent; closestParticleDistance = deltaR; bestMatchPhoton = *aClus; } } } if(closestParticleDistance < 0.05 && etFound/etTrue > .5 && etFound/etTrue < 1.5) { hist_EtOverTruth_->Fill(etFound/etTrue); hist_EOverTruth_->Fill(eFound/eTrue); hist_EtaOverTruth_->Fill(etaFound/etaTrue); hist_PhiOverTruth_->Fill(phiFound/phiTrue); hist_EtEfficiency_->Fill(etTrue); hist_EEfficiency_->Fill(eTrue); hist_EtaEfficiency_->Fill(etaTrue); hist_PhiEfficiency_->Fill(phiTrue); double deltaPhi = phiFound-phiTrue; if(deltaPhi > Geom::pi()) deltaPhi -= 2.*Geom::pi(); if(deltaPhi < -Geom::pi()) deltaPhi += 2.*Geom::pi(); _TEMP_scatterPlot_EtOverTruthVsEt_->Fill(etFound,etFound/etTrue); _TEMP_scatterPlot_EtOverTruthVsE_->Fill(eFound,etFound/etTrue); _TEMP_scatterPlot_EtOverTruthVsEta_->Fill(etaFound,etFound/etTrue); _TEMP_scatterPlot_EtOverTruthVsPhi_->Fill(phiFound,etFound/etTrue); _TEMP_scatterPlot_EOverTruthVsEt_->Fill(etFound,eFound/eTrue); _TEMP_scatterPlot_EOverTruthVsE_->Fill(eFound,eFound/eTrue); _TEMP_scatterPlot_EOverTruthVsEta_->Fill(etaFound,eFound/eTrue); _TEMP_scatterPlot_EOverTruthVsPhi_->Fill(phiFound,eFound/eTrue); _TEMP_scatterPlot_deltaEtaVsEt_->Fill(etFound,etaFound-etaTrue); _TEMP_scatterPlot_deltaEtaVsE_->Fill(eFound,etaFound-etaTrue); _TEMP_scatterPlot_deltaEtaVsEta_->Fill(etaFound,etaFound-etaTrue); _TEMP_scatterPlot_deltaEtaVsPhi_->Fill(phiFound,etaFound-etaTrue); _TEMP_scatterPlot_deltaPhiVsEt_->Fill(etFound,deltaPhi); _TEMP_scatterPlot_deltaPhiVsE_->Fill(eFound,deltaPhi); _TEMP_scatterPlot_deltaPhiVsEta_->Fill(etaFound,deltaPhi); _TEMP_scatterPlot_deltaPhiVsPhi_->Fill(phiFound,deltaPhi); photonsMCMatched.push_back(bestMatchPhoton); } hist_EtNumRecoOverNumTrue_->Fill(etTrue); hist_ENumRecoOverNumTrue_->Fill(eTrue); hist_EtaNumRecoOverNumTrue_->Fill(etaTrue); hist_PhiNumRecoOverNumTrue_->Fill(phiTrue); } } if(photonsMCMatched.size() == 2) { reco::Photon pOne = photonsMCMatched[0]; reco::Photon pTwo = photonsMCMatched[1]; double recoMass = findRecoMass(pOne, pTwo); hist_All_recoMass_->Fill(recoMass); if(pOne.superCluster()->seed()->algo() == 1 && pTwo.superCluster()->seed()->algo() == 1) hist_BarrelOnly_recoMass_->Fill(recoMass); else if(pOne.superCluster()->seed()->algo() == 0 && pTwo.superCluster()->seed()->algo() == 0) hist_EndcapOnly_recoMass_->Fill(recoMass); else hist_Mixed_recoMass_->Fill(recoMass); } } void EgammaObjects::analyzeElectrons( const edm::Event& evt, const edm::EventSetup& es ) { edm::Handle pElectrons; evt.getByToken(RecoCollectionT_, pElectrons); if (!pElectrons.isValid()) { Labels l; labelsForToken(RecoCollectionT_, l); edm::LogError(""DOEPlotsProducerElectrons"") << ""Error! can't get collection with label "" << l.module; } const reco::GsfElectronCollection* electrons = pElectrons.product(); std::vector electronsMCMatched; for(reco::GsfElectronCollection::const_iterator aClus = electrons->begin(); aClus != electrons->end(); aClus++) { if(aClus->et() >= EtCut) { hist_Et_->Fill(aClus->et()); hist_E_->Fill(aClus->energy()); hist_Eta_->Fill(aClus->eta()); hist_Phi_->Fill(aClus->phi()); } } for(int firstElectron = 0, numElectrons = electrons->size(); firstElectron < numElectrons - 1; firstElectron++) for(int secondElectron = firstElectron + 1; secondElectron < numElectrons; secondElectron++) { reco::GsfElectron eOne = (*electrons)[firstElectron]; reco::GsfElectron eTwo = (*electrons)[secondElectron]; double recoMass = findRecoMass(eOne, eTwo); hist_recoMass_withBackgroud_NoEtCut_->Fill(recoMass); if(eOne.et() >= 5 && eTwo.et() >= 5) hist_recoMass_withBackgroud_5EtCut_->Fill(recoMass); if(eOne.et() >= 10 && eTwo.et() >= 10) hist_recoMass_withBackgroud_10EtCut_->Fill(recoMass); if(eOne.et() >= 20 && eTwo.et() >= 20) hist_recoMass_withBackgroud_20EtCut_->Fill(recoMass); } edm::Handle pMCTruth ; evt.getByToken(MCTruthCollectionT_, pMCTruth); if (!pMCTruth.isValid()) { Labels l; labelsForToken(MCTruthCollectionT_, l); edm::LogError(""DOEPlotsProducerElectrons"") << ""Error! can't get collection with label "" << l.module; } const HepMC::GenEvent* genEvent = pMCTruth->GetEvent(); for(HepMC::GenEvent::particle_const_iterator currentParticle = genEvent->particles_begin(); currentParticle != genEvent->particles_end(); currentParticle++ ) { if(abs((*currentParticle)->pdg_id())==11 && (*currentParticle)->status()==1 && (*currentParticle)->momentum().e()/cosh((*currentParticle)->momentum().eta()) >= EtCut) { double phiTrue = (*currentParticle)->momentum().phi(); double etaTrue = (*currentParticle)->momentum().eta(); double eTrue = (*currentParticle)->momentum().e(); double etTrue = (*currentParticle)->momentum().e()/cosh(etaTrue); double etaCurrent, etaFound = -999; double phiCurrent, phiFound = -999; double etCurrent, etFound = -999; double eCurrent, eFound = -999; reco::GsfElectron bestMatchElectron; double closestParticleDistance = 999; for(reco::GsfElectronCollection::const_iterator aClus = electrons->begin(); aClus != electrons->end(); aClus++) { if(aClus->et() > EtCut) { etaCurrent = aClus->eta(); phiCurrent = aClus->phi(); etCurrent = aClus->et(); eCurrent = aClus->energy(); double deltaPhi = phiCurrent-phiTrue; if(deltaPhi > Geom::pi()) deltaPhi -= 2.*Geom::pi(); if(deltaPhi < -Geom::pi()) deltaPhi += 2.*Geom::pi(); double deltaR = std::sqrt(std::pow(etaCurrent-etaTrue,2)+std::pow(deltaPhi,2)); if(deltaR < closestParticleDistance) { etFound = etCurrent; eFound = eCurrent; etaFound = etaCurrent; phiFound = phiCurrent; closestParticleDistance = deltaR; bestMatchElectron = *aClus; } } } if(closestParticleDistance < 0.05 && etFound/etTrue > .5 && etFound/etTrue < 1.5) { hist_EtOverTruth_->Fill(etFound/etTrue); hist_EOverTruth_->Fill(eFound/eTrue); hist_EtaOverTruth_->Fill(etaFound/etaTrue); hist_PhiOverTruth_->Fill(phiFound/phiTrue); hist_EtEfficiency_->Fill(etTrue); hist_EEfficiency_->Fill(eTrue); hist_EtaEfficiency_->Fill(etaTrue); hist_PhiEfficiency_->Fill(phiTrue); double deltaPhi = phiFound-phiTrue; if(deltaPhi > Geom::pi()) deltaPhi -= 2.*Geom::pi(); if(deltaPhi < -Geom::pi()) deltaPhi += 2.*Geom::pi(); _TEMP_scatterPlot_EtOverTruthVsEt_->Fill(etFound,etFound/etTrue); _TEMP_scatterPlot_EtOverTruthVsE_->Fill(eFound,etFound/etTrue); _TEMP_scatterPlot_EtOverTruthVsEta_->Fill(etaFound,etFound/etTrue); _TEMP_scatterPlot_EtOverTruthVsPhi_->Fill(phiFound,etFound/etTrue); _TEMP_scatterPlot_EOverTruthVsEt_->Fill(etFound,eFound/eTrue); _TEMP_scatterPlot_EOverTruthVsE_->Fill(eFound,eFound/eTrue); _TEMP_scatterPlot_EOverTruthVsEta_->Fill(etaFound,eFound/eTrue); _TEMP_scatterPlot_EOverTruthVsPhi_->Fill(phiFound,eFound/eTrue); _TEMP_scatterPlot_deltaEtaVsEt_->Fill(etFound,etaFound-etaTrue); _TEMP_scatterPlot_deltaEtaVsE_->Fill(eFound,etaFound-etaTrue); _TEMP_scatterPlot_deltaEtaVsEta_->Fill(etaFound,etaFound-etaTrue); _TEMP_scatterPlot_deltaEtaVsPhi_->Fill(phiFound,etaFound-etaTrue); _TEMP_scatterPlot_deltaPhiVsEt_->Fill(etFound,deltaPhi); _TEMP_scatterPlot_deltaPhiVsE_->Fill(eFound,deltaPhi); _TEMP_scatterPlot_deltaPhiVsEta_->Fill(etaFound,deltaPhi); _TEMP_scatterPlot_deltaPhiVsPhi_->Fill(phiFound,deltaPhi); electronsMCMatched.push_back(bestMatchElectron); } hist_EtNumRecoOverNumTrue_->Fill(etTrue); hist_ENumRecoOverNumTrue_->Fill(eTrue); hist_EtaNumRecoOverNumTrue_->Fill(etaTrue); hist_PhiNumRecoOverNumTrue_->Fill(phiTrue); } } if(electronsMCMatched.size() == 2) { reco::GsfElectron eOne = electronsMCMatched[0]; reco::GsfElectron eTwo = electronsMCMatched[1]; double recoMass = findRecoMass(eOne, eTwo); hist_All_recoMass_->Fill(recoMass); if(eOne.superCluster()->seed()->algo() == 1 && eTwo.superCluster()->seed()->algo() == 1) hist_BarrelOnly_recoMass_->Fill(recoMass); else if(eOne.superCluster()->seed()->algo() == 0 && eTwo.superCluster()->seed()->algo() == 0) hist_EndcapOnly_recoMass_->Fill(recoMass); else hist_Mixed_recoMass_->Fill(recoMass); } } double EgammaObjects::findRecoMass(const reco::Photon& pOne,const reco::Photon& pTwo) { double cosTheta = (cos(pOne.superCluster()->phi() - pTwo.superCluster()->phi()) + sinh(pOne.superCluster()->eta()) * sinh(pTwo.superCluster()->eta())) / (cosh(pOne.superCluster()->eta()) * cosh(pTwo.superCluster()->eta())); double recoMass = sqrt(2 * (pOne.superCluster())->energy() * (pTwo.superCluster())->energy() * (1 - cosTheta)); return recoMass; } double EgammaObjects::findRecoMass(const reco::GsfElectron& eOne, const reco::GsfElectron& eTwo) { double cosTheta = (cos(eOne.caloPosition().phi() - eTwo.caloPosition().phi()) + sinh(eOne.caloPosition().eta()) * sinh(eTwo.caloPosition().eta())) / (cosh(eOne.caloPosition().eta()) * cosh(eTwo.caloPosition().eta())); double recoMass = sqrt(2 * eOne.caloEnergy() * eTwo.caloEnergy() * (1 - cosTheta)); return recoMass; } float EgammaObjects::ecalEta(float EtaParticle , float Zvertex, float plane_Radius) { const float R_ECAL = 136.5; const float Z_Endcap = 328.0; const float etaBarrelEndcap = 1.479; if(EtaParticle != 0.) { float Theta = 0.0 ; float ZEcal = (R_ECAL-plane_Radius)*sinh(EtaParticle)+Zvertex; if(ZEcal != 0.0) Theta = atan(R_ECAL/ZEcal); if(Theta<0.0) Theta = Theta+Geom::pi() ; float ETA = - log(tan(0.5*Theta)); if( std::abs(ETA) > etaBarrelEndcap ) { float Zend = Z_Endcap ; if(EtaParticle<0.0 ) Zend = -Zend ; float Zlen = Zend - Zvertex ; float RR = Zlen/sinh(EtaParticle); Theta = atan((RR+plane_Radius)/Zend); if(Theta<0.0) Theta = Theta+Geom::pi() ; ETA = - log(tan(0.5*Theta)); } return ETA; } else { edm::LogWarning("""") << ""[EgammaObjects::ecalEta] Warning: Eta equals to zero, not correcting"" ; return EtaParticle; } } void EgammaObjects::endJob() { rootFile_->cd(); rootFile_->mkdir(particleString.c_str()); getDeltaResHistosViaSlicing(); getEfficiencyHistosViaDividing(); fitHistos(); applyLabels(); setDrawOptions(); saveHistos(); rootFile_->Close(); } void EgammaObjects::getDeltaResHistosViaSlicing() { _TEMP_scatterPlot_EtOverTruthVsEt_->FitSlicesY(0,1,hist_bins_Et_,10,""QRG3""); _TEMP_scatterPlot_EtOverTruthVsE_->FitSlicesY(0,1,hist_bins_E_,10,""QRG3""); _TEMP_scatterPlot_EtOverTruthVsEta_->FitSlicesY(0,1,hist_bins_Eta_,10,""QRG2""); _TEMP_scatterPlot_EtOverTruthVsPhi_->FitSlicesY(0,1,hist_bins_Phi_,10,""QRG2""); _TEMP_scatterPlot_EOverTruthVsEt_->FitSlicesY(0,1,hist_bins_Et_,10,""QRG3""); _TEMP_scatterPlot_EOverTruthVsE_->FitSlicesY(0,1,hist_bins_E_,10,""QRG3""); _TEMP_scatterPlot_EOverTruthVsEta_->FitSlicesY(0,1,hist_bins_Eta_,10,""QRG2""); _TEMP_scatterPlot_EOverTruthVsPhi_->FitSlicesY(0,1,hist_bins_Phi_,10,""QRG2""); _TEMP_scatterPlot_deltaEtaVsEt_->FitSlicesY(0,1,hist_bins_Et_,10,""QRG3""); _TEMP_scatterPlot_deltaEtaVsE_->FitSlicesY(0,1,hist_bins_E_,10,""QRG3""); _TEMP_scatterPlot_deltaEtaVsEta_->FitSlicesY(0,1,hist_bins_Eta_,10,""QRG2""); _TEMP_scatterPlot_deltaEtaVsPhi_->FitSlicesY(0,1,hist_bins_Phi_,10,""QRG2""); _TEMP_scatterPlot_deltaPhiVsEt_->FitSlicesY(0,1,hist_bins_Et_,10,""QRG3""); _TEMP_scatterPlot_deltaPhiVsE_->FitSlicesY(0,1,hist_bins_E_,10,""QRG3""); _TEMP_scatterPlot_deltaPhiVsEta_->FitSlicesY(0,1,hist_bins_Eta_,10,""QRG2""); _TEMP_scatterPlot_deltaPhiVsPhi_->FitSlicesY(0,1,hist_bins_Phi_,10,""QRG2""); hist_EtOverTruthVsEt_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EtOverTruthVsEt__1""); hist_EtOverTruthVsE_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EtOverTruthVsE__1""); hist_EtOverTruthVsEta_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EtOverTruthVsEta__1""); hist_EtOverTruthVsPhi_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EtOverTruthVsPhi__1""); hist_EOverTruthVsEt_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EOverTruthVsEt__1""); hist_EOverTruthVsE_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EOverTruthVsE__1""); hist_EOverTruthVsEta_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EOverTruthVsEta__1""); hist_EOverTruthVsPhi_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EOverTruthVsPhi__1""); hist_deltaEtaVsEt_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaEtaVsEt__1""); hist_deltaEtaVsE_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaEtaVsE__1""); hist_deltaEtaVsEta_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaEtaVsEta__1""); hist_deltaEtaVsPhi_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaEtaVsPhi__1""); hist_deltaPhiVsEt_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaPhiVsEt__1""); hist_deltaPhiVsE_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaPhiVsE__1""); hist_deltaPhiVsEta_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaPhiVsEta__1""); hist_deltaPhiVsPhi_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaPhiVsPhi__1""); hist_EtOverTruthVsEt_->SetNameTitle(""hist_EtOverTruthVsEt_"",(""Reco Et over True Et VS Et of ""+particleString).c_str()); hist_EtOverTruthVsE_->SetNameTitle(""hist_EtOverTruthVsE_"",(""Reco Et over True Et VS E of ""+particleString).c_str()); hist_EtOverTruthVsEta_->SetNameTitle(""hist_EtOverTruthVsEta_"",(""Reco Et over True Et VS Eta of ""+particleString).c_str()); hist_EtOverTruthVsPhi_->SetNameTitle(""hist_EtOverTruthVsPhi_"",(""Reco Et over True Et VS Phi of ""+particleString).c_str()); hist_EOverTruthVsEt_->SetNameTitle(""hist_EOverTruthVsEt_"",(""Reco E over True E VS Et of ""+particleString).c_str()); hist_EOverTruthVsE_->SetNameTitle(""hist_EOverTruthVsE_"",(""Reco E over True E VS E of ""+particleString).c_str()); hist_EOverTruthVsEta_->SetNameTitle(""hist_EOverTruthVsEta_"",(""Reco E over True E VS Eta of ""+particleString).c_str()); hist_EOverTruthVsPhi_->SetNameTitle(""hist_EOverTruthVsPhi_"",(""Reco E over True E VS Phi of ""+particleString).c_str()); hist_deltaEtaVsEt_->SetNameTitle(""hist_deltaEtaVsEt_"",(""delta Eta VS Et of ""+particleString).c_str()); hist_deltaEtaVsE_->SetNameTitle(""hist_deltaEtaVsE_"",(""delta Eta VS E of ""+particleString).c_str()); hist_deltaEtaVsEta_->SetNameTitle(""hist_deltaEtaVsEta_"",(""delta Eta VS Eta of ""+particleString).c_str()); hist_deltaEtaVsPhi_->SetNameTitle(""hist_deltaEtaVsPhi_"",(""delta Eta VS Phi of ""+particleString).c_str()); hist_deltaPhiVsEt_->SetNameTitle(""hist_deltaPhiVsEt_"",(""delta Phi VS Et of ""+particleString).c_str()); hist_deltaPhiVsE_->SetNameTitle(""hist_deltaPhiVsE_"",(""delta Phi VS E of ""+particleString).c_str()); hist_deltaPhiVsEta_->SetNameTitle(""hist_deltaPhiVsEta_"",(""delta Phi VS Eta of ""+particleString).c_str()); hist_deltaPhiVsPhi_->SetNameTitle(""hist_deltaPhiVsPhi_"",(""delta Phi VS Phi of ""+particleString).c_str()); hist_resolutionEtVsEt_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EtOverTruthVsEt__2""); hist_resolutionEtVsE_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EtOverTruthVsE__2""); hist_resolutionEtVsEta_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EtOverTruthVsEta__2""); hist_resolutionEtVsPhi_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EtOverTruthVsPhi__2""); hist_resolutionEVsEt_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EOverTruthVsEt__2""); hist_resolutionEVsE_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EOverTruthVsE__2""); hist_resolutionEVsEta_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EOverTruthVsEta__2""); hist_resolutionEVsPhi_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_EOverTruthVsPhi__2""); hist_resolutionEtaVsEt_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaEtaVsEt__2""); hist_resolutionEtaVsE_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaEtaVsE__2""); hist_resolutionEtaVsEta_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaEtaVsEta__2""); hist_resolutionEtaVsPhi_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaEtaVsPhi__2""); hist_resolutionPhiVsEt_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaPhiVsEt__2""); hist_resolutionPhiVsE_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaPhiVsE__2""); hist_resolutionPhiVsEta_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaPhiVsEta__2""); hist_resolutionPhiVsPhi_ = (TH1D*)gDirectory->Get(""_TEMP_scatterPlot_deltaPhiVsPhi__2""); hist_resolutionEtVsEt_->SetNameTitle(""hist_resolutionEtVsEt_"",(""#sigma of Reco Et over True Et VS Et of ""+particleString).c_str()); hist_resolutionEtVsE_->SetNameTitle(""hist_resolutionEtVsE_"",(""#sigma of Reco Et over True Et VS E of ""+particleString).c_str()); hist_resolutionEtVsEta_->SetNameTitle(""hist_resolutionEtVsEta_"",(""#sigma of Reco Et over True Et VS Eta of ""+particleString).c_str()); hist_resolutionEtVsPhi_->SetNameTitle(""hist_resolutionEtVsPhi_"",(""#sigma of Reco Et over True Et VS Phi of ""+particleString).c_str()); hist_resolutionEVsEt_->SetNameTitle(""hist_resolutionEVsEt_"",(""#sigma of Reco E over True E VS Et of ""+particleString).c_str()); hist_resolutionEVsE_->SetNameTitle(""hist_resolutionEVsE_"",(""#sigma of Reco E over True E VS E of ""+particleString).c_str()); hist_resolutionEVsEta_->SetNameTitle(""hist_resolutionEVsEta_"",(""#sigma of Reco E over True E VS Eta of ""+particleString).c_str()); hist_resolutionEVsPhi_->SetNameTitle(""hist_resolutionEVsPhi_"",(""#sigma of Reco E over True E VS Phi of ""+particleString).c_str()); hist_resolutionEtaVsEt_->SetNameTitle(""hist_resolutionEtaVsEt_"",(""#sigma of delta Eta VS Et of ""+particleString).c_str()); hist_resolutionEtaVsE_->SetNameTitle(""hist_resolutionEtaVsE_"",(""#sigma of delta Eta VS E of ""+particleString).c_str()); hist_resolutionEtaVsEta_->SetNameTitle(""hist_resolutionEtaVsEta_"",(""#sigma of delta Eta VS Eta of ""+particleString).c_str()); hist_resolutionEtaVsPhi_->SetNameTitle(""hist_resolutionEtaVsPhi_"",(""#sigma of delta Eta VS Phi of ""+particleString).c_str()); hist_resolutionPhiVsEt_->SetNameTitle(""hist_resolutionPhiVsEt_"",(""#sigma of delta Phi VS Et of ""+particleString).c_str()); hist_resolutionPhiVsE_->SetNameTitle(""hist_resolutionPhiVsE_"",(""#sigma of delta Phi VS E of ""+particleString).c_str()); hist_resolutionPhiVsEta_->SetNameTitle(""hist_resolutionPhiVsEta_"",(""#sigma of delta Phi VS Eta of ""+particleString).c_str()); hist_resolutionPhiVsPhi_->SetNameTitle(""hist_resolutionPhiVsPhi_"",(""#sigma of delta Phi VS Phi of ""+particleString).c_str()); } void EgammaObjects::getEfficiencyHistosViaDividing() { hist_EtEfficiency_->Divide(hist_EtEfficiency_,hist_EtNumRecoOverNumTrue_,1,1); hist_EEfficiency_->Divide(hist_EEfficiency_,hist_ENumRecoOverNumTrue_,1,1); hist_EtaEfficiency_->Divide(hist_EtaEfficiency_,hist_EtaNumRecoOverNumTrue_,1,1); hist_PhiEfficiency_->Divide(hist_PhiEfficiency_,hist_PhiNumRecoOverNumTrue_,1,1); hist_EtNumRecoOverNumTrue_->Divide(hist_Et_,hist_EtNumRecoOverNumTrue_,1,1); hist_ENumRecoOverNumTrue_->Divide(hist_E_,hist_ENumRecoOverNumTrue_,1,1); hist_EtaNumRecoOverNumTrue_->Divide(hist_Eta_,hist_EtaNumRecoOverNumTrue_,1,1); hist_PhiNumRecoOverNumTrue_->Divide(hist_Phi_,hist_PhiNumRecoOverNumTrue_,1,1); } void EgammaObjects::fitHistos() { //Use our own copy for thread safety TF1 gaus(""mygaus"",""gaus""); hist_EtOverTruth_->Fit(&gaus,""QEM""); // hist_EtNumRecoOverNumTrue_->Fit(""pol1"",""QEM""); hist_EOverTruth_->Fit(&gaus,""QEM""); // hist_ENumRecoOverNumTrue_->Fit(""pol1"",""QEM""); hist_EtaOverTruth_->Fit(&gaus,""QEM""); // hist_EtaNumRecoOverNumTrue_->Fit(""pol1"",""QEM""); hist_PhiOverTruth_->Fit(&gaus,""QEM""); // hist_PhiNumRecoOverNumTrue_->Fit(""pol1"",""QEM""); /* hist_EtOverTruthVsEt_->Fit(""pol1"",""QEM""); hist_EtOverTruthVsEta_->Fit(""pol1"",""QEM""); hist_EtOverTruthVsPhi_->Fit(""pol1"",""QEM""); hist_resolutionEtVsEt_->Fit(""pol1"",""QEM""); hist_resolutionEtVsEta_->Fit(""pol1"",""QEM""); hist_resolutionEtVsPhi_->Fit(""pol1"",""QEM""); hist_EOverTruthVsEt_->Fit(""pol1"",""QEM""); hist_EOverTruthVsEta_->Fit(""pol1"",""QEM""); hist_EOverTruthVsPhi_->Fit(""pol1"",""QEM""); hist_resolutionEVsEt_->Fit(""pol1"",""QEM""); hist_resolutionEVsEta_->Fit(""pol1"",""QEM""); hist_resolutionEVsPhi_->Fit(""pol1"",""QEM""); hist_deltaEtaVsEt_->Fit(""pol1"",""QEM""); hist_deltaEtaVsEta_->Fit(""pol1"",""QEM""); hist_deltaEtaVsPhi_->Fit(""pol1"",""QEM""); hist_resolutionEtaVsEt_->Fit(""pol1"",""QEM""); hist_resolutionEtaVsEta_->Fit(""pol1"",""QEM""); hist_resolutionEtaVsPhi_->Fit(""pol1"",""QEM""); hist_deltaPhiVsEt_->Fit(""pol1"",""QEM""); hist_deltaPhiVsEta_->Fit(""pol1"",""QEM""); hist_deltaPhiVsPhi_->Fit(""pol1"",""QEM""); hist_resolutionPhiVsEt_->Fit(""pol1"",""QEM""); hist_resolutionPhiVsEta_->Fit(""pol1"",""QEM""); hist_resolutionPhiVsPhi_->Fit(""pol1"",""QEM""); */ } void EgammaObjects::applyLabels() { hist_Et_->GetXaxis()->SetTitle(""Et (GeV)""); hist_Et_->GetYaxis()->SetTitle(""# per Et Bin""); hist_EtOverTruth_->GetXaxis()->SetTitle(""Reco Et/True Et""); hist_EtOverTruth_->GetYaxis()->SetTitle(""# per Ratio Bin""); hist_EtEfficiency_->GetXaxis()->SetTitle(""Et (GeV)""); hist_EtEfficiency_->GetYaxis()->SetTitle(""# True Reconstructed/# True per Et Bin""); hist_EtNumRecoOverNumTrue_->GetXaxis()->SetTitle(""Et (GeV)""); hist_EtNumRecoOverNumTrue_->GetYaxis()->SetTitle(""# Reco/# True per Et Bin""); hist_EtOverTruthVsEt_->GetXaxis()->SetTitle(""Et (GeV)""); hist_EtOverTruthVsEt_->GetYaxis()->SetTitle(""Reco Et/True Et per Et Bin""); hist_EtOverTruthVsE_->GetXaxis()->SetTitle(""E (GeV)""); hist_EtOverTruthVsE_->GetYaxis()->SetTitle(""Reco Et/True Et per E Bin""); hist_EtOverTruthVsEta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_EtOverTruthVsEta_->GetYaxis()->SetTitle(""Reco Et/True Et per Eta Bin""); hist_EtOverTruthVsPhi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_EtOverTruthVsPhi_->GetYaxis()->SetTitle(""Reco Et/True Et per Phi Bin""); hist_resolutionEtVsEt_->GetXaxis()->SetTitle(""Et (GeV)""); hist_resolutionEtVsEt_->GetYaxis()->SetTitle(""#sigma of Reco Et/True Et per Et Bin""); hist_resolutionEtVsE_->GetXaxis()->SetTitle(""E (GeV)""); hist_resolutionEtVsE_->GetYaxis()->SetTitle(""#sigma of Reco Et/True Et per E Bin""); hist_resolutionEtVsEta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_resolutionEtVsEta_->GetYaxis()->SetTitle(""#sigma of Reco Et/True Et per Eta Bin""); hist_resolutionEtVsPhi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_resolutionEtVsPhi_->GetYaxis()->SetTitle(""#sigma of Reco Et/True Et per Phi Bin""); hist_E_->GetXaxis()->SetTitle(""E (GeV)""); hist_E_->GetYaxis()->SetTitle(""# per E Bin""); hist_EOverTruth_->GetXaxis()->SetTitle(""Reco E/True E""); hist_EOverTruth_->GetYaxis()->SetTitle(""# per Ratio Bin""); hist_EEfficiency_->GetXaxis()->SetTitle(""E (GeV)""); hist_EEfficiency_->GetYaxis()->SetTitle(""# True Reconstructed/# True per E Bin""); hist_ENumRecoOverNumTrue_->GetXaxis()->SetTitle(""E (GeV)""); hist_ENumRecoOverNumTrue_->GetYaxis()->SetTitle(""# Reco/# True per E Bin""); hist_EOverTruthVsEt_->GetXaxis()->SetTitle(""Et (GeV)""); hist_EOverTruthVsEt_->GetYaxis()->SetTitle(""Reco E/True E per Et Bin""); hist_EOverTruthVsE_->GetXaxis()->SetTitle(""E (GeV)""); hist_EOverTruthVsE_->GetYaxis()->SetTitle(""Reco E/True E per E Bin""); hist_EOverTruthVsEta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_EOverTruthVsEta_->GetYaxis()->SetTitle(""Reco E/True E per Eta Bin""); hist_EOverTruthVsPhi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_EOverTruthVsPhi_->GetYaxis()->SetTitle(""Reco E/True E per Phi Bin""); hist_resolutionEVsEt_->GetXaxis()->SetTitle(""Et (GeV)""); hist_resolutionEVsEt_->GetYaxis()->SetTitle(""#sigma of Reco E/True E per Et Bin""); hist_resolutionEVsE_->GetXaxis()->SetTitle(""E (GeV)""); hist_resolutionEVsE_->GetYaxis()->SetTitle(""#sigma of Reco E/True E per E Bin""); hist_resolutionEVsEta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_resolutionEVsEta_->GetYaxis()->SetTitle(""#sigma of Reco E/True E per Eta Bin""); hist_resolutionEVsPhi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_resolutionEVsPhi_->GetYaxis()->SetTitle(""#sigma of Reco E/True E per Phi Bin""); hist_Eta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_Eta_->GetYaxis()->SetTitle(""# per Eta Bin""); hist_EtaOverTruth_->GetXaxis()->SetTitle(""Reco Eta/True Eta""); hist_EtaOverTruth_->GetYaxis()->SetTitle(""# per Ratio Bin""); hist_EtaEfficiency_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_EtaEfficiency_->GetYaxis()->SetTitle(""# True Reconstructed/# True per Eta Bin""); hist_EtaNumRecoOverNumTrue_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_EtaNumRecoOverNumTrue_->GetYaxis()->SetTitle(""# Reco/# True per Eta Bin""); hist_deltaEtaVsEt_->GetXaxis()->SetTitle(""Et (GeV)""); hist_deltaEtaVsEt_->GetYaxis()->SetTitle(""Reco Eta - True Eta per Et Bin""); hist_deltaEtaVsE_->GetXaxis()->SetTitle(""E (GeV)""); hist_deltaEtaVsE_->GetYaxis()->SetTitle(""Reco Eta - True Eta per E Bin""); hist_deltaEtaVsEta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_deltaEtaVsEta_->GetYaxis()->SetTitle(""Reco Eta - True Eta per Eta Bin""); hist_deltaEtaVsPhi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_deltaEtaVsPhi_->GetYaxis()->SetTitle(""Reco Eta - True Eta per Phi Bin""); hist_resolutionEtaVsEt_->GetXaxis()->SetTitle(""Et (GeV)""); hist_resolutionEtaVsEt_->GetYaxis()->SetTitle(""#sigma of Reco Eta - True Eta per Et Bin""); hist_resolutionEtaVsE_->GetXaxis()->SetTitle(""E (GeV)""); hist_resolutionEtaVsE_->GetYaxis()->SetTitle(""#sigma of Reco Eta - True Eta per E Bin""); hist_resolutionEtaVsEta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_resolutionEtaVsEta_->GetYaxis()->SetTitle(""#sigma of Reco Eta - True Eta per Eta Bin""); hist_resolutionEtaVsPhi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_resolutionEtaVsPhi_->GetYaxis()->SetTitle(""#sigma of Reco Eta - True Eta per Phi Bin""); hist_Phi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_Phi_->GetYaxis()->SetTitle(""# per Phi Bin""); hist_PhiOverTruth_->GetXaxis()->SetTitle(""Reco Phi/True Phi""); hist_PhiOverTruth_->GetYaxis()->SetTitle(""# per Ratio Bin""); hist_PhiEfficiency_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_PhiEfficiency_->GetYaxis()->SetTitle(""# True Reconstructed/# True per Phi Bin""); hist_PhiNumRecoOverNumTrue_->GetXaxis()->SetTitle(""#Phi (Radians)""); hist_PhiNumRecoOverNumTrue_->GetYaxis()->SetTitle(""# Reco/# True per Phi Bin""); hist_deltaPhiVsEt_->GetXaxis()->SetTitle(""Et (GeV)""); hist_deltaPhiVsEt_->GetYaxis()->SetTitle(""Reco Phi - True Phi per Et Bin""); hist_deltaPhiVsE_->GetXaxis()->SetTitle(""E (GeV)""); hist_deltaPhiVsE_->GetYaxis()->SetTitle(""Reco Phi - True Phi per E Bin""); hist_deltaPhiVsEta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_deltaPhiVsEta_->GetYaxis()->SetTitle(""Reco Phi - True Phi per Eta Bin""); hist_deltaPhiVsPhi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_deltaPhiVsPhi_->GetYaxis()->SetTitle(""Reco Phi - True Phi per Phi Bin""); hist_resolutionPhiVsEt_->GetXaxis()->SetTitle(""Et (GeV)""); hist_resolutionPhiVsEt_->GetYaxis()->SetTitle(""#sigma of Reco Phi - True Phi per Et Bin""); hist_resolutionPhiVsE_->GetXaxis()->SetTitle(""E (GeV)""); hist_resolutionPhiVsE_->GetYaxis()->SetTitle(""#sigma of Reco Phi - True Phi per E Bin""); hist_resolutionPhiVsEta_->GetXaxis()->SetTitle(""#eta (Radians)""); hist_resolutionPhiVsEta_->GetYaxis()->SetTitle(""#sigma of Reco Phi - True Phi per Eta Bin""); hist_resolutionPhiVsPhi_->GetXaxis()->SetTitle(""#phi (Radians)""); hist_resolutionPhiVsPhi_->GetYaxis()->SetTitle(""#sigma of Reco Phi - True Phi per Phi Bin""); std::string recoParticleName; if( particleID == 22 ) recoParticleName = ""Reco Higgs""; else if( particleID == 11 ) recoParticleName = ""Reco Z""; hist_All_recoMass_->GetXaxis()->SetTitle((recoParticleName+"" Mass (GeV)"").c_str()); hist_All_recoMass_->GetYaxis()->SetTitle(""# of Reco Masses per Mass Bin""); hist_BarrelOnly_recoMass_->GetXaxis()->SetTitle((recoParticleName+"" Mass (GeV)"").c_str()); hist_BarrelOnly_recoMass_->GetYaxis()->SetTitle(""# of Reco Masses per Mass Bin""); hist_EndcapOnly_recoMass_->GetXaxis()->SetTitle((recoParticleName+"" Mass (GeV)"").c_str()); hist_EndcapOnly_recoMass_->GetYaxis()->SetTitle(""# of Reco Masses per Mass Bin""); hist_Mixed_recoMass_->GetXaxis()->SetTitle((recoParticleName+"" Mass (GeV)"").c_str()); hist_Mixed_recoMass_->GetYaxis()->SetTitle(""# of Reco Masses per Mass Bin""); hist_recoMass_withBackgroud_NoEtCut_->GetXaxis()->SetTitle((recoParticleName+"" Mass (GeV)"").c_str()); hist_recoMass_withBackgroud_NoEtCut_->GetYaxis()->SetTitle(""# of Reco Masses per Mass Bin""); hist_recoMass_withBackgroud_5EtCut_->GetXaxis()->SetTitle((recoParticleName+"" Mass (GeV)"").c_str()); hist_recoMass_withBackgroud_5EtCut_->GetYaxis()->SetTitle(""# of Reco Masses per Mass Bin""); hist_recoMass_withBackgroud_10EtCut_->GetXaxis()->SetTitle((recoParticleName+"" Mass (GeV)"").c_str()); hist_recoMass_withBackgroud_10EtCut_->GetYaxis()->SetTitle(""# of Reco Masses per Mass Bin""); hist_recoMass_withBackgroud_20EtCut_->GetXaxis()->SetTitle((recoParticleName+"" Mass (GeV)"").c_str()); hist_recoMass_withBackgroud_20EtCut_->GetYaxis()->SetTitle(""# of Reco Masses per Mass Bin""); } void EgammaObjects::setDrawOptions() { hist_Et_->SetOption(""e""); hist_EtOverTruth_->SetOption(""e""); hist_EtEfficiency_->SetOption(""e""); hist_EtNumRecoOverNumTrue_->SetOption(""e""); hist_EtOverTruthVsEt_->SetOption(""e""); hist_EtOverTruthVsE_->SetOption(""e""); hist_EtOverTruthVsEta_->SetOption(""e""); hist_EtOverTruthVsPhi_->SetOption(""e""); hist_resolutionEtVsEt_->SetOption(""e""); hist_resolutionEtVsE_->SetOption(""e""); hist_resolutionEtVsEta_->SetOption(""e""); hist_resolutionEtVsPhi_->SetOption(""e""); hist_E_->SetOption(""e""); hist_EOverTruth_->SetOption(""e""); hist_EEfficiency_->SetOption(""e""); hist_ENumRecoOverNumTrue_->SetOption(""e""); hist_EOverTruthVsEt_->SetOption(""e""); hist_EOverTruthVsE_->SetOption(""e""); hist_EOverTruthVsEta_->SetOption(""e""); hist_EOverTruthVsPhi_->SetOption(""e""); hist_resolutionEVsEt_->SetOption(""e""); hist_resolutionEVsE_->SetOption(""e""); hist_resolutionEVsEta_->SetOption(""e""); hist_resolutionEVsPhi_->SetOption(""e""); hist_Eta_->SetOption(""e""); hist_EtaOverTruth_->SetOption(""e""); hist_EtaEfficiency_->SetOption(""e""); hist_EtaNumRecoOverNumTrue_->SetOption(""e""); hist_deltaEtaVsEt_->SetOption(""e""); hist_deltaEtaVsE_->SetOption(""e""); hist_deltaEtaVsEta_->SetOption(""e""); hist_deltaEtaVsPhi_->SetOption(""e""); hist_resolutionEtaVsEt_->SetOption(""e""); hist_resolutionEtaVsE_->SetOption(""e""); hist_resolutionEtaVsEta_->SetOption(""e""); hist_resolutionEtaVsPhi_->SetOption(""e""); hist_Phi_->SetOption(""e""); hist_PhiOverTruth_->SetOption(""e""); hist_PhiEfficiency_->SetOption(""e""); hist_PhiNumRecoOverNumTrue_->SetOption(""e""); hist_deltaPhiVsEt_->SetOption(""e""); hist_deltaPhiVsE_->SetOption(""e""); hist_deltaPhiVsEta_->SetOption(""e""); hist_deltaPhiVsPhi_->SetOption(""e""); hist_resolutionPhiVsEt_->SetOption(""e""); hist_resolutionPhiVsE_->SetOption(""e""); hist_resolutionPhiVsEta_->SetOption(""e""); hist_resolutionPhiVsPhi_->SetOption(""e""); hist_All_recoMass_->SetOption(""e""); hist_BarrelOnly_recoMass_->SetOption(""e""); hist_EndcapOnly_recoMass_->SetOption(""e""); hist_Mixed_recoMass_->SetOption(""e""); hist_recoMass_withBackgroud_NoEtCut_->SetOption(""e""); hist_recoMass_withBackgroud_5EtCut_->SetOption(""e""); hist_recoMass_withBackgroud_10EtCut_->SetOption(""e""); hist_recoMass_withBackgroud_20EtCut_->SetOption(""e""); } void EgammaObjects::saveHistos() { rootFile_->cd(); rootFile_->GetDirectory(particleString.c_str())->mkdir(""ET""); rootFile_->cd((""/""+particleString+""/ET"").c_str()); hist_Et_->Write(); hist_EtOverTruth_->Write(); hist_EtEfficiency_->Write(); hist_EtNumRecoOverNumTrue_->Write(); hist_EtOverTruthVsEt_->Write(); hist_EtOverTruthVsE_->Write(); hist_EtOverTruthVsEta_->Write(); hist_EtOverTruthVsPhi_->Write(); hist_resolutionEtVsEt_->Write(); hist_resolutionEtVsE_->Write(); hist_resolutionEtVsEta_->Write(); hist_resolutionEtVsPhi_->Write(); rootFile_->cd(); rootFile_->GetDirectory(particleString.c_str())->mkdir(""E""); rootFile_->cd((""/""+particleString+""/E"").c_str()); hist_E_->Write(); hist_EOverTruth_->Write(); hist_EEfficiency_->Write(); hist_ENumRecoOverNumTrue_->Write(); hist_EOverTruthVsEt_->Write(); hist_EOverTruthVsE_->Write(); hist_EOverTruthVsEta_->Write(); hist_EOverTruthVsPhi_->Write(); hist_resolutionEVsEt_->Write(); hist_resolutionEVsE_->Write(); hist_resolutionEVsEta_->Write(); hist_resolutionEVsPhi_->Write(); rootFile_->cd(); rootFile_->GetDirectory(particleString.c_str())->mkdir(""Eta""); rootFile_->cd((""/""+particleString+""/Eta"").c_str()); hist_Eta_->Write(); hist_EtaOverTruth_->Write(); hist_EtaEfficiency_->Write(); hist_EtaNumRecoOverNumTrue_->Write(); hist_deltaEtaVsEt_->Write(); hist_deltaEtaVsE_->Write(); hist_deltaEtaVsEta_->Write(); hist_deltaEtaVsPhi_->Write(); hist_resolutionEtaVsEt_->Write(); hist_resolutionEtaVsE_->Write(); hist_resolutionEtaVsEta_->Write(); hist_resolutionEtaVsPhi_->Write(); rootFile_->cd(); rootFile_->GetDirectory(particleString.c_str())->mkdir(""Phi""); rootFile_->cd((""/""+particleString+""/Phi"").c_str()); hist_Phi_->Write(); hist_PhiOverTruth_->Write(); hist_PhiEfficiency_->Write(); hist_PhiNumRecoOverNumTrue_->Write(); hist_deltaPhiVsEt_->Write(); hist_deltaPhiVsE_->Write(); hist_deltaPhiVsEta_->Write(); hist_deltaPhiVsPhi_->Write(); hist_resolutionPhiVsEt_->Write(); hist_resolutionPhiVsE_->Write(); hist_resolutionPhiVsEta_->Write(); hist_resolutionPhiVsPhi_->Write(); std::string recoParticleName; if( particleID == 22 ) recoParticleName = ""HiggsRecoMass""; else if( particleID == 11 ) recoParticleName = ""ZRecoMass""; rootFile_->cd(); rootFile_->GetDirectory(particleString.c_str())->mkdir(recoParticleName.c_str()); rootFile_->cd((""/""+particleString+""/""+recoParticleName).c_str()); hist_All_recoMass_->Write(); hist_BarrelOnly_recoMass_->Write(); hist_EndcapOnly_recoMass_->Write(); hist_Mixed_recoMass_->Write(); hist_recoMass_withBackgroud_NoEtCut_->Write(); hist_recoMass_withBackgroud_5EtCut_->Write(); hist_recoMass_withBackgroud_10EtCut_->Write(); hist_recoMass_withBackgroud_20EtCut_->Write(); rootFile_->cd(); rootFile_->GetDirectory(particleString.c_str())->mkdir(""_TempScatterPlots""); rootFile_->cd((""/""+particleString+""/_TempScatterPlots"").c_str()); _TEMP_scatterPlot_EtOverTruthVsEt_->Write(); _TEMP_scatterPlot_EtOverTruthVsE_->Write(); _TEMP_scatterPlot_EtOverTruthVsEta_->Write(); _TEMP_scatterPlot_EtOverTruthVsPhi_->Write(); _TEMP_scatterPlot_EOverTruthVsEt_->Write(); _TEMP_scatterPlot_EOverTruthVsE_->Write(); _TEMP_scatterPlot_EOverTruthVsEta_->Write(); _TEMP_scatterPlot_EOverTruthVsPhi_->Write(); _TEMP_scatterPlot_deltaEtaVsEt_->Write(); _TEMP_scatterPlot_deltaEtaVsE_->Write(); _TEMP_scatterPlot_deltaEtaVsEta_->Write(); _TEMP_scatterPlot_deltaEtaVsPhi_->Write(); _TEMP_scatterPlot_deltaPhiVsEt_->Write(); _TEMP_scatterPlot_deltaPhiVsE_->Write(); _TEMP_scatterPlot_deltaPhiVsEta_->Write(); _TEMP_scatterPlot_deltaPhiVsPhi_->Write(); rootFile_->cd(); } ",16374,True,3157.1265931645894,median "/****************************************************************************** * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Utility functions for OGR classes, including some related to * parsing well known text format vectors. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Frank Warmerdam * Copyright (c) 2008-2014, Even Rouault * * 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 ""cpl_port.h"" #include ""ogr_p.h"" #include #include #include #include #include #include #include #include #include #include #include ""cpl_conv.h"" #include ""cpl_error.h"" #include ""cpl_string.h"" #include ""cpl_time.h"" #include ""cpl_vsi.h"" #include ""gdal.h"" #include ""ogr_core.h"" #include ""ogr_geometry.h"" #include ""ogrsf_frmts.h"" CPL_CVSID(""$Id$"") // Returns whether a double fits within an int. // Unable to put this in cpl_port.h as include limit breaks grib. inline bool CPLIsDoubleAnInt(double d) { // Write it this way to detect NaN if ( !(d >= std::numeric_limits::min() && d <= std::numeric_limits::max()) ) { return false; } return d == static_cast(static_cast(d)); } namespace { // Remove trailing zeros except the last one. std::string removeTrailingZeros(std::string s) { auto pos = s.find('.'); if (pos == std::string::npos) return s; // Remove zeros at the end. We know this won't be npos because we // have a decimal point. auto nzpos = s.find_last_not_of('0'); s = s.substr(0, nzpos + 1); // Make sure there is one 0 after the decimal point. if (s.back() == '.') s += '0'; return s; } // Round a string representing a number by 1 in the least significant digit. std::string roundup(std::string s) { // Remove a negative sign if it exists to make processing // more straigtforward. bool negative(false); if (s[0] == '-') { negative = true; s = s.substr(1); } // Go from the back to the front. If we increment a digit other than // a '9', we're done. If we increment a '9', set it to a '0' and move // to the next (more significant) digit. If we get to the front of the // string, add a '1' to the front of the string. for (int pos = static_cast(s.size() - 1); pos >= 0; pos--) { if (s[pos] == '.') continue; s[pos]++; // Incrementing past 9 gets you a colon in ASCII. if (s[pos] != ':') break; else s[pos] = '0'; if (pos == 0) s = '1' + s; } if (negative) s = '-' + s; return s; } // This attempts to elimiate what is likely binary -> decimal representation // error or the result of low-order rounding with calculations. The result // may be more visually pleasing and takes up fewer places. std::string intelliround(std::string& s) { // If there is no decimal point, just return. auto dotPos = s.find("".""); if (dotPos == std::string::npos) return s; // Don't mess with exponential formatting. if (s.find_first_of(""eE"") != std::string::npos) return s; size_t iDotPos = static_cast(dotPos); size_t nCountBeforeDot = iDotPos - 1; if (s[0] == '-') nCountBeforeDot--; size_t i = s.size(); // If we don't have ten characters, don't do anything. if (i <= 10) return s; /* -------------------------------------------------------------------- */ /* Trim trailing 00000x's as they are likely roundoff error. */ /* -------------------------------------------------------------------- */ if (s[i-2] == '0' && s[i-3] == '0' && s[i-4] == '0' && s[i-5] == '0' && s[i-6] == '0') { s.resize(s.size() - 1); } // I don't understand this case exactly. It's like saying if the // value is large enough and there are sufficient sig digits before // a bunch of zeros, remove the zeros and any digits at the end that // may be nonzero. Perhaps if we can't exactly explain in words what // we're doing here, we shouldn't do it? Perhaps it should // be generalized? // The value ""12345.000000011"" invokes this case, if anyone // is interested. else if (iDotPos < i - 8 && (nCountBeforeDot >= 4 || s[i-3] == '0') && (nCountBeforeDot >= 5 || s[i-4] == '0') && (nCountBeforeDot >= 6 || s[i-5] == '0') && (nCountBeforeDot >= 7 || s[i-6] == '0') && (nCountBeforeDot >= 8 || s[i-7] == '0') && s[i-8] == '0' && s[i-9] == '0') { s.resize(s.size() - 8); } /* -------------------------------------------------------------------- */ /* Trim trailing 99999x's as they are likely roundoff error. */ /* -------------------------------------------------------------------- */ else if (s[i-2] == '9' && s[i-3] == '9' && s[i-4] == '9' && s[i-5] == '9' && s[i-6] == '9' ) { s.resize(i - 6); s = roundup(s); } else if (iDotPos < i - 9 && (nCountBeforeDot >= 4 || s[i-3] == '9') && (nCountBeforeDot >= 5 || s[i-4] == '9') && (nCountBeforeDot >= 6 || s[i-5] == '9') && (nCountBeforeDot >= 7 || s[i-6] == '9') && (nCountBeforeDot >= 8 || s[i-7] == '9') && s[i-8] == '9' && s[i-9] == '9') { s.resize(i - 9); s = roundup(s); } return s; } } // unnamed namespace /************************************************************************/ /* OGRFormatDouble() */ /************************************************************************/ void OGRFormatDouble( char *pszBuffer, int nBufferLen, double dfVal, char chDecimalSep, int nPrecision, char chConversionSpecifier ) { OGRWktOptions opts; opts.precision = nPrecision; opts.format = (chConversionSpecifier == 'g' || chConversionSpecifier == 'G') ? OGRWktFormat::G : OGRWktFormat::F; std::string s = OGRFormatDouble(dfVal, opts); if (chDecimalSep != '\\0' && chDecimalSep != '.') { auto pos = s.find('.'); if (pos != std::string::npos) s.replace(pos, 1, std::string(1, chDecimalSep)); } if (s.size() + 1 > static_cast(nBufferLen)) { CPLError(CE_Warning, CPLE_AppDefined, ""Truncated double value %s to "" ""%s."", s.data(), s.substr(0, nBufferLen - 1).data()); s.resize(nBufferLen - 1); } strcpy(pszBuffer, s.data()); } /// Simplified OGRFormatDouble that can be made to adhere to provided /// options. std::string OGRFormatDouble(double val, const OGRWktOptions& opts) { // So to have identical cross platform representation. if( CPLIsInf(val) ) return (val > 0) ? ""inf"" : ""-inf""; if( CPLIsNan(val) ) return ""nan""; std::ostringstream oss; oss.imbue(std::locale::classic()); // Make sure we output decimal points. bool l_round(opts.round); if (opts.format == OGRWktFormat::F || (opts.format == OGRWktFormat::Default && fabs(val) < 1)) oss << std::fixed; else { // Uppercase because OGC spec says capital 'E'. oss << std::uppercase; l_round = false; } oss << std::setprecision(opts.precision); oss << val; std::string sval = oss.str(); if (l_round) sval = intelliround(sval); return removeTrailingZeros(sval); } /************************************************************************/ /* OGRMakeWktCoordinate() */ /* */ /* Format a well known text coordinate, trying to keep the */ /* ASCII representation compact, but accurate. These rules */ /* will have to tighten up in the future. */ /* */ /* Currently a new point should require no more than 64 */ /* characters barring the X or Y value being extremely large. */ /************************************************************************/ void OGRMakeWktCoordinate( char *pszTarget, double x, double y, double z, int nDimension ) { std::string wkt = OGRMakeWktCoordinate(x, y, z, nDimension, OGRWktOptions()); memcpy(pszTarget, wkt.data(), wkt.size() + 1); } static bool isInteger(const std::string& s) { return s.find_first_not_of(""0123456789"") == std::string::npos; } std::string OGRMakeWktCoordinate(double x, double y, double z, int nDimension, OGRWktOptions opts) { std::string xval; std::string yval; // Why do we do this? Seems especially strange since we're ADDING // "".0"" onto values in the case below. The ""&&"" here also seems strange. if( opts.format == OGRWktFormat::Default && CPLIsDoubleAnInt(x) && CPLIsDoubleAnInt(y) ) { xval = std::to_string(static_cast(x)); yval = std::to_string(static_cast(y)); } else { xval = OGRFormatDouble(x, opts); //ABELL - Why do we do special formatting? if (isInteger(xval)) xval += "".0""; yval = OGRFormatDouble(y, opts); if (isInteger(yval)) yval += "".0""; } std::string wkt = xval + "" "" + yval; // Why do we always format Z with type G. if( nDimension == 3 ) { if(opts.format == OGRWktFormat::Default && CPLIsDoubleAnInt(z) ) wkt += "" "" + std::to_string(static_cast(z)); else { opts.format = OGRWktFormat::G; wkt += "" "" + OGRFormatDouble(z, opts); } } return wkt; } /************************************************************************/ /* OGRMakeWktCoordinateM() */ /* */ /* Format a well known text coordinate, trying to keep the */ /* ASCII representation compact, but accurate. These rules */ /* will have to tighten up in the future. */ /* */ /* Currently a new point should require no more than 64 */ /* characters barring the X or Y value being extremely large. */ /************************************************************************/ void OGRMakeWktCoordinateM( char *pszTarget, double x, double y, double z, double m, OGRBoolean hasZ, OGRBoolean hasM ) { std::string wkt = OGRMakeWktCoordinateM(x, y, z, m, hasZ, hasM, OGRWktOptions()); memcpy(pszTarget, wkt.data(), wkt.size() + 1); } std::string OGRMakeWktCoordinateM(double x, double y, double z, double m, OGRBoolean hasZ, OGRBoolean hasM, OGRWktOptions opts) { std::string xval, yval; if( opts.format == OGRWktFormat::Default && CPLIsDoubleAnInt(x) && CPLIsDoubleAnInt(y) ) { xval = std::to_string(static_cast(x)); yval = std::to_string(static_cast(y)); } else { xval = OGRFormatDouble(x, opts); if (isInteger(xval)) xval += "".0""; yval = OGRFormatDouble(y, opts); if (isInteger(yval)) yval += "".0""; } std::string wkt = xval + "" "" + yval; // For some reason we always format Z and M as G-type opts.format = OGRWktFormat::G; if( hasZ ) { /*if( opts.format == OGRWktFormat::Default && CPLIsDoubleAnInt(z) ) wkt += "" "" + std::to_string(static_cast(z)); else*/ wkt += "" "" + OGRFormatDouble(z, opts); } if( hasM ) { /*if( opts.format == OGRWktFormat::Default && CPLIsDoubleAnInt(m) ) wkt += "" "" + std::to_string(static_cast(m)); else*/ wkt += "" "" + OGRFormatDouble(m, opts); } return wkt; } /************************************************************************/ /* OGRWktReadToken() */ /* */ /* Read one token or delimiter and put into token buffer. Pre */ /* and post white space is swallowed. */ /************************************************************************/ const char *OGRWktReadToken( const char * pszInput, char * pszToken ) { if( pszInput == nullptr ) return nullptr; /* -------------------------------------------------------------------- */ /* Swallow pre-white space. */ /* -------------------------------------------------------------------- */ while( *pszInput == ' ' || *pszInput == '\\t' ) ++pszInput; /* -------------------------------------------------------------------- */ /* If this is a delimiter, read just one character. */ /* -------------------------------------------------------------------- */ if( *pszInput == '(' || *pszInput == ')' || *pszInput == ',' ) { pszToken[0] = *pszInput; pszToken[1] = '\\0'; ++pszInput; } /* -------------------------------------------------------------------- */ /* Or if it alpha numeric read till we reach non-alpha numeric */ /* text. */ /* -------------------------------------------------------------------- */ else { int iChar = 0; while( iChar < OGR_WKT_TOKEN_MAX-1 && ((*pszInput >= 'a' && *pszInput <= 'z') || (*pszInput >= 'A' && *pszInput <= 'Z') || (*pszInput >= '0' && *pszInput <= '9') || *pszInput == '.' || *pszInput == '+' || *pszInput == '-') ) { pszToken[iChar++] = *(pszInput++); } pszToken[iChar++] = '\\0'; } /* -------------------------------------------------------------------- */ /* Eat any trailing white space. */ /* -------------------------------------------------------------------- */ while( *pszInput == ' ' || *pszInput == '\\t' ) ++pszInput; return pszInput; } /************************************************************************/ /* OGRWktReadPoints() */ /* */ /* Read a point string. The point list must be contained in */ /* brackets and each point pair separated by a comma. */ /************************************************************************/ const char * OGRWktReadPoints( const char * pszInput, OGRRawPoint ** ppaoPoints, double **ppadfZ, int * pnMaxPoints, int * pnPointsRead ) { const char *pszOrigInput = pszInput; *pnPointsRead = 0; if( pszInput == nullptr ) return nullptr; /* -------------------------------------------------------------------- */ /* Eat any leading white space. */ /* -------------------------------------------------------------------- */ while( *pszInput == ' ' || *pszInput == '\\t' ) ++pszInput; /* -------------------------------------------------------------------- */ /* If this isn't an opening bracket then we have a problem. */ /* -------------------------------------------------------------------- */ if( *pszInput != '(' ) { CPLDebug( ""OGR"", ""Expected '(', but got %s in OGRWktReadPoints()."", pszInput ); return pszInput; } ++pszInput; /* ==================================================================== */ /* This loop reads a single point. It will continue till we */ /* run out of well formed points, or a closing bracket is */ /* encountered. */ /* ==================================================================== */ char szDelim[OGR_WKT_TOKEN_MAX] = {}; do { /* -------------------------------------------------------------------- */ /* Read the X and Y values, verify they are numeric. */ /* -------------------------------------------------------------------- */ char szTokenX[OGR_WKT_TOKEN_MAX] = {}; char szTokenY[OGR_WKT_TOKEN_MAX] = {}; pszInput = OGRWktReadToken( pszInput, szTokenX ); pszInput = OGRWktReadToken( pszInput, szTokenY ); if( (!isdigit(szTokenX[0]) && szTokenX[0] != '-' && szTokenX[0] != '.' ) || (!isdigit(szTokenY[0]) && szTokenY[0] != '-' && szTokenY[0] != '.') ) return nullptr; /* -------------------------------------------------------------------- */ /* Do we need to grow the point list to hold this point? */ /* -------------------------------------------------------------------- */ if( *pnPointsRead == *pnMaxPoints ) { *pnMaxPoints = *pnMaxPoints * 2 + 10; *ppaoPoints = static_cast( CPLRealloc(*ppaoPoints, sizeof(OGRRawPoint) * *pnMaxPoints) ); if( *ppadfZ != nullptr ) { *ppadfZ = static_cast( CPLRealloc(*ppadfZ, sizeof(double) * *pnMaxPoints) ); } } /* -------------------------------------------------------------------- */ /* Add point to list. */ /* -------------------------------------------------------------------- */ (*ppaoPoints)[*pnPointsRead].x = CPLAtof(szTokenX); (*ppaoPoints)[*pnPointsRead].y = CPLAtof(szTokenY); /* -------------------------------------------------------------------- */ /* Do we have a Z coordinate? */ /* -------------------------------------------------------------------- */ pszInput = OGRWktReadToken( pszInput, szDelim ); if( isdigit(szDelim[0]) || szDelim[0] == '-' || szDelim[0] == '.' ) { if( *ppadfZ == nullptr ) { *ppadfZ = static_cast( CPLCalloc(sizeof(double), *pnMaxPoints) ); } (*ppadfZ)[*pnPointsRead] = CPLAtof(szDelim); pszInput = OGRWktReadToken( pszInput, szDelim ); } else if( *ppadfZ != nullptr ) { (*ppadfZ)[*pnPointsRead] = 0.0; } ++(*pnPointsRead); /* -------------------------------------------------------------------- */ /* Do we have a M coordinate? */ /* If we do, just skip it. */ /* -------------------------------------------------------------------- */ if( isdigit(szDelim[0]) || szDelim[0] == '-' || szDelim[0] == '.' ) { pszInput = OGRWktReadToken( pszInput, szDelim ); } /* -------------------------------------------------------------------- */ /* Read next delimiter ... it should be a comma if there are */ /* more points. */ /* -------------------------------------------------------------------- */ if( szDelim[0] != ')' && szDelim[0] != ',' ) { CPLDebug( ""OGR"", ""Corrupt input in OGRWktReadPoints(). "" ""Got `%s' when expecting `,' or `)', near `%s' in %s."", szDelim, pszInput, pszOrigInput ); return nullptr; } } while( szDelim[0] == ',' ); return pszInput; } /************************************************************************/ /* OGRWktReadPointsM() */ /* */ /* Read a point string. The point list must be contained in */ /* brackets and each point pair separated by a comma. */ /************************************************************************/ const char * OGRWktReadPointsM( const char * pszInput, OGRRawPoint ** ppaoPoints, double **ppadfZ, double **ppadfM, int * flags, int * pnMaxPoints, int * pnPointsRead ) { const char *pszOrigInput = pszInput; const bool bNoFlags = !(*flags & OGRGeometry::OGR_G_3D) && !(*flags & OGRGeometry::OGR_G_MEASURED); *pnPointsRead = 0; if( pszInput == nullptr ) return nullptr; /* -------------------------------------------------------------------- */ /* Eat any leading white space. */ /* -------------------------------------------------------------------- */ while( *pszInput == ' ' || *pszInput == '\\t' ) ++pszInput; /* -------------------------------------------------------------------- */ /* If this isn't an opening bracket then we have a problem. */ /* -------------------------------------------------------------------- */ if( *pszInput != '(' ) { CPLDebug( ""OGR"", ""Expected '(', but got %s in OGRWktReadPointsM()."", pszInput ); return pszInput; } ++pszInput; /* ==================================================================== */ /* This loop reads a single point. It will continue till we */ /* run out of well formed points, or a closing bracket is */ /* encountered. */ /* ==================================================================== */ char szDelim[OGR_WKT_TOKEN_MAX] = {}; do { /* -------------------------------------------------------------------- */ /* Read the X and Y values, verify they are numeric. */ /* -------------------------------------------------------------------- */ char szTokenX[OGR_WKT_TOKEN_MAX] = {}; char szTokenY[OGR_WKT_TOKEN_MAX] = {}; pszInput = OGRWktReadToken( pszInput, szTokenX ); pszInput = OGRWktReadToken( pszInput, szTokenY ); if( (!isdigit(szTokenX[0]) && szTokenX[0] != '-' && szTokenX[0] != '.' ) || (!isdigit(szTokenY[0]) && szTokenY[0] != '-' && szTokenY[0] != '.') ) return nullptr; /* -------------------------------------------------------------------- */ /* Do we need to grow the point list to hold this point? */ /* -------------------------------------------------------------------- */ if( *pnPointsRead == *pnMaxPoints ) { *pnMaxPoints = *pnMaxPoints * 2 + 10; *ppaoPoints = static_cast( CPLRealloc(*ppaoPoints, sizeof(OGRRawPoint) * *pnMaxPoints) ); if( *ppadfZ != nullptr ) { *ppadfZ = static_cast( CPLRealloc(*ppadfZ, sizeof(double) * *pnMaxPoints) ); } if( *ppadfM != nullptr ) { *ppadfM = static_cast( CPLRealloc(*ppadfM, sizeof(double) * *pnMaxPoints) ); } } /* -------------------------------------------------------------------- */ /* Add point to list. */ /* -------------------------------------------------------------------- */ (*ppaoPoints)[*pnPointsRead].x = CPLAtof(szTokenX); (*ppaoPoints)[*pnPointsRead].y = CPLAtof(szTokenY); /* -------------------------------------------------------------------- */ /* Read the next token. */ /* -------------------------------------------------------------------- */ pszInput = OGRWktReadToken( pszInput, szDelim ); /* -------------------------------------------------------------------- */ /* If there are unexpectedly more coordinates, they are Z. */ /* -------------------------------------------------------------------- */ if( !(*flags & OGRGeometry::OGR_G_3D) && !(*flags & OGRGeometry::OGR_G_MEASURED) && (isdigit(szDelim[0]) || szDelim[0] == '-' || szDelim[0] == '.' )) { *flags |= OGRGeometry::OGR_G_3D; } /* -------------------------------------------------------------------- */ /* Get Z if flag says so. */ /* Zero out possible remains from earlier strings. */ /* -------------------------------------------------------------------- */ if( *flags & OGRGeometry::OGR_G_3D ) { if( *ppadfZ == nullptr ) { *ppadfZ = static_cast( CPLCalloc(sizeof(double), *pnMaxPoints) ); } if( isdigit(szDelim[0]) || szDelim[0] == '-' || szDelim[0] == '.' ) { (*ppadfZ)[*pnPointsRead] = CPLAtof(szDelim); pszInput = OGRWktReadToken( pszInput, szDelim ); } else { (*ppadfZ)[*pnPointsRead] = 0.0; } } else if( *ppadfZ != nullptr ) { (*ppadfZ)[*pnPointsRead] = 0.0; } /* -------------------------------------------------------------------- */ /* If there are unexpectedly even more coordinates, */ /* they are discarded unless there were no flags originally. */ /* This is for backwards compatibility. Should this be an error? */ /* -------------------------------------------------------------------- */ if( !(*flags & OGRGeometry::OGR_G_MEASURED) && (isdigit(szDelim[0]) || szDelim[0] == '-' || szDelim[0] == '.' ) ) { if( bNoFlags ) { *flags |= OGRGeometry::OGR_G_MEASURED; } else { pszInput = OGRWktReadToken( pszInput, szDelim ); } } /* -------------------------------------------------------------------- */ /* Get M if flag says so. */ /* Zero out possible remains from earlier strings. */ /* -------------------------------------------------------------------- */ if( *flags & OGRGeometry::OGR_G_MEASURED ) { if( *ppadfM == nullptr ) { *ppadfM = static_cast( CPLCalloc(sizeof(double), *pnMaxPoints) ); } if( isdigit(szDelim[0]) || szDelim[0] == '-' || szDelim[0] == '.' ) { (*ppadfM)[*pnPointsRead] = CPLAtof(szDelim); pszInput = OGRWktReadToken( pszInput, szDelim ); } else { (*ppadfM)[*pnPointsRead] = 0.0; } } else if( *ppadfM != nullptr ) { (*ppadfM)[*pnPointsRead] = 0.0; } /* -------------------------------------------------------------------- */ /* If there are still more coordinates and we do not have Z */ /* then we have a case of flags == M and four coordinates. */ /* This is allowed in BNF. */ /* -------------------------------------------------------------------- */ if( !(*flags & OGRGeometry::OGR_G_3D) && (isdigit(szDelim[0]) || szDelim[0] == '-' || szDelim[0] == '.') ) { *flags |= OGRGeometry::OGR_G_3D; if( *ppadfZ == nullptr ) { *ppadfZ = static_cast( CPLCalloc(sizeof(double), *pnMaxPoints) ); } (*ppadfZ)[*pnPointsRead] = (*ppadfM)[*pnPointsRead]; (*ppadfM)[*pnPointsRead] = CPLAtof(szDelim); pszInput = OGRWktReadToken( pszInput, szDelim ); } /* -------------------------------------------------------------------- */ /* Increase points index. */ /* -------------------------------------------------------------------- */ ++(*pnPointsRead); /* -------------------------------------------------------------------- */ /* The next delimiter should be a comma or an ending bracket. */ /* -------------------------------------------------------------------- */ if( szDelim[0] != ')' && szDelim[0] != ',' ) { CPLDebug( ""OGR"", ""Corrupt input in OGRWktReadPointsM() "" ""Got `%s' when expecting `,' or `)', near `%s' in %s."", szDelim, pszInput, pszOrigInput ); return nullptr; } } while( szDelim[0] == ',' ); return pszInput; } /************************************************************************/ /* OGRMalloc() */ /* */ /* Cover for CPLMalloc() */ /************************************************************************/ void *OGRMalloc( size_t size ) { return CPLMalloc( size ); } /************************************************************************/ /* OGRCalloc() */ /* */ /* Cover for CPLCalloc() */ /************************************************************************/ void *OGRCalloc( size_t count, size_t size ) { return CPLCalloc( count, size ); } /************************************************************************/ /* OGRRealloc() */ /* */ /* Cover for CPLRealloc() */ /************************************************************************/ void *OGRRealloc( void * pOld, size_t size ) { return CPLRealloc( pOld, size ); } /************************************************************************/ /* OGRFree() */ /* */ /* Cover for CPLFree(). */ /************************************************************************/ void OGRFree( void * pMemory ) { CPLFree( pMemory ); } /** * \\fn OGRGeneralCmdLineProcessor(int, char***, int) * General utility option processing. * * This function is intended to provide a variety of generic commandline * options for all OGR commandline utilities. It takes care of the following * commandline options: * * --version: report version of GDAL in use. * --license: report GDAL license info. * --format [format]: report details of one format driver. * --formats: report all format drivers configured. * --optfile filename: expand an option file into the argument list. * --config key value: set system configuration option. * --debug [on/off/value]: set debug level. * --pause: Pause for user input (allows time to attach debugger) * --locale [locale]: Install a locale using setlocale() (debugging) * --help-general: report detailed help on general options. * * The argument array is replaced ""in place"" and should be freed with * CSLDestroy() when no longer needed. The typical usage looks something * like the following. Note that the formats should be registered so that * the --formats option will work properly. * * int main( int argc, char ** argv ) * { * OGRRegisterAll(); * * argc = OGRGeneralCmdLineProcessor( argc, &argv, 0 ); * if( argc < 1 ) * exit( -argc ); * * @param nArgc number of values in the argument list. * @param ppapszArgv pointer to the argument list array (will be updated in * place). * @param nOptions unused. * * @return updated nArgc argument count. Return of 0 requests terminate * without error, return of -1 requests exit with error code. */ int OGRGeneralCmdLineProcessor( int nArgc, char ***ppapszArgv, CPL_UNUSED int nOptions ) { return GDALGeneralCmdLineProcessor( nArgc, ppapszArgv, GDAL_OF_VECTOR ); } /************************************************************************/ /* OGRParseDate() */ /* */ /* Parse a variety of text date formats into an OGRField. */ /************************************************************************/ /** * Parse date string. * * This function attempts to parse a date string in a variety of formats * into the OGRField.Date format suitable for use with OGR. Generally * speaking this function is expecting values like: * * YYYY-MM-DD HH:MM:SS[.sss]+nn * or YYYY-MM-DDTHH:MM:SS[.sss]Z (ISO 8601 format) * or YYYY-MM-DDZ * * The seconds may also have a decimal portion (which is ignored). And * just dates (YYYY-MM-DD) or just times (HH:MM:SS[.sss]) are also supported. * The date may also be in YYYY/MM/DD format. If the year is less than 100 * and greater than 30 a ""1900"" century value will be set. If it is less than * 30 and greater than -1 then a ""2000"" century value will be set. In * the future this function may be generalized, and additional control * provided through nOptions, but an nOptions value of ""0"" should always do * a reasonable default form of processing. * * The value of psField will be indeterminate if the function fails (returns * FALSE). * * @param pszInput the input date string. * @param psField the OGRField that will be updated with the parsed result. * @param nOptions parsing options, for now always 0. * * @return TRUE if apparently successful or FALSE on failure. */ int OGRParseDate( const char *pszInput, OGRField *psField, CPL_UNUSED int nOptions ) { psField->Date.Year = 0; psField->Date.Month = 0; psField->Date.Day = 0; psField->Date.Hour = 0; psField->Date.Minute = 0; psField->Date.Second = 0; psField->Date.TZFlag = 0; psField->Date.Reserved = 0; /* -------------------------------------------------------------------- */ /* Do we have a date? */ /* -------------------------------------------------------------------- */ while( *pszInput == ' ' ) ++pszInput; bool bGotSomething = false; if( strstr(pszInput,""-"") != nullptr || strstr(pszInput,""/"") != nullptr ) { if( !(*pszInput == '-' || *pszInput == '+' || (*pszInput >= '0' && *pszInput <= '9')) ) return FALSE; int nYear = atoi(pszInput); if (nYear > std::numeric_limits::max() || nYear < std::numeric_limits::min() ) { CPLError(CE_Failure, CPLE_NotSupported, ""Years < %d or > %d are not supported"", std::numeric_limits::min(), std::numeric_limits::max()); return FALSE; } psField->Date.Year = static_cast(nYear); if( (pszInput[1] == '-' || pszInput[1] == '/' ) || (pszInput[1] != '\\0' && (pszInput[2] == '-' || pszInput[2] == '/' )) ) { if( psField->Date.Year < 100 && psField->Date.Year >= 30 ) psField->Date.Year += 1900; else if( psField->Date.Year < 30 && psField->Date.Year >= 0 ) psField->Date.Year += 2000; } if( *pszInput == '-' ) ++pszInput; while( *pszInput >= '0' && *pszInput <= '9' ) ++pszInput; if( *pszInput != '-' && *pszInput != '/' ) return FALSE; else ++pszInput; const int nMonth = atoi(pszInput); if( nMonth <= 0 || nMonth > 12 ) return FALSE; psField->Date.Month = static_cast(nMonth); while( *pszInput >= '0' && *pszInput <= '9' ) ++pszInput; if( *pszInput != '-' && *pszInput != '/' ) return FALSE; else ++pszInput; const int nDay = atoi(pszInput); if( nDay <= 0 || nDay > 31 ) return FALSE; psField->Date.Day = static_cast(nDay); while( *pszInput >= '0' && *pszInput <= '9' ) ++pszInput; if( *pszInput == '\\0' ) return TRUE; bGotSomething = true; // If ISO 8601 format. if( *pszInput == 'T' ) ++pszInput; else if( *pszInput == 'Z' ) return TRUE; else if( *pszInput != ' ' ) return FALSE; } /* -------------------------------------------------------------------- */ /* Do we have a time? */ /* -------------------------------------------------------------------- */ while( *pszInput == ' ' ) ++pszInput; if( strstr(pszInput, "":"") != nullptr ) { if( !(*pszInput >= '0' && *pszInput <= '9') ) return FALSE; const int nHour = atoi(pszInput); if( nHour < 0 || nHour > 23 ) return FALSE; psField->Date.Hour = static_cast(nHour); while( *pszInput >= '0' && *pszInput <= '9' ) ++pszInput; if( *pszInput != ':' ) return FALSE; else ++pszInput; if( !(*pszInput >= '0' && *pszInput <= '9') ) return FALSE; const int nMinute = atoi(pszInput); if( nMinute < 0 || nMinute > 59 ) return FALSE; psField->Date.Minute = static_cast(nMinute); while( *pszInput >= '0' && *pszInput <= '9' ) ++pszInput; if( *pszInput == ':' ) { ++pszInput; if( !(*pszInput >= '0' && *pszInput <= '9') ) return FALSE; const double dfSeconds = CPLAtof(pszInput); // We accept second=60 for leap seconds if (dfSeconds > 60.0 || dfSeconds < 0.0) return FALSE; psField->Date.Second = static_cast(dfSeconds); while( (*pszInput >= '0' && *pszInput <= '9') || *pszInput == '.' ) { ++pszInput; } // If ISO 8601 format. if( *pszInput == 'Z' ) { psField->Date.TZFlag = 100; } } bGotSomething = true; } // No date or time! if( !bGotSomething ) return FALSE; /* -------------------------------------------------------------------- */ /* Do we have a timezone? */ /* -------------------------------------------------------------------- */ while( *pszInput == ' ' ) ++pszInput; if( *pszInput == '-' || *pszInput == '+' ) { // +HH integral offset if( strlen(pszInput) <= 3 ) { psField->Date.TZFlag = static_cast(100 + atoi(pszInput) * 4); } else if( pszInput[3] == ':' // +HH:MM offset && atoi(pszInput + 4) % 15 == 0 ) { psField->Date.TZFlag = static_cast(100 + atoi(pszInput + 1) * 4 + (atoi(pszInput + 4) / 15)); if( pszInput[0] == '-' ) psField->Date.TZFlag = -1 * (psField->Date.TZFlag - 100) + 100; } else if( isdigit(pszInput[3]) && isdigit(pszInput[4]) // +HHMM offset && atoi(pszInput + 3) % 15 == 0 ) { psField->Date.TZFlag = static_cast(100 + static_cast(CPLScanLong(pszInput + 1, 2)) * 4 + (atoi(pszInput + 3) / 15)); if( pszInput[0] == '-' ) psField->Date.TZFlag = -1 * (psField->Date.TZFlag - 100) + 100; } else if( isdigit(pszInput[3]) && pszInput[4] == '\\0' // +HMM offset && atoi(pszInput + 2) % 15 == 0 ) { psField->Date.TZFlag = static_cast(100 + static_cast(CPLScanLong(pszInput + 1, 1)) * 4 + (atoi(pszInput + 2) / 15)); if( pszInput[0] == '-' ) psField->Date.TZFlag = -1 * (psField->Date.TZFlag - 100) + 100; } // otherwise ignore any timezone info. } return TRUE; } /************************************************************************/ /* OGRParseXMLDateTime() */ /************************************************************************/ int OGRParseXMLDateTime( const char* pszXMLDateTime, OGRField* psField) { int year = 0; int month = 0; int day = 0; int hour = 0; int minute = 0; int TZHour = 0; int TZMinute = 0; float second = 0; char c = '\\0'; int TZ = 0; bool bRet = false; // Date is expressed as a UTC date. if( sscanf(pszXMLDateTime, ""%04d-%02d-%02dT%02d:%02d:%f%c"", &year, &month, &day, &hour, &minute, &second, &c) == 7 && c == 'Z' ) { TZ = 100; bRet = true; } // Date is expressed as a UTC date, with a timezone. else if( sscanf(pszXMLDateTime, ""%04d-%02d-%02dT%02d:%02d:%f%c%02d:%02d"", &year, &month, &day, &hour, &minute, &second, &c, &TZHour, &TZMinute) == 9 && (c == '+' || c == '-') ) { TZ = 100 + ((c == '+') ? 1 : -1) * ((TZHour * 60 + TZMinute) / 15); bRet = true; } // Date is expressed into an unknown timezone. else if( sscanf(pszXMLDateTime, ""%04d-%02d-%02dT%02d:%02d:%f"", &year, &month, &day, &hour, &minute, &second) == 6 ) { TZ = 0; bRet = true; } // Date is expressed as a UTC date with only year:month:day. else if( sscanf(pszXMLDateTime, ""%04d-%02d-%02d"", &year, &month, &day) == 3 ) { TZ = 0; bRet = true; } // Date is expressed as a UTC date with only year:month. else if( sscanf(pszXMLDateTime, ""%04d-%02d"", &year, &month) == 2 ) { TZ = 0; bRet = true; day = 1; } if( !bRet ) return FALSE; psField->Date.Year = static_cast(year); psField->Date.Month = static_cast(month); psField->Date.Day = static_cast(day); psField->Date.Hour = static_cast(hour); psField->Date.Minute = static_cast(minute); psField->Date.Second = second; psField->Date.TZFlag = static_cast(TZ); psField->Date.Reserved = 0; return TRUE; } /************************************************************************/ /* OGRParseRFC822DateTime() */ /************************************************************************/ static const char* const aszMonthStr[] = { ""Jan"", ""Feb"", ""Mar"", ""Apr"", ""May"", ""Jun"", ""Jul"", ""Aug"", ""Sep"", ""Oct"", ""Nov"", ""Dec"" }; int OGRParseRFC822DateTime( const char* pszRFC822DateTime, OGRField* psField ) { int nYear, nMonth, nDay, nHour, nMinute, nSecond, nTZFlag; if( !CPLParseRFC822DateTime( pszRFC822DateTime, &nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond, &nTZFlag, nullptr ) ) { return false; } psField->Date.Year = static_cast(nYear); psField->Date.Month = static_cast(nMonth); psField->Date.Day = static_cast(nDay); psField->Date.Hour = static_cast(nHour); psField->Date.Minute = static_cast(nMinute); psField->Date.Second = (nSecond < 0) ? 0.0f : static_cast(nSecond); psField->Date.TZFlag = static_cast(nTZFlag); psField->Date.Reserved = 0; return true; } /** * Returns the day of the week in Gregorian calendar * * @param day : day of the month, between 1 and 31 * @param month : month of the year, between 1 (Jan) and 12 (Dec) * @param year : year * @return day of the week : 0 for Monday, ... 6 for Sunday */ int OGRGetDayOfWeek( int day, int month, int year ) { // Reference: Zeller's congruence. const int q = day; int m = month; if( month >=3 ) { // m = month; } else { m = month + 12; year--; } const int K = year % 100; const int J = year / 100; const int h = ( q + (((m+1)*26)/10) + K + K/4 + J/4 + 5 * J) % 7; return ( h + 5 ) % 7; } /************************************************************************/ /* OGRGetRFC822DateTime() */ /************************************************************************/ char* OGRGetRFC822DateTime( const OGRField* psField ) { char* pszTZ = nullptr; const char* const aszDayOfWeek[] = { ""Mon"", ""Tue"", ""Wed"", ""Thu"", ""Fri"", ""Sat"", ""Sun"" }; int dayofweek = OGRGetDayOfWeek(psField->Date.Day, psField->Date.Month, psField->Date.Year); int month = psField->Date.Month; if( month < 1 || month > 12 ) month = 1; int TZFlag = psField->Date.TZFlag; if( TZFlag == 0 || TZFlag == 100 ) { pszTZ = CPLStrdup(""GMT""); } else { int TZOffset = std::abs(TZFlag - 100) * 15; int TZHour = TZOffset / 60; int TZMinute = TZOffset - TZHour * 60; pszTZ = CPLStrdup(CPLSPrintf(""%c%02d%02d"", TZFlag > 100 ? '+' : '-', TZHour, TZMinute)); } char* pszRet = CPLStrdup(CPLSPrintf( ""%s, %02d %s %04d %02d:%02d:%02d %s"", aszDayOfWeek[dayofweek], psField->Date.Day, aszMonthStr[month - 1], psField->Date.Year, psField->Date.Hour, psField->Date.Minute, static_cast(psField->Date.Second), pszTZ)); CPLFree(pszTZ); return pszRet; } /************************************************************************/ /* OGRGetXMLDateTime() */ /************************************************************************/ char* OGRGetXMLDateTime(const OGRField* psField) { const GInt16 year = psField->Date.Year; const GByte month = psField->Date.Month; const GByte day = psField->Date.Day; const GByte hour = psField->Date.Hour; const GByte minute = psField->Date.Minute; const float second = psField->Date.Second; const GByte TZFlag = psField->Date.TZFlag; char szTimeZone[7]; char* pszRet = nullptr; switch( TZFlag ) { case 0: // Unknown time zone case 1: // Local time zone (not specified) szTimeZone[0] = 0; break; case 100: // GMT szTimeZone[0] = 'Z'; szTimeZone[1] = 0; break; default: // Offset (in quarter-hour units) from GMT const int TZOffset = std::abs(TZFlag - 100) * 15; const int TZHour = TZOffset / 60; const int TZMinute = TZOffset % 60; snprintf(szTimeZone, 7, ""%c%02d:%02d"", (TZFlag > 100) ? '+' : '-', TZHour, TZMinute); } if( OGR_GET_MS(second) ) pszRet = CPLStrdup(CPLSPrintf( ""%04d-%02u-%02uT%02u:%02u:%06.3f%s"", year, month, day, hour, minute, second, szTimeZone)); else pszRet = CPLStrdup(CPLSPrintf( ""%04d-%02u-%02uT%02u:%02u:%02u%s"", year, month, day, hour, minute, static_cast(second), szTimeZone)); return pszRet; } /************************************************************************/ /* OGRGetXML_UTF8_EscapedString() */ /************************************************************************/ char* OGRGetXML_UTF8_EscapedString(const char* pszString) { char *pszEscaped = nullptr; if( !CPLIsUTF8(pszString, -1) && CPLTestBool(CPLGetConfigOption(""OGR_FORCE_ASCII"", ""YES"")) ) { static bool bFirstTime = true; if( bFirstTime ) { bFirstTime = false; CPLError(CE_Warning, CPLE_AppDefined, ""%s is not a valid UTF-8 string. Forcing it to ASCII. "" ""If you still want the original string and change the XML "" ""file encoding afterwards, you can define "" ""OGR_FORCE_ASCII=NO as configuration option. "" ""This warning won't be issued anymore"", pszString); } else { CPLDebug(""OGR"", ""%s is not a valid UTF-8 string. Forcing it to ASCII"", pszString); } char* pszTemp = CPLForceToASCII(pszString, -1, '?'); pszEscaped = CPLEscapeString( pszTemp, -1, CPLES_XML ); CPLFree(pszTemp); } else pszEscaped = CPLEscapeString( pszString, -1, CPLES_XML ); return pszEscaped; } /************************************************************************/ /* OGRCompareDate() */ /************************************************************************/ int OGRCompareDate( const OGRField *psFirstTuple, const OGRField *psSecondTuple ) { // TODO: We ignore TZFlag. if( psFirstTuple->Date.Year < psSecondTuple->Date.Year ) return -1; else if( psFirstTuple->Date.Year > psSecondTuple->Date.Year ) return 1; if( psFirstTuple->Date.Month < psSecondTuple->Date.Month ) return -1; else if( psFirstTuple->Date.Month > psSecondTuple->Date.Month ) return 1; if( psFirstTuple->Date.Day < psSecondTuple->Date.Day ) return -1; else if( psFirstTuple->Date.Day > psSecondTuple->Date.Day ) return 1; if( psFirstTuple->Date.Hour < psSecondTuple->Date.Hour ) return -1; else if( psFirstTuple->Date.Hour > psSecondTuple->Date.Hour ) return 1; if( psFirstTuple->Date.Minute < psSecondTuple->Date.Minute ) return -1; else if( psFirstTuple->Date.Minute > psSecondTuple->Date.Minute ) return 1; if( psFirstTuple->Date.Second < psSecondTuple->Date.Second ) return -1; else if( psFirstTuple->Date.Second > psSecondTuple->Date.Second ) return 1; return 0; } /************************************************************************/ /* OGRFastAtof() */ /************************************************************************/ // On Windows, CPLAtof() is very slow if the number is followed by other long // content. Just extract the number into a short string before calling // CPLAtof() on it. static double OGRCallAtofOnShortString(const char* pszStr) { const char* p = pszStr; while( *p == ' ' || *p == '\\t' ) ++p; char szTemp[128] = {}; int nCounter = 0; while( *p == '+' || *p == '-' || (*p >= '0' && *p <= '9') || *p == '.' || (*p == 'e' || *p == 'E' || *p == 'd' || *p == 'D') ) { szTemp[nCounter++] = *(p++); if( nCounter == 127 ) return CPLAtof(pszStr); } szTemp[nCounter] = '\\0'; return CPLAtof(szTemp); } /** Same contract as CPLAtof, except than it doesn't always call the * system CPLAtof() that may be slow on some platforms. For simple but * common strings, it'll use a faster implementation (up to 20x faster * than CPLAtof() on MS runtime libraries) that has no guaranty to return * exactly the same floating point number. */ double OGRFastAtof(const char* pszStr) { double dfVal = 0; double dfSign = 1.0; const char* p = pszStr; constexpr double adfTenPower[] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22, 1e23, 1e24, 1e25, 1e26, 1e27, 1e28, 1e29, 1e30, 1e31 }; while( *p == ' ' || *p == '\\t' ) ++p; if( *p == '+' ) ++p; else if( *p == '-' ) { dfSign = -1.0; ++p; } while( true ) { if( *p >= '0' && *p <= '9' ) { dfVal = dfVal * 10.0 + (*p - '0'); ++p; } else if( *p == '.' ) { ++p; break; } else if( *p == 'e' || *p == 'E' || *p == 'd' || *p == 'D' ) return OGRCallAtofOnShortString(pszStr); else return dfSign * dfVal; } unsigned int countFractionnal = 0; while( true ) { if( *p >= '0' && *p <= '9' ) { dfVal = dfVal * 10.0 + (*p - '0'); ++countFractionnal; ++p; } else if( *p == 'e' || *p == 'E' || *p == 'd' || *p == 'D' ) return OGRCallAtofOnShortString(pszStr); else { if( countFractionnal < CPL_ARRAYSIZE(adfTenPower) ) return dfSign * (dfVal / adfTenPower[countFractionnal]); else return OGRCallAtofOnShortString(pszStr); } } } /** * Check that panPermutation is a permutation of [0, nSize-1]. * @param panPermutation an array of nSize elements. * @param nSize size of the array. * @return OGRERR_NONE if panPermutation is a permutation of [0, nSize - 1]. * @since OGR 1.9.0 */ OGRErr OGRCheckPermutation( int* panPermutation, int nSize ) { OGRErr eErr = OGRERR_NONE; int* panCheck = static_cast(CPLCalloc(nSize, sizeof(int))); for( int i = 0; i < nSize; ++i ) { if( panPermutation[i] < 0 || panPermutation[i] >= nSize ) { CPLError(CE_Failure, CPLE_IllegalArg, ""Bad value for element %d"", i); eErr = OGRERR_FAILURE; break; } if( panCheck[panPermutation[i]] != 0 ) { CPLError(CE_Failure, CPLE_IllegalArg, ""Array is not a permutation of [0,%d]"", nSize - 1); eErr = OGRERR_FAILURE; break; } panCheck[panPermutation[i]] = 1; } CPLFree(panCheck); return eErr; } OGRErr OGRReadWKBGeometryType( const unsigned char * pabyData, OGRwkbVariant eWkbVariant, OGRwkbGeometryType *peGeometryType ) { if( !peGeometryType ) return OGRERR_FAILURE; /* -------------------------------------------------------------------- */ /* Get the byte order byte. */ /* -------------------------------------------------------------------- */ int nByteOrder = DB2_V72_FIX_BYTE_ORDER(*pabyData); if( !( nByteOrder == wkbXDR || nByteOrder == wkbNDR ) ) return OGRERR_CORRUPT_DATA; OGRwkbByteOrder eByteOrder = static_cast(nByteOrder); /* -------------------------------------------------------------------- */ /* Get the geometry type. */ /* -------------------------------------------------------------------- */ bool bIs3D = false; bool bIsMeasured = false; int iRawType = 0; memcpy(&iRawType, pabyData + 1, 4); if( OGR_SWAP(eByteOrder)) { CPL_SWAP32PTR(&iRawType); } // Test for M bit in PostGIS WKB, see ogrgeometry.cpp:4956. if( 0x40000000 & iRawType ) { iRawType &= ~0x40000000; bIsMeasured = true; } // Old-style OGC z-bit is flipped? Tests also Z bit in PostGIS WKB. if( wkb25DBitInternalUse & iRawType ) { // Clean off top 3 bytes. iRawType &= 0x000000FF; bIs3D = true; } // ISO SQL/MM Part3 draft -> Deprecated. // See http://jtc1sc32.org/doc/N1101-1150/32N1107-WD13249-3--spatial.pdf if( iRawType == 1000001 ) iRawType = wkbCircularString; else if( iRawType == 1000002 ) iRawType = wkbCompoundCurve; else if( iRawType == 1000003 ) iRawType = wkbCurvePolygon; else if( iRawType == 1000004 ) iRawType = wkbMultiCurve; else if( iRawType == 1000005 ) iRawType = wkbMultiSurface; else if( iRawType == 2000001 ) iRawType = wkbPointZM; else if( iRawType == 2000002 ) iRawType = wkbLineStringZM; else if( iRawType == 2000003 ) iRawType = wkbCircularStringZM; else if( iRawType == 2000004 ) iRawType = wkbCompoundCurveZM; else if( iRawType == 2000005 ) iRawType = wkbPolygonZM; else if( iRawType == 2000006 ) iRawType = wkbCurvePolygonZM; else if( iRawType == 2000007 ) iRawType = wkbMultiPointZM; else if( iRawType == 2000008 ) iRawType = wkbMultiCurveZM; else if( iRawType == 2000009 ) iRawType = wkbMultiLineStringZM; else if( iRawType == 2000010 ) iRawType = wkbMultiSurfaceZM; else if( iRawType == 2000011 ) iRawType = wkbMultiPolygonZM; else if( iRawType == 2000012 ) iRawType = wkbGeometryCollectionZM; else if( iRawType == 3000001 ) iRawType = wkbPoint25D; else if( iRawType == 3000002 ) iRawType = wkbLineString25D; else if( iRawType == 3000003 ) iRawType = wkbCircularStringZ; else if( iRawType == 3000004 ) iRawType = wkbCompoundCurveZ; else if( iRawType == 3000005 ) iRawType = wkbPolygon25D; else if( iRawType == 3000006 ) iRawType = wkbCurvePolygonZ; else if( iRawType == 3000007 ) iRawType = wkbMultiPoint25D; else if( iRawType == 3000008 ) iRawType = wkbMultiCurveZ; else if( iRawType == 3000009 ) iRawType = wkbMultiLineString25D; else if( iRawType == 3000010 ) iRawType = wkbMultiSurfaceZ; else if( iRawType == 3000011 ) iRawType = wkbMultiPolygon25D; else if( iRawType == 3000012 ) iRawType = wkbGeometryCollection25D; else if( iRawType == 4000001 ) iRawType = wkbPointM; else if( iRawType == 4000002 ) iRawType = wkbLineStringM; else if( iRawType == 4000003 ) iRawType = wkbCircularStringM; else if( iRawType == 4000004 ) iRawType = wkbCompoundCurveM; else if( iRawType == 4000005 ) iRawType = wkbPolygonM; else if( iRawType == 4000006 ) iRawType = wkbCurvePolygonM; else if( iRawType == 4000007 ) iRawType = wkbMultiPointM; else if( iRawType == 4000008 ) iRawType = wkbMultiCurveM; else if( iRawType == 4000009 ) iRawType = wkbMultiLineStringM; else if( iRawType == 4000010 ) iRawType = wkbMultiSurfaceM; else if( iRawType == 4000011 ) iRawType = wkbMultiPolygonM; else if( iRawType == 4000012 ) iRawType = wkbGeometryCollectionM; // Sometimes the Z flag is in the 2nd byte? if( iRawType & (wkb25DBitInternalUse >> 16) ) { // Clean off top 3 bytes. iRawType &= 0x000000FF; bIs3D = true; } if( eWkbVariant == wkbVariantPostGIS1 ) { if( iRawType == POSTGIS15_CURVEPOLYGON ) iRawType = wkbCurvePolygon; else if( iRawType == POSTGIS15_MULTICURVE ) iRawType = wkbMultiCurve; else if( iRawType == POSTGIS15_MULTISURFACE ) iRawType = wkbMultiSurface; } if( bIs3D ) { iRawType += 1000; } if( bIsMeasured ) { iRawType += 2000; } // ISO SQL/MM style types are between 1-17, 1001-1017, 2001-2017, and // 3001-3017. if( !((iRawType > 0 && iRawType <= 17) || (iRawType > 1000 && iRawType <= 1017) || (iRawType > 2000 && iRawType <= 2017) || (iRawType > 3000 && iRawType <= 3017)) ) { CPLError(CE_Failure, CPLE_NotSupported, ""Unsupported WKB type %d"", iRawType); return OGRERR_UNSUPPORTED_GEOMETRY_TYPE; } // Convert to OGRwkbGeometryType value. if( iRawType >= 1001 && iRawType <= 1007 ) { iRawType -= 1000; iRawType |= wkb25DBitInternalUse; } *peGeometryType = static_cast(iRawType); return OGRERR_NONE; } /************************************************************************/ /* OGRFormatFloat() */ /************************************************************************/ int OGRFormatFloat(char *pszBuffer, int nBufferLen, float fVal, int nPrecision, char chConversionSpecifier) { int nSize = 0; char szFormatting[32] = {}; constexpr int MAX_SIGNIFICANT_DIGITS_FLOAT32 = 8; const int nInitialSignificantFigures = nPrecision >= 0 ? nPrecision : MAX_SIGNIFICANT_DIGITS_FLOAT32; CPLsnprintf(szFormatting, sizeof(szFormatting), ""%%.%d%c"", nInitialSignificantFigures, chConversionSpecifier); nSize = CPLsnprintf(pszBuffer, nBufferLen, szFormatting, fVal); const char* pszDot = strchr(pszBuffer, '.'); // Try to avoid 0.34999999 or 0.15000001 rounding issues by // decreasing a bit precision. if( nInitialSignificantFigures >= 8 && pszDot != nullptr && (strstr(pszDot, ""99999"") != nullptr || strstr(pszDot, ""00000"") != nullptr) ) { const CPLString osOriBuffer(pszBuffer, nSize); bool bOK = false; for( int i = 1; i <= 3; i++ ) { CPLsnprintf(szFormatting, sizeof(szFormatting), ""%%.%d%c"", nInitialSignificantFigures - i, chConversionSpecifier); nSize = CPLsnprintf(pszBuffer, nBufferLen, szFormatting, fVal); pszDot = strchr(pszBuffer, '.'); if( pszDot != nullptr && strstr(pszDot, ""99999"") == nullptr && strstr(pszDot, ""00000"") == nullptr && static_cast(CPLAtof(pszBuffer)) == fVal ) { bOK = true; break; } } if( !bOK ) { memcpy(pszBuffer, osOriBuffer.c_str(), osOriBuffer.size()+1); nSize = static_cast(osOriBuffer.size()); } } if( nSize+2 < static_cast(nBufferLen) && strchr(pszBuffer, '.') == nullptr && strchr(pszBuffer, 'e') == nullptr ) { nSize += CPLsnprintf(pszBuffer + nSize, nBufferLen - nSize, "".0""); } return nSize; } ",16235,True,2628.4638128170277,median "/************************************************************************** * Copyright(c) 1998-2019, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided ""as is"" without express or implied warranty. * **************************************************************************/ #include #include #include #include #include #include #include #include #include ""AliVertexingHFUtils.h"" #include ""AliHFInvMassFitter.h"" /// \\cond CLASSIMP ClassImp(AliHFInvMassFitter); /// \\endcond ///////////////////////////////////////////////////////////// /// /// Implemenatation od AliHFInvMassFitter class for /// the fit of invariant mass distribution of charm hadron candidates /// reconstructed from their hadronic decays /// /// Author: F. Prino /// -> Simplified version of AliHFMassFitter class developed by C.Bianchin /// -> With extra features: /// - Polynomials with degree >2 as background fit function /// (as implemented by A. Rossi in AliHFMassFitterVAR /// - Possibility to incude a Gaussian function in the background /// (for D+ -> KKpi decays in the D_s background) /// ///////////////////////////////////////////////////////////// //__________________________________________________________________________ AliHFInvMassFitter::AliHFInvMassFitter() : TNamed(), fHistoInvMass(0x0), fMinMass(0), fMaxMass(5), fTypeOfFit4Bkg(kExpo), fPolDegreeBkg(4), fCurPolDegreeBkg(-1), fMassParticle(1.864), fTypeOfFit4Sgn(kGaus), fMass(1.865), fMassErr(0.), fSigmaSgn(0.012), fSigmaSgnErr(0.), fSigmaSgn2Gaus(0.012), fFixedMean(kFALSE), fFixedSigma(kFALSE), fFixedSigma2Gaus(kFALSE), fFixedRawYield(-1.), fFrac2Gaus(0.2), fFixedFrac2Gaus(kFALSE), fRatio2GausSigma(0.), fFixedRatio2GausSigma(kFALSE), fNParsSig(3), fNParsBkg(2), fOnlySideBands(kFALSE), fNSigma4SideBands(4.), fFitOption(""L,E""), fRawYield(0.), fRawYieldErr(0.), fSigFunc(0x0), fBkgFuncSb(0x0), fBkgFunc(0x0), fBkgFuncRefit(0x0), fReflections(kFALSE), fNParsRfl(0), fRflOverSig(0), fFixRflOverSig(kFALSE), fHistoTemplRfl(0x0), fSmoothRfl(kFALSE), fRawYieldHelp(0), fRflFunc(0x0), fBkRFunc(0x0), fSecondPeak(kFALSE), fNParsSec(0), fSecMass(-999.), fSecWidth(9999.), fFixSecMass(kFALSE), fFixSecWidth(kFALSE), fSecFunc(0x0), fTotFunc(0x0) { /// default constructor } //__________________________________________________________________________ AliHFInvMassFitter::AliHFInvMassFitter(const TH1F *histoToFit, Double_t minvalue, Double_t maxvalue, Int_t fittypeb, Int_t fittypes): TNamed(), fHistoInvMass(0x0), fMinMass(minvalue), fMaxMass(maxvalue), fTypeOfFit4Bkg(fittypeb), fPolDegreeBkg(4), fCurPolDegreeBkg(-1), fMassParticle(1.864), fTypeOfFit4Sgn(fittypes), fMass(1.865), fMassErr(0.), fSigmaSgn(0.012), fSigmaSgnErr(0.), fSigmaSgn2Gaus(0.012), fFixedMean(kFALSE), fFixedSigma(kFALSE), fFixedSigma2Gaus(kFALSE), fFixedRawYield(-1.), fFrac2Gaus(0.2), fFixedFrac2Gaus(kFALSE), fRatio2GausSigma(0.), fFixedRatio2GausSigma(kFALSE), fNParsSig(3), fNParsBkg(2), fOnlySideBands(kFALSE), fNSigma4SideBands(4.), fFitOption(""L,E""), fRawYield(0.), fRawYieldErr(0.), fSigFunc(0x0), fBkgFuncSb(0x0), fBkgFunc(0x0), fBkgFuncRefit(0x0), fReflections(kFALSE), fNParsRfl(0), fRflOverSig(0), fFixRflOverSig(kFALSE), fHistoTemplRfl(0x0), fSmoothRfl(kFALSE), fRawYieldHelp(0), fRflFunc(0x0), fBkRFunc(0x0), fSecondPeak(kFALSE), fNParsSec(0), fSecMass(-999.), fSecWidth(9999.), fFixSecMass(kFALSE), fFixSecWidth(kFALSE), fSecFunc(0x0), fTotFunc(0x0) { /// standard constructor fHistoInvMass=(TH1F*)histoToFit->Clone(""fHistoInvMass""); fHistoInvMass->SetDirectory(0); SetNumberOfParams(); } //_________________________________________________________________________ AliHFInvMassFitter::~AliHFInvMassFitter() { ///destructor delete fSigFunc; delete fBkgFunc; delete fBkgFuncSb; delete fBkgFuncRefit; delete fHistoInvMass; delete fRflFunc; delete fBkRFunc; delete fSecFunc; delete fTotFunc; delete fHistoTemplRfl; } //__________________________________________________________________________ void AliHFInvMassFitter::SetNumberOfParams(){ /// Configure number of parameters of fit functions /// switch (fTypeOfFit4Bkg) { case 0: fNParsBkg=2; break; case 1: fNParsBkg=2; break; case 2: fNParsBkg=3; break; case 3: fNParsBkg=1; break; case 4: fNParsBkg=2; break; case 5: fNParsBkg=2; break; case 6: fNParsBkg=fPolDegreeBkg+1; break; default: AliError(""Error in computing fNParsBkg: check fTypeOfFit4Bkg""); break; } switch (fTypeOfFit4Sgn) { case 0: fNParsSig=3; break; case 1: fNParsSig=5; break; case 2: fNParsSig=5; break; default: AliError(""Error in computing fNParsSig: check fTypeOfFit4Sgn""); break; } if(fReflections) fNParsRfl=1; else fNParsRfl=0; if(fSecondPeak) fNParsSec=3; else fNParsSec=0; } //__________________________________________________________________________ Int_t AliHFInvMassFitter::MassFitter(Bool_t draw){ /// Main function to fit the invariant mass distribution /// returns 0 if the fit fails /// returns 1 if the fit succeeds /// returns 2 if there is no signal and the fit is performed with only background TVirtualFitter::SetDefaultFitter(""Minuit""); Double_t integralHisto=fHistoInvMass->Integral(fHistoInvMass->FindBin(fMinMass),fHistoInvMass->FindBin(fMaxMass),""width""); fOnlySideBands = kTRUE; fBkgFuncSb = CreateBackgroundFitFunction(""funcbkgsb"",integralHisto); Int_t status=-1; printf(""\\n--- First fit with only background on the side bands - Exclusion region = %.2f sigma ---\\n"",fNSigma4SideBands); if(fTypeOfFit4Bkg==6){ if(PrepareHighPolFit(fBkgFuncSb)){ fHistoInvMass->GetListOfFunctions()->Add(fBkgFuncSb); fHistoInvMass->GetFunction(fBkgFuncSb->GetName())->SetBit(1<<9,kTRUE); status=0; } } else status=fHistoInvMass->Fit(""funcbkgsb"",Form(""R,%s,+,0"",fFitOption.Data())); fBkgFuncSb->SetLineColor(kGray+1); if (status != 0){ printf("" ---> Failed first fit with only background, minuit status = %d\\n"",status); return 0; } fOnlySideBands = kFALSE; if(!fBkgFunc){ fBkgFunc = CreateBackgroundFitFunction(""funcbkg"",integralHisto); for(Int_t ipar=0; iparSetParameter(ipar,fBkgFuncSb->GetParameter(ipar)); } fBkgFunc->SetLineColor(kGray+1); printf(""\\n--- Estimate signal counts in the peak region ---\\n""); Double_t estimSignal=CheckForSignal(fMass,fSigmaSgn); Bool_t doFinalFit=kTRUE; if(estimSignal<0.){ if(draw) DrawFit(); estimSignal=0.; doFinalFit=kFALSE; } fRawYieldHelp=estimSignal; // needed for reflection normalization if(!fBkgFuncRefit){ fBkgFuncRefit = CreateBackgroundFitFunction(""funcbkgrefit"",integralHisto); for(Int_t ipar=0; iparSetParameter(ipar,fBkgFunc->GetParameter(ipar)); } fBkgFuncRefit->SetLineColor(2); fSigFunc = CreateSignalFitFunction(""fsigfit"",estimSignal); if(fSecondPeak){ printf("" ---> Final fit includes a second inv. mass peak\\n""); Double_t estimSec=CheckForSignal(fSecMass,fSecWidth); fSecFunc = CreateSecondPeakFunction(""fsecpeak"",estimSec); } if(fReflections){ printf("" ---> Final fit includes reflections\\n""); fRflFunc = CreateReflectionFunction(""freflect""); fBkRFunc = CreateBackgroundPlusReflectionFunction(""fbkgrfl""); } fTotFunc = CreateTotalFitFunction(""funcmass""); if(doFinalFit){ printf(""\\n--- Final fit with signal+background on the full range ---\\n""); status=fHistoInvMass->Fit(""funcmass"",Form(""R,%s,+,0"",fFitOption.Data())); if (status != 0){ printf("" ---> Failed fit with signal+background, minuit status = %d\\n"",status); return 0; } } for(Int_t ipar=0; iparSetParameter(ipar,fTotFunc->GetParameter(ipar)); fBkgFuncRefit->SetParError(ipar,fTotFunc->GetParError(ipar)); } for(Int_t ipar=0; iparSetParameter(ipar,fTotFunc->GetParameter(ipar+fNParsBkg)); fSigFunc->SetParError(ipar,fTotFunc->GetParError(ipar+fNParsBkg)); } if(fSecondPeak){ for(Int_t ipar=0; iparSetParameter(ipar,fTotFunc->GetParameter(ipar+fNParsBkg+fNParsSig)); fSecFunc->SetParError(ipar,fTotFunc->GetParError(ipar+fNParsBkg+fNParsSig)); } fSecFunc->SetLineColor(kMagenta+1); fSecFunc->SetLineStyle(3); } if(fReflections){ for(Int_t ipar=0; iparSetParameter(ipar,fTotFunc->GetParameter(ipar+fNParsBkg+fNParsSig+fNParsSec)); fRflFunc->SetParError(ipar,fTotFunc->GetParError(ipar+fNParsBkg+fNParsSig+fNParsSec)); fBkRFunc->SetParameter(ipar+fNParsBkg,fTotFunc->GetParameter(ipar+fNParsBkg+fNParsSig+fNParsSec)); fBkRFunc->SetParError(ipar+fNParsBkg,fTotFunc->GetParError(ipar+fNParsBkg+fNParsSig+fNParsSec)); } for(Int_t ipar=0; iparSetParameter(ipar,fTotFunc->GetParameter(ipar)); fBkRFunc->SetParError(ipar,fTotFunc->GetParError(ipar)); } fRflFunc->SetLineColor(kGreen+1); fBkRFunc->SetLineColor(kRed+1); fBkRFunc->SetLineStyle(7); } fMass=fSigFunc->GetParameter(1); fMassErr=fSigFunc->GetParError(1); fSigmaSgn=fSigFunc->GetParameter(2); fSigmaSgnErr=fSigFunc->GetParError(2); fTotFunc->SetLineColor(4); fRawYield=fTotFunc->GetParameter(fNParsBkg)/fHistoInvMass->GetBinWidth(1); fRawYieldErr=fTotFunc->GetParError(fNParsBkg)/fHistoInvMass->GetBinWidth(1); fRawYieldHelp=fRawYield; if(draw) DrawFit(); if(doFinalFit) return 1; else return 2; } //______________________________________________________________________________ void AliHFInvMassFitter::DrawFit(){ /// Steering method to draw the fit output /// TCanvas* c0=new TCanvas(""c0""); DrawHere(c0); } //______________________________________________________________________________ void AliHFInvMassFitter::DrawHere(TVirtualPad* c, Double_t nsigma,Int_t writeFitInfo){ /// Core method to draw the fit output /// gStyle->SetOptStat(0); gStyle->SetCanvasColor(0); gStyle->SetFrameFillColor(0); c->cd(); fHistoInvMass->GetXaxis()->SetRangeUser(fMinMass,fMaxMass); fHistoInvMass->SetMarkerStyle(20); fHistoInvMass->SetMinimum(0.); fHistoInvMass->Draw(""PE""); if(fBkgFunc) fBkgFunc->Draw(""same""); if(fBkgFuncRefit) fBkgFuncRefit->Draw(""same""); if(fBkRFunc) fBkRFunc->Draw(""same""); if(fRflFunc) fRflFunc->Draw(""same""); if(fSecFunc) fSecFunc->Draw(""same""); if(fTotFunc) fTotFunc->Draw(""same""); if(writeFitInfo > 0){ TPaveText *pinfos=new TPaveText(0.12,0.65,0.47,0.89,""NDC""); TPaveText *pinfom=new TPaveText(0.6,0.7,1.,.87,""NDC""); pinfos->SetBorderSize(0); pinfos->SetFillStyle(0); pinfom->SetBorderSize(0); pinfom->SetFillStyle(0); if(fTotFunc){ pinfom->SetTextColor(kBlue); for(Int_t ipar=1; iparAddText(Form(""%s = %.3f #pm %.3f"",fTotFunc->GetParName(ipar+fNParsBkg),fTotFunc->GetParameter(ipar+fNParsBkg),fTotFunc->GetParError(ipar+fNParsBkg))); } pinfom->Draw(); Double_t bkg,errbkg; Background(nsigma,bkg,errbkg); Double_t signif,errsignif; Significance(nsigma,signif,errsignif); pinfos->AddText(Form(""S = %.0f #pm %.0f "",fRawYield,fRawYieldErr)); pinfos->AddText(Form(""B (%.0f#sigma) = %.0f #pm %.0f"",nsigma,bkg,errbkg)); pinfos->AddText(Form(""S/B (%.0f#sigma) = %.4f "",nsigma,fRawYield/bkg)); if(fRflFunc) pinfos->AddText(Form(""Refl/Sig = %.3f #pm %.3f "",fRflFunc->GetParameter(0),fRflFunc->GetParError(0))); pinfos->AddText(Form(""Signif (%.0f#sigma) = %.1f #pm %.1f "",nsigma,signif,errsignif)); pinfos->Draw(); } } c->Update(); return; } //______________________________________________________________________________ Double_t AliHFInvMassFitter::CheckForSignal(Double_t mean, Double_t sigma){ /// Checks if there are signal counts above the background /// in the invariant mass region of the peak Double_t minForSig=mean-4.*sigma; Double_t maxForSig=mean+4.*sigma; Int_t binForMinSig=fHistoInvMass->FindBin(minForSig); Int_t binForMaxSig=fHistoInvMass->FindBin(maxForSig); Double_t sum=0.; Double_t sumback=0.; fBkgFunc->Print(); for(Int_t ibin=binForMinSig; ibin<=binForMaxSig; ibin++){ sum+=fHistoInvMass->GetBinContent(ibin); sumback+=fBkgFunc->Eval(fHistoInvMass->GetBinCenter(ibin)); } Double_t diffUnderPeak=(sum-sumback); printf("" ---> IntegralUnderFitFunc=%f IntegralUnderHisto=%f EstimatedSignal=%f\\n"",sum,sumback,diffUnderPeak); if(diffUnderPeak/TMath::Sqrt(sum)<1.){ printf("" ---> (Tot-Bkg)/sqrt(Tot)=%f ---> Likely no signal/\\n"",diffUnderPeak/TMath::Sqrt(sum)); return -1; } return diffUnderPeak*fHistoInvMass->GetBinWidth(1); } //______________________________________________________________________________ TF1* AliHFInvMassFitter::CreateBackgroundFitFunction(TString fname, Double_t integral){ /// Creates the background fit fucntion /// SetNumberOfParams(); TF1* funcbkg = new TF1(fname.Data(),this,&AliHFInvMassFitter::FitFunction4Bkg,fMinMass,fMaxMass,fNParsBkg,""AliHFInvMassFitter"",""FitFunction4Bkg""); switch (fTypeOfFit4Bkg) { case 0: //gaus+expo funcbkg->SetParNames(""BkgInt"",""Slope""); funcbkg->SetParameters(integral,-2.); break; case 1: funcbkg->SetParNames(""BkgInt"",""Slope""); funcbkg->SetParameters(integral,-100.); break; case 2: funcbkg->SetParNames(""BkgInt"",""Coef1"",""Coef2""); funcbkg->SetParameters(integral,-10.,5); break; case 3: funcbkg->SetParNames(""Const""); funcbkg->SetParameter(0,0.); funcbkg->FixParameter(0,0.); break; case 4: funcbkg->SetParNames(""BkgInt"",""Coef1""); funcbkg->SetParameters(integral,0.5); break; case 5: funcbkg->SetParNames(""Coef1"",""Coef2""); funcbkg->SetParameters(-10.,5.); break; case 6: for(Int_t j=0;jSetParName(j,Form(""Coef%d"",j)); funcbkg->SetParameter(j,0); } funcbkg->SetParameter(0,integral); break; default: AliError(Form(""Wrong choice of fTypeOfFit4Bkg (%d)"",fTypeOfFit4Bkg)); delete funcbkg; return 0x0; break; } // if(fFixToHistoIntegral) funcbkg->FixParameter(0,integral); funcbkg->SetLineColor(kBlue+3); return funcbkg; } //______________________________________________________________________________ TF1* AliHFInvMassFitter::CreateSecondPeakFunction(TString fname, Double_t integsig){ /// Creates a function for a gaussian peak in the background fit function /// Can be used e.g. to include the D+->KKpi peak in the D_s inv. mass fit TF1* funcsec = new TF1(fname.Data(),this,&AliHFInvMassFitter::FitFunction4SecPeak,fMinMass,fMaxMass,3,""AliHFInvMassFitter"",""FitFunction4SecPeak""); funcsec->SetParameter(0,integsig); funcsec->SetParameter(1,fSecMass); if(fFixSecMass) funcsec->FixParameter(1,fSecMass); funcsec->SetParameter(2,fSecWidth); if(fFixSecWidth) funcsec->FixParameter(2,fSecWidth); funcsec->SetParNames(""SecPeakInt"",""SecMean"",""SecSigma""); return funcsec; } //______________________________________________________________________________ TF1* AliHFInvMassFitter::CreateReflectionFunction(TString fname){ /// Creates a function for reflections contribution /// in the D0->Kpi inv. mass distribution TF1* funcrfl = new TF1(fname.Data(),this,&AliHFInvMassFitter::FitFunction4Refl,fMinMass,fMaxMass,1,""AliHFInvMassFitter"",""FitFunction4Refl""); funcrfl->SetParameter(0,fRflOverSig); funcrfl->SetParLimits(0,0.,1.); if(fFixRflOverSig) funcrfl->FixParameter(0,fRflOverSig); funcrfl->SetParNames(""ReflOverS""); return funcrfl; } //______________________________________________________________________________ TF1* AliHFInvMassFitter::CreateBackgroundPlusReflectionFunction(TString fname){ /// Creates the function with sum of background and reflections /// SetNumberOfParams(); Int_t totParams=fNParsBkg+fNParsRfl; TF1* fbr=new TF1(fname.Data(),this,&AliHFInvMassFitter::FitFunction4BkgAndRefl,fMinMass,fMaxMass,totParams,""AliHFInvMassFitter"",""FitFunction4BkgAndRefl""); for(Int_t ipar=0; iparSetParameter(ipar,fBkgFunc->GetParameter(ipar)); fbr->SetParName(ipar,fBkgFunc->GetParName(ipar)); } for(Int_t ipar=0; iparSetParameter(ipar+fNParsBkg,fRflFunc->GetParameter(ipar)); fbr->SetParName(ipar+fNParsBkg,fRflFunc->GetParName(ipar)); // par limits not set because this function is not used for fitting but only for drawing } return fbr; } //______________________________________________________________________________ TF1* AliHFInvMassFitter::CreateSignalFitFunction(TString fname, Double_t integsig){ /// Creates the fit function for the signal peak /// SetNumberOfParams(); TF1* funcsig = new TF1(fname.Data(),this,&AliHFInvMassFitter::FitFunction4Sgn,fMinMass,fMaxMass,fNParsSig,""AliHFInvMassFitter"",""FitFunction4Sgn""); if(fTypeOfFit4Sgn==kGaus){ funcsig->SetParameter(0,integsig); if(fFixedRawYield>-0.1) funcsig->FixParameter(0,fFixedRawYield); funcsig->SetParameter(1,fMass); if(fFixedMean) funcsig->FixParameter(1,fMass); funcsig->SetParameter(2,fSigmaSgn); if(fFixedSigma) funcsig->FixParameter(2,fSigmaSgn); funcsig->SetParNames(""SgnInt"",""Mean"",""Sigma""); } if(fTypeOfFit4Sgn==k2Gaus){ funcsig->SetParameter(0,integsig); if(fFixedRawYield>-0.1) funcsig->FixParameter(0,fFixedRawYield); funcsig->SetParameter(1,fMass); if(fFixedMean) funcsig->FixParameter(1,fMass); funcsig->SetParameter(2,fSigmaSgn); funcsig->SetParLimits(2,0.004,0.05); if(fFixedSigma) funcsig->FixParameter(2,fSigmaSgn); funcsig->SetParameter(3,fFrac2Gaus); if(fFixedFrac2Gaus) funcsig->FixParameter(3,fFrac2Gaus); else funcsig->SetParLimits(3,0.,1.); funcsig->SetParameter(4,fSigmaSgn2Gaus); if(fFixedSigma2Gaus) funcsig->FixParameter(4,fSigmaSgn2Gaus); else funcsig->SetParLimits(4,0.004,0.05); funcsig->SetParNames(""SgnInt"",""Mean"",""Sigma1"",""Frac"",""Sigma2""); } if(fTypeOfFit4Sgn==k2GausSigmaRatioPar){ funcsig->SetParameter(0,integsig); if(fFixedRawYield>-0.1) funcsig->FixParameter(0,fFixedRawYield); funcsig->SetParameter(1,fMass); if(fFixedMean) funcsig->FixParameter(1,fMass); funcsig->SetParameter(2,fSigmaSgn); funcsig->SetParLimits(2,0.004,0.05); if(fFixedSigma) funcsig->FixParameter(2,fSigmaSgn); funcsig->SetParameter(3,fFrac2Gaus); if(fFixedFrac2Gaus) funcsig->FixParameter(3,fFrac2Gaus); else funcsig->SetParLimits(3,0.,1.); funcsig->SetParameter(4,fSigmaSgn2Gaus); if(fFixedRatio2GausSigma) funcsig->FixParameter(4,fRatio2GausSigma); else funcsig->SetParLimits(4,0.,20.); funcsig->SetParNames(""SgnInt"",""Mean"",""Sigma1"",""Frac"",""RatioSigma12""); } return funcsig; } //______________________________________________________________________________ TF1* AliHFInvMassFitter::CreateTotalFitFunction(TString fname){ /// Creates the total fit fucntion (signal+background+possible second peak) /// SetNumberOfParams(); Int_t totParams=fNParsBkg+fNParsRfl+fNParsSec+fNParsSig; TF1* ftot=new TF1(fname.Data(),this,&AliHFInvMassFitter::FitFunction4Mass,fMinMass,fMaxMass,totParams,""AliHFInvMassFitter"",""FitFunction4Mass""); for(Int_t ipar=0; iparSetParameter(ipar,fBkgFunc->GetParameter(ipar)); ftot->SetParName(ipar,fBkgFunc->GetParName(ipar)); // Double_t parmin,parmax; // fBkgFunc->GetParLimits(ipar,parmin,parmax); // ftot->SetParLimits(ipar,parmin,parmax); } for(Int_t ipar=0; iparSetParameter(ipar+fNParsBkg,fSigFunc->GetParameter(ipar)); ftot->SetParName(ipar+fNParsBkg,fSigFunc->GetParName(ipar)); Double_t parmin,parmax; fSigFunc->GetParLimits(ipar,parmin,parmax); ftot->SetParLimits(ipar+fNParsBkg,parmin,parmax); } if(fSecondPeak && fSecFunc){ for(Int_t ipar=0; iparSetParameter(ipar+fNParsBkg+fNParsSig,fSecFunc->GetParameter(ipar)); ftot->SetParName(ipar+fNParsBkg+fNParsSig,fSecFunc->GetParName(ipar)); Double_t parmin,parmax; fSecFunc->GetParLimits(ipar,parmin,parmax); ftot->SetParLimits(ipar+fNParsBkg+fNParsSig,parmin,parmax); } } if(fReflections && fRflFunc){ for(Int_t ipar=0; iparSetParameter(ipar+fNParsBkg+fNParsSig+fNParsSec,fRflFunc->GetParameter(ipar)); ftot->SetParName(ipar+fNParsBkg+fNParsSig+fNParsSec,fRflFunc->GetParName(ipar)); Double_t parmin,parmax; fRflFunc->GetParLimits(ipar,parmin,parmax); ftot->SetParLimits(ipar+fNParsBkg+fNParsSig+fNParsSec,parmin,parmax); } } return ftot; } //__________________________________________________________________________ Double_t AliHFInvMassFitter::FitFunction4Bkg (Double_t *x, Double_t *par){ /// Fit function for the background /// Double_t maxDeltaM = fNSigma4SideBands*fSigmaSgn; if(fOnlySideBands && TMath::Abs(x[0]-fMass) < maxDeltaM) { TF1::RejectPoint(); return 0; } if(fOnlySideBands && fSecondPeak && TMath::Abs(x[0]-fSecMass) < (fNSigma4SideBands*fSecWidth)){ TF1::RejectPoint(); return 0; } Double_t total=0; switch (fTypeOfFit4Bkg){ case 0: //exponential //exponential = A*exp(B*x) -> integral(exponential)=A/B*exp(B*x)](min,max) //-> A = B*integral/(exp(B*max)-exp(B*min)) where integral can be written //as integralTot- integralGaus (=par [2]) //Par: // * [0] = integralBkg; // * [1] = B; //exponential = [1]*[0]/(exp([1]*max)-exp([1]*min))*exp([1]*x) total = par[0]*par[1]/(TMath::Exp(par[1]*fMaxMass)-TMath::Exp(par[1]*fMinMass))*TMath::Exp(par[1]*x[0]); // AliInfo(""Background function set to: exponential""); break; case 1: //linear //y=a+b*x -> integral = a(max-min)+1/2*b*(max^2-min^2) -> a = (integral-1/2*b*(max^2-min^2))/(max-min)=integral/(max-min)-1/2*b*(max+min) // * [0] = integralBkg; // * [1] = b; total= par[0]/(fMaxMass-fMinMass)+par[1]*(x[0]-0.5*(fMaxMass+fMinMass)); // AliInfo(""Background function set to: linear""); break; case 2: //parabola //y=a+b*x+c*x**2 -> integral = a(max-min) + 1/2*b*(max^2-min^2) + //+ 1/3*c*(max^3-min^3) -> //a = (integral-1/2*b*(max^2-min^2)-1/3*c*(max^3-min^3))/(max-min) // * [0] = integralBkg; // * [1] = b; // * [2] = c; total = par[0]/(fMaxMass-fMinMass)+par[1]*(x[0]-0.5*(fMaxMass+fMinMass))+par[2]*(x[0]*x[0]-1/3.*(fMaxMass*fMaxMass*fMaxMass-fMinMass*fMinMass*fMinMass)/(fMaxMass-fMinMass)); // AliInfo(""Background function set to: polynomial""); break; case 3: total=par[0]; break; case 4: //power function //y=a(x-m_pi)^b -> integral = a/(b+1)*((max-m_pi)^(b+1)-(min-m_pi)^(b+1)) // //a = integral*(b+1)/((max-m_pi)^(b+1)-(min-m_pi)^(b+1)) // * [0] = integralBkg; // * [1] = b; // a(power function) = [0]*([1]+1)/((max-m_pi)^([1]+1)-(min-m_pi)^([1]+1))*(x-m_pi)^[1] { Double_t mpi = TDatabasePDG::Instance()->GetParticle(211)->Mass(); total = par[0]*(par[1]+1.)/(TMath::Power(fMaxMass-mpi,par[1]+1.)-TMath::Power(fMinMass-mpi,par[1]+1.))*TMath::Power(x[0]-mpi,par[1]); // AliInfo(""Background function set to: powerlaw""); } break; case 5: //power function wit exponential //y=a*Sqrt(x-m_pi)*exp(-b*(x-m_pi)) { Double_t mpi = TDatabasePDG::Instance()->GetParticle(211)->Mass(); total = par[0]*TMath::Sqrt(x[0] - mpi)*TMath::Exp(-1.*par[1]*(x[0]-mpi)); // AliInfo(""Background function set to: wit exponential""); } break; case 6: // the following comment must be removed // // pol 3, following convention for pol 2 // //y=a+b*x+c*x**2+d*x**3 -> integral = a(max-min) + 1/2*b*(max^2-min^2) + // //+ 1/3*c*(max^3-min^3) + 1/4 d * (max^4-min^4) -> // //a = (integral-1/2*b*(max^2-min^2)-1/3*c*(max^3-min^3) - 1/4 d * (max^4-min^4) )/(max-min) // // * [0] = integralBkg; // // * [1] = b; // // * [2] = c; // // * [3] = d; { total=par[0]; for(Int_t it=1;it<=fPolDegreeBkg;it++){ total+=par[it]*TMath::Power(x[0]-fMassParticle,it)/TMath::Factorial(it); } } break; } return total; } //_________________________________________________________________________ Double_t AliHFInvMassFitter::FitFunction4Sgn (Double_t *x, Double_t *par){ /// Fit function for the signal /// // AliInfo(""Signal function set to: Gaussian""); Double_t sigval=0; Double_t g1=0; Double_t g2=0; switch (fTypeOfFit4Sgn){ case 0: //gaussian = A/(sigma*sqrt(2*pi))*exp(-(x-mean)^2/2/sigma^2) //Par: // * [0] = integralSgn // * [1] = mean // * [2] = sigma //gaussian = [0]/TMath::Sqrt(2.*TMath::Pi())/[2]*exp[-(x-[1])*(x-[1])/(2*[2]*[2])] sigval=par[0]/TMath::Sqrt(2.*TMath::Pi())/par[2]*TMath::Exp(-(x[0]-par[1])*(x[0]-par[1])/2./par[2]/par[2]); break; case 1: //double gaussian = A/(sigma*sqrt(2*pi))*exp(-(x-mean)^2/2/sigma^2) //Par: // * [0] = integralSgn // * [1] = mean // * [2] = sigma1 // * [3] = 2nd gaussian ratio // * [4] = deltaSigma //gaussian = [0]/TMath::Sqrt(2.*TMath::Pi())/[2]*exp[-(x-[1])*(x-[1])/(2*[2]*[2])] g1=(1.-par[3])/TMath::Sqrt(2.*TMath::Pi())/par[2]*TMath::Exp(-(x[0]-par[1])*(x[0]-par[1])/2./par[2]/par[2]); g2=par[3]/TMath::Sqrt(2.*TMath::Pi())/par[4]*TMath::Exp(-(x[0]-par[1])*(x[0]-par[1])/2./par[4]/par[4]); sigval=par[0]*(g1+g2); break; case 2: //double gaussian = A/(sigma*sqrt(2*pi))*exp(-(x-mean)^2/2/sigma^2) //Par: // * [0] = integralSgn // * [1] = mean // * [2] = sigma1 // * [3] = 2nd gaussian ratio // * [4] = ratio sigma12 g1=(1.-par[3])/TMath::Sqrt(2.*TMath::Pi())/par[2]*TMath::Exp(-(x[0]-par[1])*(x[0]-par[1])/2./par[2]/par[2]); g2=par[3]/TMath::Sqrt(2.*TMath::Pi())/(par[4]*par[2])*TMath::Exp(-(x[0]-par[1])*(x[0]-par[1])/2./(par[4]*par[2])/(par[4]*par[2])); sigval=par[0]*(g1+g2); break; } fRawYieldHelp=par[0]/fHistoInvMass->GetBinWidth(1); return sigval; } //_________________________________________________________________________ Double_t AliHFInvMassFitter::FitFunction4Refl(Double_t *x,Double_t *par){ /// Fit function for reflections: /// D0->Kpi decays with swapped mass assignment to pion and kaon decay tracks if(!fHistoTemplRfl) return 0; Int_t bin =fHistoTemplRfl->FindBin(x[0]); Double_t value=fHistoTemplRfl->GetBinContent(bin); Int_t binmin=fHistoTemplRfl->FindBin(fMinMass*1.00001); Int_t binmax=fHistoTemplRfl->FindBin(fMaxMass*0.99999); Double_t norm=fHistoTemplRfl->Integral(binmin,binmax)*fHistoTemplRfl->GetBinWidth(bin); if(TMath::Abs(value)<1.e-14&&fSmoothRfl){// very rough, assume a constant trend, much better would be a pol1 or pol2 over a broader range value+=fHistoTemplRfl->GetBinContent(bin-1)+fHistoTemplRfl->GetBinContent(bin+1); value/=3.; } return par[0]*value/norm*fRawYieldHelp*fHistoInvMass->GetBinWidth(1); } //_________________________________________________________________________ Double_t AliHFInvMassFitter::FitFunction4BkgAndRefl(Double_t *x, Double_t *par){ /// Fit fucntion with the sum of background and reflections /// Double_t bkg=FitFunction4Bkg(x,par); Double_t refl=0; if(fReflections) refl=FitFunction4Refl(x,&par[fNParsBkg]); return bkg+refl; } //_________________________________________________________________________ Double_t AliHFInvMassFitter::FitFunction4SecPeak (Double_t *x, Double_t *par){ /// Fit function for a second gaussian peak /// To be used, e.g., for D+->KKpi in the Ds mass spectrum //gaussian = A/(sigma*sqrt(2*pi))*exp(-(x-mean)^2/2/sigma^2) //Par: // * [0] = integralSgn // * [1] = mean // * [2] = sigma Double_t secgaval=par[0]/TMath::Sqrt(2.*TMath::Pi())/par[2]*TMath::Exp(-(x[0]-par[1])*(x[0]-par[1])/2./par[2]/par[2]); return secgaval; } //_________________________________________________________________________ Double_t AliHFInvMassFitter::FitFunction4Mass(Double_t *x, Double_t *par){ /// Total fit function (signal+background+possible second peak) /// Double_t bkg=FitFunction4Bkg(x,par); Double_t sig=FitFunction4Sgn(x,&par[fNParsBkg]); Double_t sec=0.; if(fSecondPeak) sec=FitFunction4SecPeak(x,&par[fNParsBkg+fNParsSig]); Double_t refl=0; if(fReflections) refl=FitFunction4Refl(x,&par[fNParsBkg+fNParsSig+fNParsSec]); return bkg+sig+sec+refl; } //_________________________________________________________________________ void AliHFInvMassFitter::Signal(Double_t nOfSigma,Double_t &signal,Double_t &errsignal) const { /// Return signal integral in mean +- n sigma /// Double_t minMass=fMass-nOfSigma*fSigmaSgn; Double_t maxMass=fMass+nOfSigma*fSigmaSgn; Signal(minMass,maxMass,signal,errsignal); return; } //_________________________________________________________________________ void AliHFInvMassFitter::Signal(Double_t min, Double_t max, Double_t &signal,Double_t &errsignal) const { /// Return signal integral in a range /// signal=fSigFunc->Integral(min, max)/(Double_t)fHistoInvMass->GetBinWidth(1); errsignal=(fRawYieldErr/fRawYield)*signal;/*assume relative error is the same as for total integral*/ return; } //___________________________________________________________________________ void AliHFInvMassFitter::Background(Double_t nOfSigma,Double_t &background,Double_t &errbackground) const { /// Return background integral in mean +- n sigma /// Double_t minMass=fMass-nOfSigma*fSigmaSgn; Double_t maxMass=fMass+nOfSigma*fSigmaSgn; Background(minMass,maxMass,background,errbackground); return; } //___________________________________________________________________________ void AliHFInvMassFitter::Background(Double_t min, Double_t max, Double_t &background,Double_t &errbackground) const { /// Return background integral in a range /// TF1 *funcbkg=0x0; if(fBkgFuncRefit) funcbkg=fBkgFuncRefit; else if(fBkgFunc) funcbkg=fBkgFunc; if(!funcbkg){ AliError(""Bkg function not found!""); return; } Double_t intB=funcbkg->GetParameter(0); Double_t intBerr=funcbkg->GetParError(0); //relative error evaluation: from histo Int_t leftBand=fHistoInvMass->FindBin(fMass-fNSigma4SideBands*fSigmaSgn); Int_t rightBand=fHistoInvMass->FindBin(fMass+fNSigma4SideBands*fSigmaSgn); intB=fHistoInvMass->Integral(1,leftBand)+fHistoInvMass->Integral(rightBand,fHistoInvMass->GetNbinsX()); Double_t sum2=0; for(Int_t i=1;i<=leftBand;i++){ sum2+=fHistoInvMass->GetBinError(i)*fHistoInvMass->GetBinError(i); } for(Int_t i=rightBand; i<=fHistoInvMass->GetNbinsX();i++){ sum2+=fHistoInvMass->GetBinError(i)*fHistoInvMass->GetBinError(i); } intBerr=TMath::Sqrt(sum2); background=funcbkg->Integral(min,max)/(Double_t)fHistoInvMass->GetBinWidth(1); errbackground=intBerr/intB*background; return; } //__________________________________________________________________________ void AliHFInvMassFitter::Significance(Double_t nOfSigma,Double_t &significance,Double_t &errsignificance) const { /// Return significance in mean +- n sigma /// Double_t minMass=fMass-nOfSigma*fSigmaSgn; Double_t maxMass=fMass+nOfSigma*fSigmaSgn; Significance(minMass, maxMass, significance, errsignificance); return; } //__________________________________________________________________________ void AliHFInvMassFitter::Significance(Double_t min, Double_t max, Double_t &significance,Double_t &errsignificance) const { /// Return significance integral in a range /// Double_t background,errbackground; Background(min,max,background,errbackground); if (fRawYield+background <= 0.){ significance=-1; errsignificance=0; return; } AliVertexingHFUtils::ComputeSignificance(fRawYield,fRawYieldErr,background,errbackground,significance,errsignificance); return; } //________________________________________________________________________ Bool_t AliHFInvMassFitter::PrepareHighPolFit(TF1 *fback){ /// Perform intermediate fit steps up to fPolDegreeBkg-1 /// in case of fit with a polynomial with degree > 2 (fTypeOfFit4Bkg=6) TH1F *hCp=(TH1F*)fHistoInvMass->Clone(""htemp""); Double_t estimatecent=0.5*(hCp->GetBinContent(hCp->FindBin(fMass-3.5*fSigmaSgn))+hCp->GetBinContent(hCp->FindBin(fMass+3.5*fSigmaSgn)));// just a first rough estimate Double_t estimateslope=(hCp->GetBinContent(hCp->FindBin(fMass+3.5*fSigmaSgn))-hCp->GetBinContent(hCp->FindBin(fMass-3.5*fSigmaSgn)))/(7*fSigmaSgn);// first rough estimate fCurPolDegreeBkg=2; TF1 *funcbkg,*funcPrev=0x0; while(fCurPolDegreeBkg<=fPolDegreeBkg){ funcbkg = new TF1(Form(""temp%d"",fCurPolDegreeBkg),this,&AliHFInvMassFitter::BackFitFuncPolHelper,fMinMass,fMaxMass,fCurPolDegreeBkg+1,""AliHFInvMassFitter"",""BackFitFuncPolHelper""); if(funcPrev){ for(Int_t j=0;jSetParameter(j,funcPrev->GetParameter(j)); } delete funcPrev; } else{ funcbkg->SetParameter(0,estimatecent); funcbkg->SetParameter(1,estimateslope); } printf("" ---> Pre-fit of background with pol degree %d ---\\n"",fCurPolDegreeBkg); hCp->Fit(funcbkg,""REMN"",""""); funcPrev=(TF1*)funcbkg->Clone(""ftemp""); delete funcbkg; fCurPolDegreeBkg++; } for(Int_t j=0;j<=fPolDegreeBkg;j++){ fback->SetParameter(j,funcPrev->GetParameter(j)); fback->SetParError(j,funcPrev->GetParError(j)); } printf("" ---> Final background fit with pol degree %d ---\\n"",fPolDegreeBkg); hCp->Fit(fback,""REMN"","""");// THIS IS JUST TO SET NOT ONLY THE PARAMETERS BUT ALSO chi2, etc... // The following lines might be useful for debugging // TCanvas *cDebug=new TCanvas(); // cDebug->cd(); // hCp->Draw(); // TString strout=Form(""Test%d.root"",(Int_t)fhistoInvMass->GetBinContent(fhistoInvMass->FindBin(fMass))); // cDebug->Print(strout.Data()); // delete cDebug; delete funcPrev; delete hCp; return kTRUE; } // _______________________________________________________________________ Double_t AliHFInvMassFitter::BackFitFuncPolHelper(Double_t *x,Double_t *par){ /// Helper function for polynomials with degree>2 /// Double_t maxDeltaM = fNSigma4SideBands*fSigmaSgn; if(fOnlySideBands && TMath::Abs(x[0]-fMass) < maxDeltaM) { TF1::RejectPoint(); return 0; } Double_t back=par[0]; for(Int_t it=1;it<=fCurPolDegreeBkg;it++){ back+=par[it]*TMath::Power(x[0]-fMassParticle,it)/TMath::Factorial(it); } return back; } // _______________________________________________________________________ TH1F* AliHFInvMassFitter::SetTemplateReflections(const TH1 *h, TString opt,Double_t minRange,Double_t maxRange){ /// Method to create the reflection invariant mass distributions from MC templates /// option could be: /// ""template"" use MC histograms /// ""1gaus"" ot ""singlegaus"" single gaussian function fit to MC templates /// ""2gaus"" ot ""doublegaus"" double gaussian function fit to MC templates /// ""pol3"" 3rd order polynomial fit to MC templates /// ""pol6"" 6th order polynomial fit to MC templates if(!h){ fReflections=kFALSE; return 0x0; } fHistoTemplRfl=(TH1F*)h->Clone(""hTemplRfl""); opt.ToLower(); fReflections=kTRUE; printf(""\\n--- Reflection templates from simulation ---\\n""); if(opt.Contains(""templ"")){ printf("" ---> Reflection contribution using directly the histogram from simulation\\n""); return fHistoTemplRfl; } TF1 *f=0x0; Bool_t isPoissErr=kTRUE; Double_t xMinForFit=h->GetBinLowEdge(1); Double_t xMaxForFit=h->GetXaxis()->GetBinUpEdge(h->GetNbinsX()); if(minRange>=0 && maxRange>=0){ xMinForFit=TMath::Max(minRange,h->GetBinLowEdge(1)); xMaxForFit=TMath::Min(maxRange,h->GetXaxis()->GetBinUpEdge(h->GetNbinsX())); } if(opt.EqualTo(""1gaus"") || opt.EqualTo(""singlegaus"")){ printf("" ---> Reflection contribution from single-Gaussian fit to histogram from simulation\\n""); f=new TF1(""mygaus"",""gaus"",xMinForFit,xMaxForFit); f->SetParameter(0,h->GetMaximum()); // f->SetParLimits(0,0,100.*h->Integral()); f->SetParameter(1,1.865); f->SetParameter(2,0.050); fHistoTemplRfl->Fit(f,""REM0"","""");//,h->GetBinLowEdge(1),h->GetXaxis()->GetBinUpEdge(h->GetNbinsX())); } else if(opt.EqualTo(""2gaus"") || opt.EqualTo(""doublegaus"")){ printf("" ---> Reflection contribution from double-Gaussian fit to histogram from simulation\\n""); f=new TF1(""my2gaus"",""[0]*([3]/( TMath::Sqrt(2.*TMath::Pi())*[2])*TMath::Exp(-(x-[1])*(x-[1])/(2.*[2]*[2]))+(1.-[3])/( TMath::Sqrt(2.*TMath::Pi())*[5])*TMath::Exp(-(x-[4])*(x-[4])/(2.*[5]*[5])))"",xMinForFit,xMaxForFit); f->SetParameter(0,h->GetMaximum()); // f->SetParLimits(0,0,100.*h->Integral()); f->SetParLimits(3,0.,1.); f->SetParameter(3,0.5); f->SetParameter(1,1.84); f->SetParameter(2,0.050); f->SetParameter(4,1.88); f->SetParameter(5,0.050); fHistoTemplRfl->Fit(f,""REM0"","""");//,h->GetBinLowEdge(1),h->GetXaxis()->GetBinUpEdge(h->GetNbinsX())); } else if(opt.EqualTo(""pol3"")){ printf("" ---> Reflection contribution from pol3 fit to histogram from simulation\\n""); f=new TF1(""mypol3"",""pol3"",xMinForFit,xMaxForFit); f->SetParameter(0,h->GetMaximum()); // f->SetParLimits(0,0,100.*h->Integral()); // Hard to initialize the other parameters... fHistoTemplRfl->Fit(f,""REM0"",""""); // Printf(""We USED %d POINTS in the Fit"",f->GetNumberFitPoints()); } else if(opt.EqualTo(""pol6"")){ printf("" ---> Reflection contribution from pol6 fit to histogram from simulation\\n""); f=new TF1(""mypol6"",""pol6"",xMinForFit,xMaxForFit); f->SetParameter(0,h->GetMaximum()); // f->SetParLimits(0,0,100.*h->Integral()); // Hard to initialize the other parameters... fHistoTemplRfl->Fit(f,""RLEMI0"","""");//,h->GetBinLowEdge(1),h->GetXaxis()->GetBinUpEdge(h->GetNbinsX())); } else{ // no good option passed printf("" ---> Bad option for reflection configuration -> reflections will not be included in the fit\\n""); fReflections=kFALSE; delete fHistoTemplRfl; fHistoTemplRfl=0x0; return 0x0; } // Fill fHistoTemplRfl with values of fit function if(f){ for(Int_t j=1;j<=fHistoTemplRfl->GetNbinsX();j++){ fHistoTemplRfl->SetBinContent(j,f->Integral(fHistoTemplRfl->GetBinLowEdge(j),fHistoTemplRfl->GetXaxis()->GetBinUpEdge(j))/fHistoTemplRfl->GetBinWidth(j)); if(fHistoTemplRfl->GetBinContent(j)>=0.&&TMath::Abs(h->GetBinError(j)*h->GetBinError(j)-h->GetBinContent(j))>0.1*h->GetBinContent(j))isPoissErr=kFALSE; } for(Int_t j=1;j<=fHistoTemplRfl->GetNbinsX();j++){ if(isPoissErr){ fHistoTemplRfl->SetBinError(j,TMath::Sqrt(fHistoTemplRfl->GetBinContent(j))); } else fHistoTemplRfl->SetBinError(j,0.001*fHistoTemplRfl->GetBinContent(j)); } fReflections=kTRUE; return fHistoTemplRfl; }else{ printf("" ---> Fit to MC template for reflection failed -> reflections will not be included in the fit\\n""); fReflections=kFALSE; delete fHistoTemplRfl; fHistoTemplRfl=0x0; return 0x0; } return 0x0; } // _______________________________________________________________________ Double_t AliHFInvMassFitter::GetRawYieldBinCounting(Double_t& errRyBC, Double_t nOfSigma, Int_t option, Int_t pdgCode) const{ /// Method to compute the signal using inv. mass histo bin counting /// -> interface method to compute yield in nsigma range around peak /// pdgCode: if==411,421,413,413 or 4122: range defined based on PDG mass // else (default) mean of gaussian fit Double_t massVal=fMass; switch (pdgCode) { case 411: case 421: case 431: case 4122: massVal=TDatabasePDG::Instance()->GetParticle(pdgCode)->Mass(); break; case 413: massVal=TDatabasePDG::Instance()->GetParticle(pdgCode)->Mass(); massVal-=TDatabasePDG::Instance()->GetParticle(421)->Mass(); break; default: massVal=fMass; break; } Double_t minMass=massVal-nOfSigma*fSigmaSgn; Double_t maxMass=massVal+nOfSigma*fSigmaSgn; return GetRawYieldBinCounting(errRyBC,minMass,maxMass,option); } // _______________________________________________________________________ Double_t AliHFInvMassFitter::GetRawYieldBinCounting(Double_t& errRyBC, Double_t minMass, Double_t maxMass, Int_t option) const{ /// Method to compute the signal using inv. mass histo bin counting /// after background subtraction from background fit function /// option=0: background fit function from 1st fit step (only side bands) /// option=1: background fit function from 2nd fit step (S+B) Int_t minBinSum=fHistoInvMass->FindBin(minMass); Int_t maxBinSum=fHistoInvMass->FindBin(maxMass); if(minBinSum<1){ printf(""Left range for bin counting smaller than allowed by histogram axis, setting it to the lower edge of the first histo bin\\n""); minBinSum=1; } if(maxBinSum>fHistoInvMass->GetNbinsX()){ printf(""Right range for bin counting larger than allowed by histogram axis, setting it to the upper edge of the last histo bin\\n""); maxBinSum=fHistoInvMass->GetNbinsX(); } Double_t cntSig=0.; Double_t cntErr=0.; errRyBC=0; TF1* fbackground=fBkgFunc; if(option==1) fbackground=fBkgFuncRefit; if(!fbackground) return 0.; for(Int_t jb=minBinSum; jb<=maxBinSum; jb++){ Double_t cntTot=fHistoInvMass->GetBinContent(jb); Double_t cntBkg=fbackground->Integral(fHistoInvMass->GetBinLowEdge(jb),fHistoInvMass->GetBinLowEdge(jb)+fHistoInvMass->GetBinWidth(jb))/fHistoInvMass->GetBinWidth(jb); Double_t cntRefl=0; if(option==1 && fRflFunc) cntRefl=fRflFunc->Integral(fHistoInvMass->GetBinLowEdge(jb),fHistoInvMass->GetBinLowEdge(jb)+fHistoInvMass->GetBinWidth(jb))/fHistoInvMass->GetBinWidth(jb); //Double_t cntBkg=fbackground->Eval(fHistoInvMass->GetBinCenter(jb)); Double_t cntSecPeak=0; if(option==1 && fSecondPeak && fSecFunc) cntSecPeak=fSecFunc->Integral(fHistoInvMass->GetBinLowEdge(jb),fHistoInvMass->GetBinLowEdge(jb)+fHistoInvMass->GetBinWidth(jb))/fHistoInvMass->GetBinWidth(jb); cntSig+=(cntTot-cntBkg-cntRefl-cntSecPeak); cntErr+=(fHistoInvMass->GetBinError(jb)*fHistoInvMass->GetBinError(jb)); } errRyBC=TMath::Sqrt(cntErr); return cntSig; } // _______________________________________________________________________ TH1F* AliHFInvMassFitter::GetResidualsAndPulls(TH1 *hPulls,TH1 *hResidualTrend,TH1 *hPullsTrend, Double_t minrange,Double_t maxrange, Int_t option){ /// fill and return the residual and pull histos Int_t binmi=fHistoInvMass->FindBin(fMinMass*1.001); Int_t binma=fHistoInvMass->FindBin(fMaxMass*0.9999); if(maxrange>minrange){ binmi=fHistoInvMass->FindBin(minrange*1.001); binma=fHistoInvMass->FindBin(maxrange*0.9999); } if(hResidualTrend){ //fHistoInvMass->Copy(hResidualTrend); hResidualTrend->SetBins(fHistoInvMass->GetNbinsX(),fHistoInvMass->GetXaxis()->GetXmin(),fHistoInvMass->GetXaxis()->GetXmax()); hResidualTrend->SetName(Form(""%s_residualTrend"",fHistoInvMass->GetName())); hResidualTrend->SetTitle(Form(""%s (Residuals)"",fHistoInvMass->GetTitle())); hResidualTrend->SetMarkerStyle(20); hResidualTrend->SetMarkerSize(1.0); hResidualTrend->Reset(); } if(hPullsTrend){ hPullsTrend->SetBins(fHistoInvMass->GetNbinsX(),fHistoInvMass->GetXaxis()->GetXmin(),fHistoInvMass->GetXaxis()->GetXmax()); hPullsTrend->Reset(); hPullsTrend->SetName(Form(""%s_pullTrend"",fHistoInvMass->GetName())); hPullsTrend->SetTitle(Form(""%s (Pulls)"",fHistoInvMass->GetTitle())); hPullsTrend->SetMarkerStyle(20); hPullsTrend->SetMarkerSize(1.0); } if(hPulls){ hPulls->SetName(Form(""%s_pulls"",fHistoInvMass->GetName())); hPulls->SetTitle(Form(""%s ; Pulls"",fHistoInvMass->GetTitle())); hPulls->SetBins(40,-10,10); hPulls->Reset(); } Double_t res=-1.e-6,min=1.e+12,max=-1.e+12; TArrayD *arval=new TArrayD(binma-binmi+1); for(Int_t jst=1;jst<=fHistoInvMass->GetNbinsX();jst++){ Double_t integFit=0; if(option==0) integFit=fTotFunc->Integral(fHistoInvMass->GetBinLowEdge(jst),fHistoInvMass->GetBinLowEdge(jst)+fHistoInvMass->GetBinWidth(jst)); else{ integFit=fBkgFuncRefit->Integral(fHistoInvMass->GetBinLowEdge(jst),fHistoInvMass->GetBinLowEdge(jst)+fHistoInvMass->GetBinWidth(jst)); if(option==2) integFit+=fRflFunc->Integral(fHistoInvMass->GetBinLowEdge(jst),fHistoInvMass->GetBinLowEdge(jst)+fHistoInvMass->GetBinWidth(jst)); } res=fHistoInvMass->GetBinContent(jst)-integFit/fHistoInvMass->GetBinWidth(jst); if(jst>=binmi&&jst<=binma){ arval->AddAt(res,jst-binmi); if(resmax)max=res; } // Printf(""Res = %f from %f - %f"",res,fHistoInvMass->GetBinContent(jst),fTotFunc->Integral(fHistoInvMass->GetBinLowEdge(jst),fHistoInvMass->GetBinLowEdge(jst)+fHistoInvMass->GetBinWidth(jst))/fHistoInvMass->GetBinWidth(jst)); if(hResidualTrend){ hResidualTrend->SetBinContent(jst,res); hResidualTrend->SetBinError(jst,fHistoInvMass->GetBinError(jst)); } if(hPulls){ if(jst>=binmi&&jst<=binma)hPulls->Fill(res/fHistoInvMass->GetBinError(jst)); } if(hPullsTrend){ hPullsTrend->SetBinContent(jst,res/fHistoInvMass->GetBinError(jst)); hPullsTrend->SetBinError(jst,0.0001); } } if(hResidualTrend){ hResidualTrend->GetXaxis()->SetRange(binmi,binma); if(option!=0){ TF1 *fgauss=new TF1(""signalTermForRes"",""[0]/TMath::Sqrt(2.*TMath::Pi())/[2]*TMath::Exp(-(x-[1])*(x-[1])/2./[2]/[2])"",fHistoInvMass->GetBinLowEdge(1),fHistoInvMass->GetBinLowEdge(fHistoInvMass->GetNbinsX()+1)); fgauss->SetParameter(0,fRawYield*fHistoInvMass->GetBinWidth(1)); fgauss->SetParameter(1,fMass); fgauss->SetParameter(2,fSigmaSgn); fgauss->SetLineColor(kBlue); hResidualTrend->GetListOfFunctions()->Add(fgauss); } } if(hPullsTrend){ hPullsTrend->GetXaxis()->SetRange(binmi,binma); hPullsTrend->SetMinimum(-7); hPullsTrend->SetMaximum(+7); } if(TMath::Abs(min)>TMath::Abs(max))max=min; TH1F *hout=new TH1F(Form(""%s_residuals"",fHistoInvMass->GetName()),Form(""%s ; residuals"",fHistoInvMass->GetTitle()),25,-TMath::Abs(max)*1.5,TMath::Abs(max)*1.5); for(Int_t j=0;jFill(arval->At(j)); } hout->Sumw2(); hout->Fit(""gaus"",""LEM"","""",-TMath::Abs(max)*1.2,TMath::Abs(max)*1.2); if(hPulls){ hPulls->Sumw2(); hPulls->Fit(""gaus"",""LEM"","""",-3,3); } delete arval; return hout; } // _______________________________________________________________________ TH1F* AliHFInvMassFitter::GetOverBackgroundResidualsAndPulls(TH1 *hPulls,TH1 *hResidualTrend,TH1 *hPullsTrend, Double_t minrange,Double_t maxrange){ /// return GetResidualsAndPulls(hPulls,hResidualTrend,hPullsTrend,minrange,maxrange,1); } // _______________________________________________________________________ TH1F* AliHFInvMassFitter::GetOverBackgroundPlusReflResidualsAndPulls(TH1 *hPulls,TH1 *hResidualTrend,TH1 *hPullsTrend, Double_t minrange,Double_t maxrange){ /// return GetResidualsAndPulls(hPulls,hResidualTrend,hPullsTrend,minrange,maxrange,2); } // _______________________________________________________________________ void AliHFInvMassFitter::PrintFunctions(){ /// dump the function parameters /// if(fBkgFunc){ printf(""--- Background function in 1st step fit to side bands ---\\n""); fBkgFunc->Print(); } if(fTotFunc){ printf(""--- Total fit function from 2nd step fit ---\\n""); fTotFunc->Print(); } if(fBkgFuncRefit){ printf(""--- Background function in 2nd step fit ---\\n""); fBkgFuncRefit->Print(); } if(fRflFunc){ printf(""--- Reflections ---\\n""); fRflFunc->Print(); } if(fBkRFunc){ printf(""--- Background + reflections ---\\n""); fBkRFunc->Print(); } if(fSecFunc){ printf(""--- Additional Gaussian peak ---\\n""); fSecFunc->Print(); } } ",16154,True,2748.544651479742,median "// Copyright 2017 the original author or authors. // // 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. [[native_software]] = Building native software [CAUTION] ==== The https://blog.gradle.org/state-and-future-of-the-gradle-software-model[software model] is being retired and the plugins mentioned in this chapter will eventually be deprecated and removed. We recommend new projects looking to build C++ applications and libraries use the newer <>. ==== The native software plugins add support for building native software components, such as executables or shared libraries, from code written in C++, C and other languages. While many excellent build tools exist for this space of software development, Gradle offers developers its trademark power and flexibility together with dependency management practices more traditionally found in the JVM development space. The native software plugins make use of the Gradle <>. [[sec:native_features]] == Features The native software plugins provide: * Support for building native libraries and applications on Windows, Linux, macOS and other platforms. * Support for several source languages. * Support for building different variants of the same software, for different architectures, operating systems, or for any purpose. * Incremental parallel compilation, precompiled headers. * Dependency management between native software components. * Unit test execution. * Generate Visual studio solution and project files. * Deep integration with various tool chain, including discovery of installed tool chains. [[sec:supported_languages]] == Supported languages The following source languages are currently supported: * C * C++ * Objective-C * Objective-C++ * Assembly * Windows resources [[native-binaries:tool-chain-support]] == Tool chain support Gradle offers the ability to execute the same build using different tool chains. When you build a native binary, Gradle will attempt to locate a tool chain installed on your machine that can build the binary. You can fine tune exactly how this works, see <<#native_binaries:tool_chain,Tool chain support>> for details. The following tool chains are supported: [%header%autowidth,compact] |=== | Operating System | Tool Chain | Notes | Linux | http://gcc.gnu.org/[GCC] | | Linux | http://clang.llvm.org[Clang] | | macOS | XCode | Uses the Clang tool chain bundled with XCode. | Windows | https://visualstudio.microsoft.com/[Visual C++] | Windows XP and later, Visual C++ 2010/2012/2013/2015/2017/2019. | Windows | http://gcc.gnu.org/[GCC] with http://cygwin.com[Cygwin 32 and Cygwin 64] | Windows XP and later. | Windows | http://gcc.gnu.org/[GCC] with http://www.mingw.org/[MinGW] and https://mingw-w64.org/doku.php[MinGW64] | Windows XP and later. |=== The following tool chains are unofficially supported. They generally work fine, but are not tested continuously: [%header%autowidth,compact] |=== | Operating System | Tool Chain | Notes | macOS | http://gcc.gnu.org/[GCC] from Macports | | macOS | http://clang.llvm.org[Clang] from Macports | | UNIX-like | http://gcc.gnu.org/[GCC] | | UNIX-like | http://clang.llvm.org[Clang] | |=== [[sec:tool_chain_installation]] == Tool chain installation [NOTE] ==== Note that if you are using GCC then you currently need to install support for C+\\+, even if you are not building from C++ source. This restriction will be removed in a future Gradle version. ==== To build native software, you will need to have a compatible tool chain installed: [[sec:windows]] === Windows To build on Windows, install a compatible version of Visual Studio. The native plugins will discover the Visual Studio installations and select the latest version. There is no need to mess around with environment variables or batch scripts. This works fine from a Cygwin shell or the Windows command-line. Alternatively, you can install Cygwin with GCC or MinGW. Clang is currently not supported. [[sec:macOS]] === macOS To build on macOS, you should install XCode. The native plugins will discover the XCode installation using the system PATH. The native plugins also work with GCC and Clang bundled with Macports. To use one of the Macports tool chains, you will need to make the tool chain the default using the `port select` command and add Macports to the system PATH. [[sec:linux]] === Linux To build on Linux, install a compatible version of GCC or Clang. The native plugins will discover GCC or Clang using the system PATH. [[sec:native_software_model]] == Native software model The native software model builds on the base Gradle <>. To build native software using Gradle, your project should define one or more _native components_. Each component represents either an executable or a library that Gradle should build. A project can define any number of components. Gradle does not define any components by default. For each component, Gradle defines a _source set_ for each language that the component can be built from. A source set is essentially just a set of source directories containing source files. For example, when you apply the `c` plugin and define a library called `helloworld`, Gradle will define, by default, a source set containing the C source files in the `src/helloworld/c` directory. It will use these source files to build the `helloworld` library. This is described in more detail below. For each component, Gradle defines one or more _binaries_ as output. To build a binary, Gradle will take the source files defined for the component, compile them as appropriate for the source language, and link the result into a binary file. For an executable component, Gradle can produce executable binary files. For a library component, Gradle can produce both static and shared library binary files. For example, when you define a library called `helloworld` and build on Linux, Gradle will, by default, produce `libhelloworld.so` and `libhelloworld.a` binaries. In many cases, more than one binary can be produced for a component. These binaries may vary based on the tool chain used to build, the compiler/linker flags supplied, the dependencies provided, or additional source files provided. Each native binary produced for a component is referred to as a _variant_. Binary variants are discussed in detail below. [[sec:parallel_compilation]] == Parallel Compilation Gradle uses the single build worker pool to concurrently compile and link native components, by default. No special configuration is required to enable concurrent building. By default, the worker pool size is determined by the number of available processors on the build machine (as reported to the build JVM). To explicitly set the number of workers use the `--max-workers` command-line option or `org.gradle.workers.max` system property. There is generally no need to change this setting from its default. The build worker pool is shared across all build tasks. This means that when using <>, the maximum number of concurrent individual compilation operations does not increase. For example, if the build machine has 4 processing cores and 10 projects are compiling in parallel, Gradle will only use 4 total workers, not 40. [[sec:building_a_library]] == Building a library To build either a static or shared native library, you define a library component in the `components` container. The following sample defines a library called `hello`: === Example: Defining a library component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/c/groovy/build.gradle[tag=libraries] ---- A library component is represented using link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec]. Each library component can produce at least one shared library binary (link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec]) and at least one static library binary (link:{javadocPath}/org/gradle/nativeplatform/StaticLibraryBinarySpec.html[StaticLibraryBinarySpec]). [[sec:building_an_executable]] == Building an executable To build a native executable, you define an executable component in the `components` container. The following sample defines an executable called `main`: === Example: Defining executable components [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/c/groovy/build.gradle[tag=executables] ---- An executable component is represented using link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec]. Each executable component can produce at least one executable binary (link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec]). For each component defined, Gradle adds a link:{javadocPath}/org/gradle/language/base/FunctionalSourceSet.html[FunctionalSourceSet] with the same name. Each of these functional source sets will contain a language-specific source set for each of the languages supported by the project. [[sec:dependents]] == Assembling or building dependents Sometimes, you may need to _assemble_ (compile and link) or _build_ (compile, link and test) a component or binary and its _dependents_ (things that depend upon the component or binary). The native software model provides tasks that enable this capability. First, the _dependent components_ report gives insight about the relationships between each component. Second, the _build and assemble dependents_ tasks allow you to assemble or build a component and its dependents in one step. In the following example, the build file defines `OpenSSL` as a dependency of `libUtil` and `libUtil` as a dependency of `LinuxApp` and `WindowsApp`. Test suites are treated similarly. Dependents can be thought of as reverse dependencies. .Dependent Components Example image::nativeDependents.png[] [NOTE] ==== By following the dependencies backwards, you can see `LinuxApp` and `WindowsApp` are _dependents_ of `libUtil`. When `libUtil` is changed, Gradle will need to recompile or relink `LinuxApp` and `WindowsApp`. ==== When you _assemble_ dependents of a component, the component and all of its dependents are compiled and linked, including any test suite binaries. Gradle's up-to-date checks are used to only compile or link if something has changed. For instance, if you have changed source files in a way that do not affect the headers of your project, Gradle will be able to skip compilation for dependent components and only need to re-link with the new library. Tests are not run when assembling a component. When you _build_ dependents of a component, the component and all of its dependent binaries are compiled, linked _and checked_. Checking components means running any <<#sec:check_tasks,check task>> including executing any test suites, so tests _are_ run when building a component. In the following sections, we will demonstrate the usage of the `assembleDependents\\*`, `buildDependents*` and `dependentComponents` tasks with a sample build that contains a CUnit test suite. The build script for the sample is the following: === Example: Sample build [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cunit/groovy/build.gradle[tag=terse-example] ---- [[sec:dependents_report]] === Dependent components report Gradle provides a report that you can run from the command-line that shows a graph of components in your project and components that depend upon them. The following is an example of running `gradle dependentComponents` on the sample project: === Example: Dependent components report .Output of **`gradle dependentComponents`** ---- > gradle dependentComponents include::{snippetsPath}/native-binaries/cunit/tests/dependentComponentsReport.out ---- [NOTE] ==== See link:{groovyDslPath}/org.gradle.api.reporting.dependents.DependentComponentsReport.html[DependentComponentsReport] API documentation for more details. ==== By default, non-buildable binaries and test suites are hidden from the report. The `dependentComponents` task provides options that allow you to see all dependents by using the `--all` option: === Example: Dependent components report .Output of **`gradle dependentComponents --all`** ---- > gradle dependentComponents --all include::{snippetsPath}/native-binaries/cunit/tests/dependentComponentsReportAll.out ---- Here is the corresponding report for the `operators` component, showing dependents of all its binaries: === Example: Report of components that depends on the operators component .Output of **`gradle dependentComponents --component operators`** ---- > gradle dependentComponents --component operators include::{snippetsPath}/native-binaries/cunit/tests/assembleDependentComponentsReport.out ---- Here is the corresponding report for the `operators` component, showing dependents of all its binaries, including test suites: === Example: Report of components that depends on the operators component, including test suites .Output of **`gradle dependentComponents --test-suites --component operators`** ---- > gradle dependentComponents --test-suites --component operators include::{snippetsPath}/native-binaries/cunit/tests/buildDependentComponentsReport.out ---- [[sec:assemble_dependents]] === Assembling dependents For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec], Gradle will create a task named `assembleDependents__${component.name}${binary.variant}__` that _assembles_ (compile and link) the binary and all of its dependent binaries. For each link:{javadocPath}/org/gradle/nativeplatform/NativeComponentSpec.html[NativeComponentSpec], Gradle will create a task named `assembleDependents__${component.name}__` that _assembles_ all the binaries of the component and all of their dependent binaries. For example, to assemble the dependents of the ""passing"" flavor of the ""static"" library binary of the ""operators"" component, you would run the `assembleDependentsOperatorsPassingStaticLibrary` task: === Example: Assemble components that depends on the passing/static binary of the operators component .Output of **`gradle assembleDependentsOperatorsPassingStaticLibrary --max-workers=1`** ---- > gradle assembleDependentsOperatorsPassingStaticLibrary --max-workers=1 include::{snippetsPath}/native-binaries/cunit/tests/assembleDependentComponents.out ---- In the output above, the targeted binary gets assembled as well as the test suite binary that depends on it. You can also assemble _all_ of the dependents of a component (i.e. of all its binaries/variants) using the corresponding component task, e.g. `assembleDependentsOperators`. This is useful if you have many combinations of build types, flavors and platforms and want to assemble all of them. [[sec:build_dependents]] === Building dependents For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec], Gradle will create a task named `buildDependents__${component.name}${binary.variant}__` that _builds_ (compile, link and check) the binary and all of its dependent binaries. For each link:{javadocPath}/org/gradle/nativeplatform/NativeComponentSpec.html[NativeComponentSpec], Gradle will create a task named `buildDependents__${component.name}__` that _builds_ all the binaries of the component and all of their dependent binaries. For example, to build the dependents of the ""passing"" flavor of the ""static"" library binary of the ""operators"" component, you would run the `buildDependentsOperatorsPassingStaticLibrary` task: === Example: Build components that depends on the passing/static binary of the operators component .Output of **`gradle buildDependentsOperatorsPassingStaticLibrary --max-workers=1`** ---- > gradle buildDependentsOperatorsPassingStaticLibrary --max-workers=1 include::{snippetsPath}/native-binaries/cunit/tests/buildDependentComponents.out ---- In the output above, the targeted binary as well as the test suite binary that depends on it are built and the test suite has run. You can also build _all_ of the dependents of a component (i.e. of all its binaries/variants) using the corresponding component task, e.g. `buildDependentsOperators`. [[sec:native_tasks]] == Tasks For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] that can be produced by a build, a single _lifecycle task_ is constructed that can be used to create that binary, together with a set of other tasks that do the actual work of compiling, linking or assembling the binary. `__${component.name}__Executable`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec] Location of created binary;; `__${project.buildDir}__/exe/__${component.name}__/__${component.name}__` `__${component.name}__SharedLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] Location of created binary;; `__${project.buildDir}__/libs/__${component.name}__/shared/lib__${component.name}__.so` `__${component.name}__StaticLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/StaticLibraryBinarySpec.html[StaticLibraryBinarySpec] Location of created binary;; `__${project.buildDir}__/libs/__${component.name}__/static/__${component.name}__.a` [[sec:check_tasks]] === Check tasks For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] that can be produced by a build, a single _check task_ is constructed that can be used to assemble and check that binary. `check__${component.name}__Executable`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableBinarySpec.html[NativeExecutableBinarySpec] `check__${component.name}__SharedLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] `check__${component.name}__StaticLibrary`:: Component Type;; link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] Native Binary Type;; link:{javadocPath}/org/gradle/nativeplatform/SharedLibraryBinarySpec.html[SharedLibraryBinarySpec] The built-in `check` task depends on all the _check tasks_ for binaries in the project. Without either <<#native_binaries:cunit,CUnit>> or <<#native_binaries:google_test,GoogleTest>> plugins, the binary check task only depends on the _lifecycle task_ that assembles the binary, see <<#sec:native_tasks,Native tasks>>. When the <<#native_binaries:cunit,CUnit>> or <<#native_binaries:google_test,GoogleTest>> plugins are applied, the task that executes the test suites for a component are automatically wired to the appropriate _check task_. You can also add custom check tasks as follows: === Example: Adding a custom check task [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/custom-check/groovy/build.gradle[tag=custom-check] ---- Now, running `check` or any of the _check tasks_ for the `hello` binaries will run the custom check task: === Example: Running checks for a given binary .Output of **`gradle checkHelloSharedLibrary`** ---- > gradle checkHelloSharedLibrary include::{snippetsPath}/native-binaries/custom-check/tests/nativeComponentCustomCheckOutput.out ---- [[sec:working_with_shared_libraries]] === Working with shared libraries For each executable binary produced, the `cpp` plugin provides an `install${binary.name}` task, which creates a development install of the executable, along with the shared libraries it requires. This allows you to run the executable without needing to install the shared libraries in their final locations. [[sec:finding_out_more_about_your_project]] == Finding out more about your project Gradle provides a report that you can run from the command-line that shows some details about the components and binaries that your project produces. To use this report, just run `gradle components`. Below is an example of running this report for one of the sample projects: === Example: The components report .Output of **`gradle components`** ---- > gradle components include::{snippetsPath}/native-binaries/cpp/tests/nativeComponentReport.out ---- [[native_binaries:languages]] == Language support Presently, Gradle supports building native software from any combination of source languages listed below. A native binary project will contain one or more named `FunctionalSourceSet` instances (e.g. 'main', 'test', etc), each of which can contain ``LanguageSourceSet``s containing source files, one for each language. * C * C++ * Objective-C * Objective-C++ * Assembly * Windows resources [[sec:cpp_sources]] === C++ sources C++ language support is provided by means of the `'cpp'` plugin. === Example: The 'cpp' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cpp/groovy/build.gradle[tag=apply-plugin] ---- $$C++$$ sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet], which defines a set of C++ source files and optionally a set of exported header files (for a library). By default, for any named component the link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet] contains `.cpp` source files in `src/${name}/cpp`, and header files in `src/${name}/headers`. While the `cpp` plugin defines these default locations for each link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet], it is possible to extend or override these defaults to allow for a different project layout. === Example: C++ source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippetsPath}/native-binaries/custom-layout/groovy/build.gradle[tag=cpp-sources] ---- For a library named 'main', header files in `src/main/headers` are considered the ""public"" or ""exported"" headers. Header files that should not be exported should be placed inside the `src/main/cpp` directory (though be aware that such header files should always be referenced in a manner relative to the file including them). [[sec:c_sources]] === C sources C language support is provided by means of the `'c'` plugin. === Example: The 'c' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/c/groovy/build.gradle[tag=apply-plugin] ---- C sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet], which defines a set of C source files and optionally a set of exported header files (for a library). By default, for any named component the link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet] contains `.c` source files in `src/${name}/c`, and header files in `src/${name}/headers`. While the `c` plugin defines these default locations for each link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet], it is possible to extend or override these defaults to allow for a different project layout. === Example: C source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippetsPath}/native-binaries/custom-layout/groovy/build.gradle[tag=c-sources] ---- For a library named 'main', header files in `src/main/headers` are considered the ""public"" or ""exported"" headers. Header files that should not be exported should be placed inside the `src/main/c` directory (though be aware that such header files should always be referenced in a manner relative to the file including them). [[sec:assembler_sources]] === Assembler sources Assembly language support is provided by means of the `'assembler'` plugin. === Example: The 'assembler' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/assembler/groovy/build.gradle[tag=apply-plugin] ---- Assembler sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.assembler.AssemblerSourceSet.html[AssemblerSourceSet], which defines a set of Assembler source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.assembler.AssemblerSourceSet.html[AssemblerSourceSet] contains `.s` source files under `src/${name}/asm`. [[sec:objectivec_sources]] === Objective-C sources Objective-C language support is provided by means of the `'objective-c'` plugin. === Example: The 'objective-c' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/objective-c/groovy/build.gradle[tag=apply-plugin] ---- Objective-C sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.objectivec.ObjectiveCSourceSet.html[ObjectiveCSourceSet], which defines a set of Objective-C source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.objectivec.ObjectiveCSourceSet.html[ObjectiveCSourceSet] contains `.m` source files under `src/${name}/objectiveC`. [[sec:objectivecpp_sources]] === Objective-C++ sources Objective-C++ language support is provided by means of the `'objective-cpp'` plugin. === Example: The 'objective-cpp' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/objective-cpp/groovy/build.gradle[tag=apply-plugin] ---- Objective-C$$++$$ sources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.objectivecpp.ObjectiveCppSourceSet.html[ObjectiveCppSourceSet], which defines a set of Objective-C++ source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.objectivecpp.ObjectiveCppSourceSet.html[ObjectiveCppSourceSet] contains `.mm` source files under `src/${name}/objectiveCpp`. [[sec:configuring_the_compiler_assembler_and_linker]] == Configuring the compiler, assembler and linker Each binary to be produced is associated with a set of compiler and linker settings, which include command-line arguments as well as macro definitions. These settings can be applied to all binaries, an individual binary, or selectively to a group of binaries based on some criteria. === Example: Settings that apply to all binaries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cpp/groovy/build.gradle[tag=all-binaries] ---- Each binary is associated with a particular link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain], allowing settings to be targeted based on this value. It is easy to apply settings to all binaries of a particular type: === Example: Settings that apply to all shared libraries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/c/groovy/build.gradle[tag=all-shared-libraries] ---- Furthermore, it is possible to specify settings that apply to all binaries produced for a particular `executable` or `library` component: === Example: Settings that apply to all binaries produced for the 'main' executable component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/assembler/groovy/build.gradle[tag=assembler-args] ---- The example above will apply the supplied configuration to all `executable` binaries built. Similarly, settings can be specified to target binaries for a component that are of a particular type: e.g. all shared libraries for the main library component. === Example: Settings that apply only to shared libraries produced for the 'main' library component [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cpp-lib/groovy/build.gradle[tag=args] ---- [[native_binaries:windows-resources]] == Windows Resources When using the link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.VisualCpp.html[VisualCpp] tool chain, Gradle is able to compile Window Resource (`rc`) files and link them into a native binary. This functionality is provided by the `'windows-resources'` plugin. === Example: The 'windows-resources' plugin [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/windows-resources/groovy/build.gradle[tag=apply-plugin] ---- Windows resources to be included in a native binary are provided via a link:{groovyDslPath}/org.gradle.language.rc.WindowsResourceSet.html[WindowsResourceSet], which defines a set of Windows Resource source files. By default, for any named component the link:{groovyDslPath}/org.gradle.language.rc.WindowsResourceSet.html[WindowsResourceSet] contains `.rc` source files under `src/${name}/rc`. As with other source types, you can configure the location of the windows resources that should be included in the binary. === Example: Configuring the location of Windows resource sources [source.multi-language-sample,groovy,indent=0] .build-resource-only-dll.gradle ---- include::{snippetsPath}/native-binaries/windows-resources/groovy/build-resource-only-dll.gradle[tag=windows-resource-set] ---- You are able to construct a resource-only library by providing Windows Resource sources with no other language sources, and configure the linker as appropriate: === Example: Building a resource-only dll [source.multi-language-sample,groovy] .build-resource-only-dll.gradle ---- include::{snippetsPath}/native-binaries/windows-resources/groovy/build-resource-only-dll.gradle[tag=resource-only-library] ---- The example above also demonstrates the mechanism of passing extra command-line arguments to the resource compiler. The `rcCompiler` extension is of type link:{javadocPath}/org/gradle/nativeplatform/PreprocessingTool.html[PreprocessingTool]. [[sec:library_dependencies]] == Library Dependencies Dependencies for native components are binary libraries that export header files. The header files are used during compilation, with the compiled binary dependency being used during linking and execution. Header files should be organized into subdirectories to prevent clashes of commonly named headers. For instance, if your `mylib` project has a `logging.h` header, it will make it less likely the wrong header is used if you include it as `""mylib/logging.h""` instead of `""logging.h""`. [[sec:dependencies_within_the_same_project]] === Dependencies within the same project A set of sources may depend on header files provided by another binary component within the same project. A common example is a native executable component that uses functions provided by a separate native library component. Such a library dependency can be added to a source set associated with the `executable` component: === Example: Providing a library dependency to the source set [source.multi-language-sample,groovy,indent=0] .build.gradle ---- include::{snippetsPath}/native-binaries/cpp/groovy/build.gradle[tag=source-library] ---- Alternatively, a library dependency can be provided directly to the `NativeExecutableBinarySpec` for the `executable`. === Example: Providing a library dependency to the binary [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/custom-layout/groovy/build.gradle[tag=binary-library] ---- [[sec:project_dependencies]] === Project Dependencies For a component produced in a different Gradle project, the notation is similar. === Example: Declaring project dependencies [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/multi-project/groovy/build.gradle[tag=project-dependencies] ---- [[native_binaries:preCompiledHeaders]] == Precompiled Headers Precompiled headers are a performance optimization that reduces the cost of compiling widely used headers multiple times. This feature _precompiles_ a header such that the compiled object file can be reused when compiling each source file rather than recompiling the header each time. This support is available for C, C+\\+, Objective-C, and Objective-C++ builds. To configure a precompiled header, first a header file needs to be defined that includes all of the headers that should be precompiled. It must be specified as the first included header in every source file where the precompiled header should be used. It is assumed that this header file, and any headers it contains, make use of header guards so that they can be included in an idempotent manner. If header guards are not used in a header file, it is possible the header could be compiled more than once and could potentially lead to a broken build. === Example: Creating a precompiled header file [source.multi-language-sample,c] .src/hello/headers/pch.h ---- include::{snippetsPath}/native-binaries/pre-compiled-headers/groovy/src/hello/headers/pch.h[] ---- === Example: Including a precompiled header file in a source file [source.multi-language-sample,cpp] .src/hello/cpp/hello.cpp ---- include::{snippetsPath}/native-binaries/pre-compiled-headers/groovy/src/hello/cpp/hello.cpp[] ---- Precompiled headers are specified on a source set. Only one precompiled header file can be specified on a given source set and will be applied to all source files that declare it as the first include. If a source files does not include this header file as the first header, the file will be compiled in the normal manner (without making use of the precompiled header object file). The string provided should be the same as that which is used in the ""#include"" directive in the source files. === Example: Configuring a precompiled header [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/pre-compiled-headers/groovy/build.gradle[tag=libraries] ---- A precompiled header must be included in the same way for all files that use it. Usually, this means the header file should exist in the source set ""headers"" directory or in a directory included on the compiler include path. [[native_binaries:variants]] == Native Binary Variants For each executable or library defined, Gradle is able to build a number of different native binary variants. Examples of different variants include debug vs release binaries, 32-bit vs 64-bit binaries, and binaries produced with different custom preprocessor flags. Binaries produced by Gradle can be differentiated on <<#native_binaries:build_type,build type>>, <<#native_binaries:platform,platform>>, and <<#native_binaries:flavor,flavor>>. For each of these 'variant dimensions', it is possible to specify a set of available values as well as target each component at one, some or all of these. For example, a plugin may define a range of support platforms, but you may choose to only target Windows-x86 for a particular component. [[native_binaries:build_type]] === Build types A `build type` determines various non-functional aspects of a binary, such as whether debug information is included, or what optimisation level the binary is compiled with. Typical build types are 'debug' and 'release', but a project is free to define any set of build types. === Example: Defining build types [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/variants/groovy/build.gradle[tag=build-types] ---- If no build types are defined in a project, then a single, default build type called 'debug' is added. For a build type, a Gradle project will typically define a set of compiler/linker flags per tool chain. === Example: Configuring debug binaries [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/variants/groovy/build.gradle[tag=build-type-config] ---- [NOTE] ==== At this stage, it is completely up to the build script to configure the relevant compiler/linker flags for each build type. Future versions of Gradle will automatically include the appropriate debug flags for any 'debug' build type, and may be aware of various levels of optimisation as well. ==== [[native_binaries:platform]] === Platform An executable or library can be built to run on different operating systems and cpu architectures, with a variant being produced for each platform. Gradle defines each OS/architecture combination as a link:{groovyDslPath}/org.gradle.nativeplatform.platform.NativePlatform.html[NativePlatform], and a project may define any number of platforms. If no platforms are defined in a project, then a single, default platform 'current' is added. [NOTE] ==== Presently, a `Platform` consists of a defined operating system and architecture. As we continue to develop the native binary support in Gradle, the concept of Platform will be extended to include things like C-runtime version, Windows SDK, ABI, etc. Sophisticated builds may use the extensibility of Gradle to apply additional attributes to each platform, which can then be queried to specify particular includes, preprocessor macros or compiler arguments for a native binary. ==== === Example: Defining platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/variants/groovy/build.gradle[tag=platforms] ---- For a given variant, Gradle will attempt to find a link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain] that is able to build for the target platform. Available tool chains are searched in the order defined. See the <<#native_binaries:tool_chain,tool chains>> section below for more details. [[native_binaries:flavor]] === Flavor Each component can have a set of named `flavors`, and a separate binary variant can be produced for each flavor. While the `build type` and `target platform` variant dimensions have a defined meaning in Gradle, each project is free to define any number of flavors and apply meaning to them in any way. An example of component flavors might differentiate between 'demo', 'paid' and 'enterprise' editions of the component, where the same set of sources is used to produce binaries with different functions. === Example: Defining flavors [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/flavors/groovy/build.gradle[tag=flavors] ---- In the example above, a library is defined with a 'english' and 'french' flavor. When compiling the 'french' variant, a separate macro is defined which leads to a different binary being produced. If no flavor is defined for a component, then a single default flavor named 'default' is used. [[sec:selecting_the_build_types_platforms_and_flavors_for_a_component]] === Selecting the build types, platforms and flavors for a component For a default component, Gradle will attempt to create a native binary variant for each and every combination of `buildType` and `flavor` defined for the project. It is possible to override this on a per-component basis, by specifying the set of `targetBuildTypes` and/or `targetFlavors`. By default, Gradle will build for the default platform, see <<#native_binaries:platform,above>>, unless specified explicitly on a per-component basis by specifying a set of `targetPlatforms`. === Example: Targeting a component at particular platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/variants/groovy/build.gradle[tag=target-platforms] ---- Here you can see that the link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetPlatform(java.lang.String)[TargetedNativeComponent.targetPlatform(java.lang.String)] method is used to specify a platform that the `NativeExecutableSpec` named `main` should be built for. A similar mechanism exists for selecting link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetBuildTypes(java.lang.String++[]++)[TargetedNativeComponent.targetBuildTypes(java.lang.String...)] and link:{groovyDslPath}/org.gradle.nativeplatform.TargetedNativeComponent.html#org.gradle.nativeplatform.TargetedNativeComponent:targetFlavors(java.lang.String++[]++)[TargetedNativeComponent.targetFlavors(java.lang.String...)]. [[sec:building_all_possible_variants]] === Building all possible variants When a set of build types, target platforms, and flavors is defined for a component, a link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] model element is created for every possible combination of these. However, in many cases it is not possible to build a particular variant, perhaps because no tool chain is available to build for a particular platform. If a binary variant cannot be built for any reason, then the link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] associated with that variant will not be `buildable`. It is possible to use this property to create a task to generate all possible variants on a particular machine. === Example: Building all possible variants [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/tool-chains/groovy/build.gradle[tag=buildable] ---- [[native_binaries:tool_chain]] == Tool chains A single build may utilize different tool chains to build variants for different platforms. To this end, the core 'native-binary' plugins will attempt to locate and make available supported tool chains. However, the set of tool chains for a project may also be explicitly defined, allowing additional cross-compilers to be configured as well as allowing the install directories to be specified. [[sec:defining_tool_chains]] === Defining tool chains The supported tool chain types are: * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Gcc.html[Gcc] * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Clang.html[Clang] * link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.VisualCpp.html[VisualCpp] === Example: Defining tool chains [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/tool-chains/groovy/build.gradle[tag=toolChains] ---- Each tool chain implementation allows for a certain degree of configuration (see the API documentation for more details). [[sec:using_tool_chains]] === Using tool chains It is not necessary or possible to specify the tool chain that should be used to build. For a given variant, Gradle will attempt to locate a link:{javadocPath}/org/gradle/nativeplatform/toolchain/NativeToolChain.html[NativeToolChain] that is able to build for the target platform. Available tool chains are searched in the order defined. [NOTE] ==== When a platform does not define an architecture or operating system, the default target of the tool chain is assumed. So if a platform does not define a value for `operatingSystem`, Gradle will find the first available tool chain that can build for the specified `architecture`. ==== The core Gradle tool chains are able to target the following architectures out of the box. In each case, the tool chain will target the current operating system. See the next section for information on cross-compiling for other operating systems. [cols=""a,a"", options=""header""] |=== | Tool Chain | Architectures | GCC | x86, x86_64 | Clang | x86, x86_64 | Visual C++ | x86, x86_64, ia-64 |=== So for GCC running on linux, the supported target platforms are 'linux/x86' and 'linux/x86_64'. For GCC running on Windows via Cygwin, platforms 'windows/x86' and 'windows/x86_64' are supported. (The Cygwin POSIX runtime is not yet modelled as part of the platform, but will be in the future.) If no target platforms are defined for a project, then all binaries are built to target a default platform named 'current'. This default platform does not specify any `architecture` or `operatingSystem` value, hence using the default values of the first available tool chain. Gradle provides a _hook_ that allows the build author to control the exact set of arguments passed to a tool chain executable. This enables the build author to work around any limitations in Gradle, or assumptions that Gradle makes. The arguments hook should be seen as a 'last-resort' mechanism, with preference given to truly modelling the underlying domain. === Example: Reconfigure tool arguments [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/tool-chains/groovy/build.gradle[tag=withArguments] ---- [[sec:crosscompiling_with_gcc]] === Cross-compiling with GCC Cross-compiling is possible with the link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Gcc.html[Gcc] and link:{groovyDslPath}/org.gradle.nativeplatform.toolchain.Clang.html[Clang] tool chains, by adding support for additional target platforms. This is done by specifying a target platform for a toolchain. For each target platform a custom configuration can be specified. === Example: Defining target platforms [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/target-platforms/groovy/build.gradle[tag=targetplatforms] ---- [[native_binaries:visual_studio]] == Visual Studio IDE integration Gradle has the ability to generate Visual Studio project and solution files for the native components defined in your build. This ability is added by the `visual-studio` plugin. For a multi-project build, all projects with native components (and the root project) should have this plugin applied. When the `visual-studio` plugin is applied to the root project, a task named `visualStudio` is created, which will generate a Visual Studio solution file containing all components in the build. This solution will include a Visual Studio project for each component, as well as configuring each component to build using Gradle. A task named `openVisualStudio` is also created by the `visual-studio` plugin when the project is the root project. This task generates the Visual Studio solution and then opens the solution in Visual Studio. This means you can simply run `gradlew openVisualStudio` from the root project to generate and open the Visual Studio solution in one convenient step. The content of the generated visual studio files can be modified via API hooks, provided by the `visualStudio` extension. Take a look at the 'visual-studio' sample, or see link:{groovyDslPath}/org.gradle.ide.visualstudio.VisualStudioExtension.html#org.gradle.ide.visualstudio.VisualStudioExtension:projects[VisualStudioExtension.getProjects()] and link:{groovyDslPath}/org.gradle.ide.visualstudio.VisualStudioRootExtension.html#org.gradle.ide.visualstudio.VisualStudioRootExtension:solution[VisualStudioRootExtension.getSolution()] in the API documentation for more details. [[native_binaries:cunit]] == CUnit support The Gradle `cunit` plugin provides support for compiling and executing CUnit tests in your native-binary project. For each link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] and link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] defined in your project, Gradle will create a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component, named `${component.name}Test`. [[sec:cunit_sources]] === CUnit sources Gradle will create a link:{groovyDslPath}/org.gradle.language.c.CSourceSet.html[CSourceSet] named 'cunit' for each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component in the project. This source set should contain the cunit test files for the component under test. Source files can be located in the conventional location (`src/${component.name}Test/cunit`) or can be configured like any other source set. Gradle initialises the CUnit test registry and executes the tests, utilising some generated CUnit launcher sources. Gradle will expect and call a function with the signature `void gradle_cunit_register()` that you can use to configure the actual CUnit suites and tests to execute. === Example: Registering CUnit tests [source.multi-language-sample,c] .suite_operators.c ---- include::{snippetsPath}/native-binaries/cunit/groovy/src/operatorsTest/c/suite_operators.c[] ---- [NOTE] ==== Due to this mechanism, your CUnit sources may not contain a `main` method since this will clash with the method provided by Gradle. ==== [[sec:building_cunit_executables]] === Building CUnit executables A link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteSpec.html[CUnitTestSuiteSpec] component has an associated link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] or link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] component. For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] configured for the main component, a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec] will be configured on the test suite component. These test suite binaries can be configured in a similar way to any other binary instance: === Example: Configuring CUnit tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cunit/groovy/build.gradle[tag=configure-test-binary] ---- [NOTE] ==== Both the CUnit sources provided by your project and the generated launcher require the core CUnit headers and libraries. Presently, this library dependency must be provided by your project for each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec]. ==== [[sec:running_cunit_tests]] === Running CUnit tests For each link:{groovyDslPath}/org.gradle.nativeplatform.test.cunit.CUnitTestSuiteBinarySpec.html[CUnitTestSuiteBinarySpec], Gradle will create a task to execute this binary, which will run all of the registered CUnit tests. Test results will be found in the `__${build.dir}__/test-results` directory. === Example: Running CUnit tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/cunit/groovy/build.gradle[tag=complete-example] ---- .Output of `gradle -q runOperatorsTestFailingCUnitExe` ---- > gradle -q runOperatorsTestFailingCUnitExe include::{snippetsPath}/native-binaries/cunit/tests/completeCUnitExample.out ---- [NOTE] ==== The current support for CUnit is quite rudimentary. Plans for future integration include: * Allow tests to be declared with Javadoc-style annotations. * Improved HTML reporting, similar to that available for JUnit. * Real-time feedback for test execution. * Support for additional test frameworks. ==== [[native_binaries:google_test]] == GoogleTest support The Gradle `google-test` plugin provides support for compiling and executing GoogleTest tests in your native-binary project. For each link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] and link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] defined in your project, Gradle will create a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component, named `${component.name}Test`. [[sec:googletest_sources]] === GoogleTest sources Gradle will create a link:{groovyDslPath}/org.gradle.language.cpp.CppSourceSet.html[CppSourceSet] named 'cpp' for each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component in the project. This source set should contain the GoogleTest test files for the component under test. Source files can be located in the conventional location (`src/${component.name}Test/cpp`) or can be configured like any other source set. [[sec:building_googletest_executables]] === Building GoogleTest executables A link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteSpec.html[GoogleTestTestSuiteSpec] component has an associated link:{javadocPath}/org/gradle/nativeplatform/NativeExecutableSpec.html[NativeExecutableSpec] or link:{javadocPath}/org/gradle/nativeplatform/NativeLibrarySpec.html[NativeLibrarySpec] component. For each link:{javadocPath}/org/gradle/nativeplatform/NativeBinarySpec.html[NativeBinarySpec] configured for the main component, a matching link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec] will be configured on the test suite component. These test suite binaries can be configured in a similar way to any other binary instance: === Example: Registering GoogleTest tests [source.multi-language-sample,groovy] .build.gradle ---- include::{snippetsPath}/native-binaries/google-test/groovy/build.gradle[tag=configure-test-binary] ---- [NOTE] ==== The GoogleTest sources provided by your project require the core GoogleTest headers and libraries. Presently, this library dependency must be provided by your project for each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec]. ==== [[sec:running_googletest_tests]] === Running GoogleTest tests For each link:{groovyDslPath}/org.gradle.nativeplatform.test.googletest.GoogleTestTestSuiteBinarySpec.html[GoogleTestTestSuiteBinarySpec], Gradle will create a task to execute this binary, which will run all of the registered GoogleTest tests. Test results will be found in the `__${build.dir}__/test-results` directory. [NOTE] ==== The current support for GoogleTest is quite rudimentary. Plans for future integration include: * Improved HTML reporting, similar to that available for JUnit. * Real-time feedback for test execution. * Support for additional test frameworks. ==== ",12164,False,2305.896381964016,median "/* DEMO: demoScene TEAM a.r.g.: http://www.team-arg.com 2015 - JO3RI Game License: MIT : https://opensource.org/licenses/MIT */ //determine the game #include #include ""Arglib.h"" #include ""menu_bitmaps.h"" #include ""font.h"" #include ""ATMlib.h"" SQUAWK_CONSTRUCT_ISR(SQUAWK_PWM_PIN5) extern Melody TEAMargSong[]; byte rotatingFrame[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; byte stillStar[11][2] = {{84, 9}, {67, 14}, {109, 19}, {27, 24}, {9, 29}, {96, 34}, {31, 39}, {45, 44}, {82, 49}, {19, 54}, {57, 59}}; byte movingStar[11][2] = {{16, 5}, {125, 10}, {62, 15}, {79, 20}, {115, 25}, {104, 30}, {16, 35}, {117, 40}, {65, 45}, {98, 50}, {23, 55}}; byte fastMovingStar[11][2] = {{84, 7}, {67, 12}, {109, 17}, {27, 22}, {9, 27}, {96, 32}, {31, 37}, {45, 42}, {82, 47}, {19, 52}, {57, 57}}; const unsigned char PROGMEM demoText[] = ""Hello Arduboy Here we are again with a brand new demo. Do you wanna hear a tune on the DEV kit? connect a piezo at 2 sides of the right button. DON'T PRESS THAT BUTTON! let's say hi to some people ! Greetings to @castpixel @lexaloffle @bateskecom and all TEAM a.r.g. members. If you're still reading this, you must have way to much time. ""; int scrolling = 128; int timeDemo; Arduboy arduboy; extern Melody TEAMargSong[]; void setup() { arduboy.start(); arduboy.setFrameRate(60); arduboy.drawCompressed(0, 0, TEAMarg, WHITE); arduboy.display(); delay(3000); Squawk.begin(32000); // Begin playback of melody. Squawk.play(TEAMargSong); // Tune the song to something more suitable for a piezo Squawk.tune(2.0); // Lower the tempo ever so slightly Squawk.tempo(50); timeDemo = sizeof(demoText); } void loop() { while (scrolling > -(timeDemo*13)) { if (!(arduboy.nextFrame())) return; arduboy.clearDisplay(); drawStarField(); drawSwirl(); drawScrollingText(); arduboy.display(); } if (!(arduboy.nextFrame())) return; arduboy.clearDisplay(); drawGoPlay(); arduboy.display(); } void drawSwirl() { if (arduboy.everyXFrames(3)) { for (byte x; x < 16; x++) { rotatingFrame[x]++; } } for (byte x; x < 16; x++) { if (rotatingFrame[x] > 20) rotatingFrame[x] = 0; arduboy.drawSprite(8 * x, 48, reverseRotating_bitmaps, 8, 16, rotatingFrame[x], WHITE); } } void drawStarField() { for (byte i = 0; i < 11; i++) { if (arduboy.everyXFrames(2)) { fastMovingStar[i][0]--; if (fastMovingStar[i][0] < 1) fastMovingStar[i][0] = 127; } if (arduboy.everyXFrames(3)) { movingStar[i][0]--; if (movingStar[i][0] < 1) movingStar[i][0] = 127; } if (arduboy.everyXFrames(4)) { stillStar[i][0]--; if (stillStar[i][0] < 1) stillStar[i][0] = 127; } arduboy.drawPixel(movingStar[i][0], movingStar[i][1], WHITE); arduboy.drawPixel(fastMovingStar[i][0], fastMovingStar[i][1], WHITE); arduboy.drawPixel(stillStar[i][0], stillStar[i][1], WHITE); } } void drawScrollingText() { if (arduboy.everyXFrames(1)) scrolling--; for (int textX = 0; textX < sizeof(demoText) - 1; textX++) { if ((scrolling + 13 * textX < 128) && (scrolling + 13 * textX > -32)) { arduboy.drawSprite(scrolling + 13 * textX, 20, font_bitmaps, 22, 24, pgm_read_byte(&demoText[textX]) - 32, WHITE); } } } void drawGoPlay() { arduboy.drawCompressed(0, 0, TEAMarg2, WHITE); } Melody TEAMargSong[] = { 0x41, 0x02, 0x00, 0x01, 0x40, 0x00, 0x82, 0x00, 0x5C, 0x00, 0x7F, 0xB2, 0xB7, 0x40, 0x00, 0x00, 0x00, 0x47, 0x00, 0x7F, 0xB4, 0xBC, 0x4A, 0x07, 0x00, 0x0C, 0x08, 0x00, 0xB4, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x47, 0x00, 0x7F, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0xB0, 0xB7, 0xB7, 0x6A, 0x07, 0x04, 0x0A, 0x07, 0x00, 0x7F, 0x7F, 0xB0, 0x40, 0x00, 0x00, 0x00, 0x59, 0x00, 0x7F, 0xB7, 0xB7, 0x60, 0x00, 0x04, 0x00, 0x47, 0x00, 0x7F, 0x7F, 0xBC, 0x6A, 0x07, 0x02, 0x0C, 0x08, 0x00, 0xB7, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x47, 0x00, 0x7F, 0x7F, 0x7F, 0x6A, 0x07, 0x02, 0x00, 0x47, 0x00, 0xB4, 0x7F, 0x7F, 0x6A, 0x07, 0x02, 0x00, 0x47, 0x00, 0x7F, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x4C, 0x00, 0xB0, 0xB9, 0xB7, 0x4A, 0x07, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0xBB, 0x6A, 0x07, 0x02, 0x00, 0x38, 0x00, 0xAB, 0x7F, 0x7F, 0x6A, 0x07, 0x02, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x0C, 0x08, 0x00, 0xB7, 0xB7, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x60, 0x00, 0x02, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x60, 0x00, 0x02, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0xAF, 0xB2, 0xB7, 0x4A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0x7F, 0x7F, 0xB2, 0x4A, 0x07, 0x00, 0x00, 0x47, 0x00, 0xAB, 0xB0, 0xB7, 0xCA, 0x07, 0x09, 0x00, 0x38, 0x00, 0x7F, 0xB2, 0xBB, 0x4A, 0x07, 0x00, 0x0C, 0x08, 0x00, 0xB7, 0xB2, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x38, 0x00, 0x7F, 0xB4, 0x7F, 0x40, 0x00, 0x00, 0x00, 0x47, 0x00, 0x7F, 0xB2, 0xB7, 0xC0, 0x00, 0x09, 0x00, 0x38, 0x00, 0x7F, 0xB4, 0xBB, 0x1A, 0x07, 0x03, 0x00, 0x2C, 0x00, 0xAF, 0xAF, 0xB7, 0x3A, 0x07, 0x08, 0x00, 0x5A, 0x00, 0x7F, 0xB0, 0xB9, 0x3A, 0x07, 0x00, 0x00, 0x5A, 0x00, 0xAD, 0x7F, 0x7F, 0x6A, 0x07, 0x02, 0x00, 0x5A, 0x00, 0x7F, 0x7F, 0x7F, 0x60, 0x00, 0x00, 0x00, 0x5C, 0x00, 0x7F, 0xAB, 0xB9, 0x60, 0x00, 0x01, 0x00, 0x37, 0x00, 0x7F, 0xAD, 0xBE, 0x6A, 0x07, 0x01, 0x0C, 0x08, 0x00, 0xB5, 0xB0, 0x7F, 0x6A, 0x07, 0x02, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0x7F, 0x6A, 0x07, 0x02, 0x0A, 0x07, 0x00, 0xB2, 0xAD, 0xB9, 0x6A, 0x07, 0x03, 0x0A, 0x07, 0x00, 0x7F, 0x7F, 0xB2, 0x60, 0x00, 0x03, 0x00, 0x58, 0x00, 0x7F, 0xAB, 0xB9, 0x60, 0x00, 0x04, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0xBE, 0x6A, 0x07, 0x04, 0x0C, 0x08, 0x00, 0xB9, 0xA8, 0x7F, 0x6A, 0x07, 0x05, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0x7F, 0x6A, 0x07, 0x05, 0x00, 0x37, 0x00, 0xB5, 0xA6, 0x7F, 0x6A, 0x07, 0x06, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0x7F, 0x6A, 0x07, 0x06, 0x00, 0x3C, 0x00, 0xB2, 0xA4, 0xB9, 0x6A, 0x07, 0x07, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0xBC, 0x6A, 0x07, 0x07, 0x00, 0x49, 0x00, 0xAF, 0xA6, 0x7F, 0x6A, 0x07, 0x07, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x1A, 0x07, 0x07, 0x0C, 0x08, 0x00, 0xB9, 0xA6, 0x7F, 0x3A, 0x07, 0x0F, 0x00, 0x49, 0x00, 0x7F, 0xA8, 0x7F, 0x30, 0x00, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x30, 0x00, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x3A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0xB0, 0x7F, 0xB9, 0x3A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0x7F, 0x7F, 0xB4, 0x4A, 0x07, 0x00, 0x00, 0x37, 0x00, 0xAD, 0xAB, 0xB9, 0x4A, 0x07, 0x00, 0x00, 0x49, 0x00, 0x7F, 0xAD, 0xBC, 0x6A, 0x07, 0x02, 0x0C, 0x08, 0x00, 0xB9, 0x7F, 0x7F, 0x6A, 0x07, 0x02, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x40, 0x00, 0x00, 0x00, 0x37, 0x00, 0x7F, 0xA8, 0xB9, 0xC0, 0x00, 0x09, 0x00, 0x49, 0x00, 0x7F, 0xAD, 0xBC, 0x1A, 0x07, 0x07, 0x00, 0x2C, 0x00, 0xB0, 0xA9, 0xB9, 0x3A, 0x07, 0x0F, 0x00, 0x58, 0x00, 0x7F, 0xAB, 0xBB, 0x30, 0x00, 0x00, 0x00, 0x58, 0x00, 0x7F, 0x7F, 0x7F, 0x3C, 0x08, 0x00, 0x00, 0x58, 0x00, 0x7F, 0x7F, 0x7F, 0x40, 0x00, 0x82, 0x00, 0x5C, 0x00, 0x7F, 0x7F, 0xB7, 0x40, 0x00, 0x00, 0x00, 0x47, 0x00, 0x7F, 0x7F, 0xBC, 0x6A, 0x07, 0x02, 0x0C, 0x08, 0x00, 0xB4, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x47, 0x00, 0x7F, 0x7F, 0x7F, 0x6A, 0x07, 0x02, 0x0A, 0x07, 0x00, 0xB0, 0x7F, 0xB7, 0x6A, 0x07, 0x02, 0x0A, 0x07, 0x00, 0x7F, 0x7F, 0xB0, 0x10, 0x00, 0x07, 0x00, 0x59, 0x00, 0x7F, 0xB2, 0xB7, 0x30, 0x00, 0x0F, 0x00, 0x47, 0x00, 0x7F, 0xB4, 0xBC, 0x3A, 0x07, 0x00, 0x0C, 0x08, 0x00, 0xB7, 0x7F, 0x7F, 0x3A, 0x07, 0x00, 0x00, 0x47, 0x00, 0x7F, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x47, 0x00, 0xB4, 0xB0, 0x7F, 0xCA, 0x07, 0x09, 0x00, 0x47, 0x00, 0x7F, 0xB4, 0x7F, 0x1A, 0x07, 0x03, 0x00, 0x4C, 0x00, 0xB0, 0xB0, 0xB7, 0x3A, 0x07, 0x0F, 0x00, 0x38, 0x00, 0x7F, 0xB2, 0xBB, 0x3A, 0x07, 0x00, 0x00, 0x38, 0x00, 0xAB, 0x7F, 0x7F, 0x3A, 0x07, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x0C, 0x08, 0x00, 0xB7, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x40, 0x00, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x40, 0x00, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x6A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0xAF, 0x7F, 0xB7, 0x6A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0x7F, 0x7F, 0xB2, 0x6A, 0x07, 0x00, 0x00, 0x47, 0x00, 0xAB, 0x7F, 0xB7, 0x6A, 0x07, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0xBB, 0x6A, 0x07, 0x00, 0x0C, 0x08, 0x00, 0xB7, 0x7F, 0x7F, 0x6A, 0x07, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0x7F, 0x60, 0x00, 0x00, 0x00, 0x47, 0x00, 0x7F, 0x7F, 0xB7, 0x60, 0x00, 0x00, 0x00, 0x38, 0x00, 0x7F, 0x7F, 0xBB, 0x4A, 0x07, 0x00, 0x00, 0x2C, 0x00, 0xAF, 0xB4, 0xB7, 0x4A, 0x07, 0x00, 0x00, 0x5A, 0x00, 0x7F, 0x7F, 0xB9, 0xCA, 0x07, 0x09, 0x00, 0x5A, 0x00, 0xAD, 0xB2, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x5A, 0x00, 0x7F, 0x7F, 0x7F, 0x40, 0x00, 0x00, 0x00, 0x5C, 0x00, 0x7F, 0xB0, 0xB9, 0x40, 0x00, 0x00, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0xBE, 0x3A, 0x07, 0x08, 0x0C, 0x08, 0x00, 0xB5, 0xAD, 0x7F, 0x3A, 0x07, 0x00, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0x7F, 0x3A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0xB2, 0x7F, 0xB9, 0x3A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0x7F, 0x7F, 0xB2, 0x30, 0x00, 0x00, 0x00, 0x58, 0x00, 0x7F, 0x7F, 0xB9, 0x30, 0x00, 0x00, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0xBE, 0x3A, 0x07, 0xFF, 0x0C, 0x08, 0x00, 0xB9, 0xAD, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x37, 0x00, 0xB5, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x3C, 0x00, 0xB2, 0x7F, 0xB9, 0x4A, 0x07, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0xBC, 0x4A, 0x07, 0x00, 0x00, 0x49, 0x00, 0xAF, 0x7F, 0x7F, 0x4A, 0x07, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x6A, 0x07, 0x00, 0x0C, 0x08, 0x00, 0xB9, 0x7F, 0x7F, 0x6A, 0x07, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x60, 0x00, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x60, 0x00, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x6A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0xB0, 0x7F, 0xB9, 0x6A, 0x07, 0x00, 0x0A, 0x07, 0x00, 0x7F, 0x7F, 0xB4, 0x6A, 0x07, 0x00, 0x00, 0x37, 0x00, 0xAD, 0x7F, 0xB9, 0x6A, 0x07, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0xBC, 0x6A, 0x07, 0x00, 0x0C, 0x08, 0x00, 0xB9, 0x7F, 0x7F, 0x6A, 0x07, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0x7F, 0x60, 0x00, 0x00, 0x00, 0x37, 0x00, 0x7F, 0x7F, 0xB9, 0x60, 0x00, 0x00, 0x00, 0x49, 0x00, 0x7F, 0x7F, 0xBC, 0x4A, 0x07, 0x00, 0x00, 0x2C, 0x00, 0xB0, 0xB0, 0xB9, 0x4A, 0x07, 0x00, 0x00, 0x58, 0x00, 0x7F, 0x7F, 0xBB, 0x40, 0x00, 0x00, 0x00, 0x58, 0x00, 0x7F, 0xB2, 0x7F, 0xCC, 0x08, 0x09, 0x00, 0x58, 0x00, 0x7F, 0xB0, 0x7F, }; ",8137,True,2645.3696130984576,median "/*========================================================================= Program: Visualization Toolkit Module: vtkCellLocator.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include ""vtkCellLocator.h"" #include ""vtkCellArray.h"" #include ""vtkGenericCell.h"" #include ""vtkMath.h"" #include ""vtkObjectFactory.h"" #include ""vtkPolyData.h"" #include ""vtkBox.h"" #include vtkStandardNewMacro(vtkCellLocator); #define VTK_CELL_OUTSIDE 0 #define VTK_CELL_INSIDE 1 typedef vtkIdList *vtkIdListPtr; //---------------------------------------------------------------------------- class vtkNeighborCells { public: vtkNeighborCells(const int sz, const int ext=1000) {this->P = vtkIntArray::New(); this->P->Allocate(3*sz,3*ext);}; ~vtkNeighborCells(){this->P->Delete();}; int GetNumberOfNeighbors() {return (this->P->GetMaxId()+1)/3;}; void Reset() {this->P->Reset();}; int *GetPoint(int i) {return this->P->GetPointer(3*i);}; int InsertNextPoint(int *x); protected: vtkIntArray *P; }; inline int vtkNeighborCells::InsertNextPoint(int *x) { int id = this->P->GetMaxId() + 3; this->P->InsertValue(id,x[2]); this->P->SetValue(id-2, x[0]); this->P->SetValue(id-1, x[1]); return id/3; } //---------------------------------------------------------------------------- // Construct with automatic computation of divisions, averaging // 25 cells per bucket. vtkCellLocator::vtkCellLocator() { this->MaxLevel = 8; this->Level = 8; this->NumberOfCellsPerNode = 25; this->Tree = nullptr; this->CellHasBeenVisited = nullptr; this->QueryNumber = 0; this->NumberOfDivisions = 1; this->H[0] = this->H[1] = this->H[2] = 1.0; this->Buckets = new vtkNeighborCells(10, 10); this->NumberOfOctants = 0; this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_DOUBLE_MAX; this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = VTK_DOUBLE_MIN; this->OctantBounds[0] = this->OctantBounds[2] = this->OctantBounds[4] = VTK_DOUBLE_MAX; this->OctantBounds[1] = this->OctantBounds[3] = this->OctantBounds[5] = VTK_DOUBLE_MIN; } //---------------------------------------------------------------------------- vtkCellLocator::~vtkCellLocator() { delete this->Buckets; this->Buckets = nullptr; this->FreeSearchStructure(); this->FreeCellBounds(); delete [] this->CellHasBeenVisited; this->CellHasBeenVisited = nullptr; } //---------------------------------------------------------------------------- void vtkCellLocator::FreeSearchStructure() { vtkIdList *cellIds; int i; if ( this->Tree ) { for (i=0; iNumberOfOctants; i++) { cellIds = this->Tree[i]; if (cellIds == reinterpret_cast(VTK_CELL_INSIDE)) { cellIds = nullptr; } if (cellIds) { cellIds->Delete(); } } delete [] this->Tree; this->Tree = nullptr; } } //---------------------------------------------------------------------------- // Given an offset into the structure, the number of divisions in the octree, // an i,j,k location in the octree; return the index (idx) into the structure. // Method returns 1 is the specified i,j,k location is ""outside"" of the octree. int vtkCellLocator::GenerateIndex(int offset, int numDivs, int i, int j, int k, vtkIdType &idx) { if ( i < 0 || i >= numDivs || j < 0 || j >= numDivs || k < 0 || k >= numDivs ) { return 1; } idx = offset + i + j*numDivs + k*numDivs*numDivs; return 0; } //---------------------------------------------------------------------------- void vtkCellLocator::ComputeOctantBounds(int i, int j, int k) { this->OctantBounds[0] = this->Bounds[0] + i*H[0]; this->OctantBounds[1] = this->OctantBounds[0] + H[0]; this->OctantBounds[2] = this->Bounds[2] + j*H[1]; this->OctantBounds[3] = this->OctantBounds[2] + H[1]; this->OctantBounds[4] = this->Bounds[4] + k*H[2]; this->OctantBounds[5] = this->OctantBounds[4] + H[2]; } //---------------------------------------------------------------------------- // Return intersection point (if any) AND the cell which was intersected by // finite line. // // NOTE: This method is not thread safe (i.e., when invoking this method on // the same instance of vtkCellLocator). This is the due to the use of the // data members QueryNumber and CellHasBeenVisited. These should be pulled // out of the class and made local to the appropriate methods that use // them. Since there may be a performance cost and possible effects on // output, this will be done TODO when more time is available. To see an // alternative implementation, see vtkStaticCellLocator which is thread safe. // int vtkCellLocator::IntersectWithLine(const double a0[3], const double a1[3], double tol, double& t, double x[3], double pcoords[3], int &subId, vtkIdType &cellId, vtkGenericCell *cell) { double origin[3]; double direction1[3]; double direction2[3]; double direction3[3]; double hitPosition[3]; double hitCellBoundsPosition[3], cellBounds[6]; double result; double bounds2[6]; int i, leafStart, prod, loop; vtkIdType bestCellId = -1, cId; int idx; double tMax, dist[3]; int npos[3]; int pos[3]; int bestDir; double stopDist, currDist; double deltaT, pDistance, minPDistance=1.0e38; double length, maxLength=0.0; this->BuildLocatorIfNeeded(); // convert the line into i,j,k coordinates tMax = 0.0; for (i=0; i < 3; i++) { direction1[i] = a1[i] - a0[i]; length = this->Bounds[2*i+1] - this->Bounds[2*i]; if ( length > maxLength ) { maxLength = length; } origin[i] = (a0[i] - this->Bounds[2*i]) / length; direction2[i] = direction1[i]/length; bounds2[2*i] = 0.0; bounds2[2*i+1] = 1.0; tMax += direction2[i]*direction2[i]; } tMax = sqrt(tMax); // create a parametric range around the tolerance deltaT = tol/maxLength; stopDist = tMax*this->NumberOfDivisions; for (i = 0; i < 3; i++) { direction3[i] = direction2[i]/tMax; } if (vtkBox::IntersectBox(bounds2, origin, direction2, hitPosition, result)) { // start walking through the octants prod = this->NumberOfDivisions*this->NumberOfDivisions; leafStart = this->NumberOfOctants - this->NumberOfDivisions*prod; bestCellId = -1; // Clear the array that indicates whether we have visited this cell. // The array is only cleared when the query number rolls over. This // saves a number of calls to memset. this->QueryNumber++; if (this->QueryNumber == 0) { this->ClearCellHasBeenVisited(); this->QueryNumber++; // can't use 0 as a marker } // set up curr and stop dist currDist = 0; for (i = 0; i < 3; i++) { currDist += (hitPosition[i] - origin[i])*(hitPosition[i] - origin[i]); } currDist = sqrt(currDist)*this->NumberOfDivisions; // add one offset due to the problems around zero for (loop = 0; loop <3; loop++) { hitPosition[loop] = hitPosition[loop]*this->NumberOfDivisions + 1.0; pos[loop] = static_cast(hitPosition[loop]); // Adjust right boundary condition: if we intersect from the top, right, // or back; then pos must be adjusted to a valid octant index if (pos[loop] > this->NumberOfDivisions) { pos[loop] = this->NumberOfDivisions; } } idx = leafStart + pos[0] - 1 + (pos[1] - 1)*this->NumberOfDivisions + (pos[2] - 1)*prod; while ((bestCellId < 0) && (pos[0] > 0) && (pos[1] > 0) && (pos[2] > 0) && (pos[0] <= this->NumberOfDivisions) && (pos[1] <= this->NumberOfDivisions) && (pos[2] <= this->NumberOfDivisions) && (currDist < stopDist)) { if (this->Tree[idx]) { this->ComputeOctantBounds(pos[0]-1,pos[1]-1,pos[2]-1); for (tMax = VTK_DOUBLE_MAX, cellId=0; cellId < this->Tree[idx]->GetNumberOfIds(); cellId++) { cId = this->Tree[idx]->GetId(cellId); if (this->CellHasBeenVisited[cId] != this->QueryNumber) { this->CellHasBeenVisited[cId] = this->QueryNumber; int hitCellBounds = 0; // check whether we intersect the cell bounds if (this->CacheCellBounds) { hitCellBounds = vtkBox::IntersectBox(this->CellBounds[cId], a0, direction1, hitCellBoundsPosition, result); } else { this->DataSet->GetCellBounds(cId, cellBounds); hitCellBounds = vtkBox::IntersectBox(cellBounds, a0, direction1, hitCellBoundsPosition, result); } if (hitCellBounds) { // now, do the expensive GetCell call and the expensive // intersect with line call this->DataSet->GetCell(cId, cell); if (cell->IntersectWithLine(a0, a1, tol, t, x, pcoords, subId) ) { if ( ! this->IsInOctantBounds(x, tol) ) { this->CellHasBeenVisited[cId] = 0; //mark the cell non-visited } else { if ( t < (tMax+deltaT) ) //it might be close { pDistance = cell->GetParametricDistance(pcoords); if ( pDistance < minPDistance || (pDistance == minPDistance && t < tMax) ) { tMax = t; minPDistance = pDistance; bestCellId = cId; } } //intersection point is in current octant } //if within current parametric range } // if intersection } // if (hitCellBounds) } // if (!this->CellHasBeenVisited[cId]) } } // move to the next octant tMax = VTK_DOUBLE_MAX; bestDir = 0; for (loop = 0; loop < 3; loop++) { if (direction3[loop] > 0) { npos[loop] = pos[loop] + 1; dist[loop] = (1.0 - hitPosition[loop] + pos[loop])/direction3[loop]; if (dist[loop] == 0) { dist[loop] = 1.0/direction3[loop]; } if (dist[loop] < 0) { dist[loop] = 0; } if (dist[loop] < tMax) { bestDir = loop; tMax = dist[loop]; } } if (direction3[loop] < 0) { npos[loop] = pos[loop] - 1; dist[loop] = (pos[loop] - hitPosition[loop])/direction3[loop]; if (dist[loop] == 0) { dist[loop] = -0.01/direction3[loop]; } if (dist[loop] < 0) { dist[loop] = 0; } if (dist[loop] < tMax) { bestDir = loop; tMax = dist[loop]; } } } // update our position for (loop = 0; loop < 3; loop++) { hitPosition[loop] += dist[bestDir]*direction3[loop]; } currDist += dist[bestDir]; // now make the move, find the smallest distance // only cross one boundary at a time pos[bestDir] = npos[bestDir]; idx = leafStart + pos[0] - 1 + (pos[1]-1)*this->NumberOfDivisions + (pos[2]-1)*prod; } } // if (vtkBox::IntersectBox(...)) if (bestCellId >= 0) { this->DataSet->GetCell(bestCellId, cell); cell->IntersectWithLine(a0, a1, tol, t, x, pcoords, subId); // store the best cell id in the return ""parameter"" cellId = bestCellId; return 1; } return 0; } //---------------------------------------------------------------------------- // Return closest point (if any) AND the cell on which this closest point lies void vtkCellLocator::FindClosestPoint(const double x[3], double closestPoint[3], vtkGenericCell *cell, vtkIdType &cellId, int &subId, double& dist2) { int i; vtkIdType j; int *nei; vtkIdType closestCell = -1; int closestSubCell = -1; int leafStart; int level; int ijk[3]; double minDist2, refinedRadius2, distance2ToBucket; double distance2ToCellBounds, cellBounds[6]; double pcoords[3], point[3], cachedPoint[3], weightsArray[6]; double *weights = weightsArray; int nWeights = 6, nPoints; vtkIdList *cellIds; int stat; //int minStat=0; //save this variable it is used for debugging this->BuildLocatorIfNeeded(); cachedPoint[0] = 0.0; cachedPoint[1] = 0.0; cachedPoint[2] = 0.0; leafStart = this->NumberOfOctants - this->NumberOfDivisions*this->NumberOfDivisions*this->NumberOfDivisions; // Clear the array that indicates whether we have visited this cell. // The array is only cleared when the query number rolls over. This // saves a number of calls to memset. this->QueryNumber++; if (this->QueryNumber == 0) { this->ClearCellHasBeenVisited(); this->QueryNumber++; // can't use 0 as a marker } // init dist2 = -1.0; refinedRadius2 = VTK_DOUBLE_MAX; // // Find bucket point is in. // for (j=0; j<3; j++) { ijk[j] = static_cast((x[j] - this->Bounds[2*j]) / this->H[j]); if (ijk[j] < 0) { ijk[j] = 0; } else if (ijk[j] >= this->NumberOfDivisions) { ijk[j] = this->NumberOfDivisions-1; } } // // Need to search this bucket for closest point. If there are no // cells in this bucket, search 1st level neighbors, and so on, // until closest point found. // for (closestCell=(-1),minDist2=VTK_DOUBLE_MAX,level=0; (closestCell == -1) && (level < this->NumberOfDivisions); level++) { this->GetBucketNeighbors(ijk, this->NumberOfDivisions, level); for (i=0; iBuckets->GetNumberOfNeighbors(); i++) { nei = this->Buckets->GetPoint(i); // if a neighboring bucket has cells, if ( (cellIds = this->Tree[leafStart + nei[0] + nei[1]*this->NumberOfDivisions + nei[2]*this->NumberOfDivisions*this->NumberOfDivisions]) != nullptr ) { // do we still need to test this bucket? distance2ToBucket = this->Distance2ToBucket(x, nei); if (distance2ToBucket < refinedRadius2) { // still a viable bucket for (j=0; j < cellIds->GetNumberOfIds(); j++) { // get the cell cellId = cellIds->GetId(j); if (this->CellHasBeenVisited[cellId] != this->QueryNumber) { this->CellHasBeenVisited[cellId] = this->QueryNumber; // check whether we could be close enough to the cell by // testing the cell bounds if (this->CacheCellBounds) { distance2ToCellBounds = this->Distance2ToBounds(x, this->CellBounds[cellId]); } else { this->DataSet->GetCellBounds(cellId, cellBounds); distance2ToCellBounds = this->Distance2ToBounds(x, cellBounds); } if (distance2ToCellBounds < refinedRadius2) { this->DataSet->GetCell(cellId, cell); // make sure we have enough storage space for the weights nPoints = cell->GetPointIds()->GetNumberOfIds(); if (nPoints > nWeights) { if (nWeights > 6) { delete [] weights; } weights = new double[2*nPoints]; // allocate some extra room nWeights = 2*nPoints; } // evaluate the position to find the closest point // stat==(-1) is numerical error; stat==0 means outside; // stat=1 means inside. However, for real world performance, // we sometime select stat==0 cells if the distance is close // enough stat = cell->EvaluatePosition(x, point, subId, pcoords, dist2, weights); if ( stat != -1 && dist2 < minDist2 ) // This commented out code works better in many cases // if ( stat != -1 && ((stat == minStat && dist2 < minDist2) || // (stat == 1 && minStat == 0)) ) { closestCell = cellId; closestSubCell = subId; minDist2 = dist2; cachedPoint[0] = point[0]; cachedPoint[1] = point[1]; cachedPoint[2] = point[2]; refinedRadius2 = dist2; // minStat = stat; } } } // if (!this->CellHasBeenVisited[cellId]) } } } } } // Because of the relative location of the points in the buckets, the // cell found previously may not be the closest cell. Have to // search those bucket neighbors that might also contain nearby cells. // if ( (minDist2 > 0.0) && (level < this->NumberOfDivisions)) { int prevMinLevel[3], prevMaxLevel[3]; // setup prevMinLevel and prevMaxLevel to indicate previously visited // buckets if (--level < 0) { level = 0; } for (i = 0; i < 3; i++) { prevMinLevel[i] = ijk[i] - level; if (prevMinLevel[i] < 0) { prevMinLevel[i] = 0; } prevMaxLevel[i] = ijk[i] + level; if (prevMaxLevel[i] >= this->NumberOfDivisions) { prevMaxLevel[i] = this->NumberOfDivisions - 1; } } this->GetOverlappingBuckets(x, ijk, sqrt(minDist2), prevMinLevel, prevMaxLevel); for (i=0; iBuckets->GetNumberOfNeighbors(); i++) { nei = this->Buckets->GetPoint(i); if ( (cellIds = this->Tree[leafStart + nei[0] + nei[1]*this->NumberOfDivisions + nei[2]*this->NumberOfDivisions*this->NumberOfDivisions]) != nullptr ) { // do we still need to test this bucket? distance2ToBucket = this->Distance2ToBucket(x, nei); if (distance2ToBucket < refinedRadius2) { // still a viable bucket for (j=0; j < cellIds->GetNumberOfIds(); j++) { // get the cell cellId = cellIds->GetId(j); if (this->CellHasBeenVisited[cellId] != this->QueryNumber) { this->CellHasBeenVisited[cellId] = this->QueryNumber; // check whether we could be close enough to the cell by // testing the cell bounds if (this->CacheCellBounds) { distance2ToCellBounds = this->Distance2ToBounds(x, this->CellBounds[cellId]); } else { this->DataSet->GetCellBounds(cellId, cellBounds); distance2ToCellBounds = this->Distance2ToBounds(x, cellBounds); } if (distance2ToCellBounds < refinedRadius2) { this->DataSet->GetCell(cellId, cell); // make sure we have enough storage space for the weights nPoints = cell->GetPointIds()->GetNumberOfIds(); if (nPoints > nWeights) { if (nWeights > 6) { delete [] weights; } weights = new double[2*nPoints]; // allocate some extra room nWeights = 2*nPoints; } // evaluate the position to find the closest point cell->EvaluatePosition(x, point, subId, pcoords, dist2, weights); if ( dist2 < minDist2 ) { closestCell = cellId; closestSubCell = subId; minDist2 = dist2; cachedPoint[0] = point[0]; cachedPoint[1] = point[1]; cachedPoint[2] = point[2]; refinedRadius2 = dist2; } }//if point close enough to cell bounds }//if cell has not been visited }//for each cell }//if bucket is still viable }//if cells in bucket }//for each overlapping bucket }//if not identical point if (closestCell != -1) { dist2 = minDist2; cellId = closestCell; subId = closestSubCell; closestPoint[0] = cachedPoint[0]; closestPoint[1] = cachedPoint[1]; closestPoint[2] = cachedPoint[2]; this->DataSet->GetCell(cellId, cell); } if (nWeights > 6) { delete [] weights; } } //---------------------------------------------------------------------------- vtkIdType vtkCellLocator::FindClosestPointWithinRadius(double x[3], double radius, double closestPoint[3], vtkGenericCell *cell, vtkIdType &cellId, int &subId, double& dist2, int &inside) { int i; vtkIdType j; int tmpInside; int *nei; int closestSubCell = -1; int leafStart; int ijk[3]; double pcoords[3], point[3], cachedPoint[3], weightsArray[6]; double *weights = weightsArray; int nWeights = 6, nPoints; int returnVal = 0; vtkIdList *cellIds; double distance2ToBucket; double distance2ToCellBounds, cellBounds[6], currentRadius; double distance2ToDataBounds, maxDistance; int ii, radiusLevels[3], radiusLevel, prevMinLevel[3], prevMaxLevel[3]; this->BuildLocatorIfNeeded(); cachedPoint[0] = 0.0; cachedPoint[1] = 0.0; cachedPoint[2] = 0.0; leafStart = this->NumberOfOctants - this->NumberOfDivisions*this->NumberOfDivisions*this->NumberOfDivisions; // Clear the array that indicates whether we have visited this cell. // The array is only cleared when the query number rolls over. This // saves a number of calls to memset. this->QueryNumber++; if (this->QueryNumber == 0) { this->ClearCellHasBeenVisited(); this->QueryNumber++; // can't use 0 as a marker } // init dist2 = -1.0; int closestCell = -1; double radius2 = radius*radius; double minDist2 = 1.1*radius2; // something slightly bigger.... double refinedRadius; double refinedRadius2 = radius2; // Find bucket point is in. // for (j=0; j<3; j++) { ijk[j] = static_cast((x[j] - this->Bounds[2*j]) / this->H[j]); if (ijk[j] < 0) { ijk[j] = 0; } else if (ijk[j] >= this->NumberOfDivisions) { ijk[j] = this->NumberOfDivisions-1; } } // Start by searching the bucket that the point is in. // if ((cellIds = this->Tree[leafStart + ijk[0] + ijk[1]*this->NumberOfDivisions + ijk[2]*this->NumberOfDivisions*this->NumberOfDivisions]) != nullptr ) { // query each cell for (j=0; j < cellIds->GetNumberOfIds(); j++) { // get the cell cellId = cellIds->GetId(j); if (this->CellHasBeenVisited[cellId] != this->QueryNumber) { this->CellHasBeenVisited[cellId] = this->QueryNumber; // check whether we could be close enough to the cell by // testing the cell bounds if (this->CacheCellBounds) { distance2ToCellBounds = this->Distance2ToBounds(x, this->CellBounds[cellId]); } else { this->DataSet->GetCellBounds(cellId, cellBounds); distance2ToCellBounds = this->Distance2ToBounds(x, cellBounds); } if (distance2ToCellBounds < refinedRadius2) { this->DataSet->GetCell(cellId, cell); // make sure we have enough storage space for the weights nPoints = cell->GetPointIds()->GetNumberOfIds(); if (nPoints > nWeights) { if (nWeights > 6) { delete [] weights; } weights = new double[2*nPoints]; // allocate some extra room nWeights = 2*nPoints; } // evaluate the position to find the closest point tmpInside = cell->EvaluatePosition(x, point, subId, pcoords, dist2, weights); if ( dist2 < minDist2 ) { inside = tmpInside; closestCell = cellId; closestSubCell = subId; minDist2 = dist2; cachedPoint[0] = point[0]; cachedPoint[1] = point[1]; cachedPoint[2] = point[2]; refinedRadius2 = dist2; } } } // if (this->CellHasBeenVisited[cellId]) } } // Now, search only those buckets that are within a radius. The radius used // is the smaller of sqrt(dist2) and the radius that is passed in. To avoid // checking a large number of buckets unnecessarily, if the radius is // larger than the dimensions of a bucket, we search outward using a // simple heuristic of rings. This heuristic ends up collecting inner // buckets multiple times, but this only happens in the case where these // buckets are empty, so they are discarded quickly. // if (dist2 < radius2 && dist2 >= 0.0) { refinedRadius = sqrt(dist2); refinedRadius2 = dist2; } else { refinedRadius = radius; refinedRadius2 = radius2; } distance2ToDataBounds = this->Distance2ToBounds(x, this->Bounds); maxDistance = sqrt(distance2ToDataBounds) + this->DataSet->GetLength(); if (refinedRadius > maxDistance) { refinedRadius = maxDistance; refinedRadius2 = maxDistance*maxDistance; } radiusLevels[0] = static_cast(refinedRadius/this->H[0]); radiusLevels[1] = static_cast(refinedRadius/this->H[1]); radiusLevels[2] = static_cast(refinedRadius/this->H[2]); radiusLevel = radiusLevels[0]; radiusLevel = radiusLevels[1] > radiusLevel ? radiusLevels[1] : radiusLevel; radiusLevel = radiusLevels[2] > radiusLevel ? radiusLevels[2] : radiusLevel; if (radiusLevel > this->NumberOfDivisions / 2 ) { radiusLevel = this->NumberOfDivisions / 2; } if (radiusLevel == 0) { radiusLevel = 1; } // radius schedule increases the radius each iteration, this is currently // implemented by decreasing ii by 1 each iteration. another alternative // is to double the radius each iteration, i.e. ii = ii >> 1 // In practice, reducing ii by one has been found to be more efficient. int numberOfBucketsPerPlane; numberOfBucketsPerPlane = this->NumberOfDivisions*this->NumberOfDivisions; prevMinLevel[0] = prevMaxLevel[0] = ijk[0]; prevMinLevel[1] = prevMaxLevel[1] = ijk[1]; prevMinLevel[2] = prevMaxLevel[2] = ijk[2]; for (ii=radiusLevel; ii >= 1; ii--) { currentRadius = refinedRadius; // used in if at bottom of this for loop // Build up a list of buckets that are arranged in rings this->GetOverlappingBuckets(x, ijk, refinedRadius/ii, prevMinLevel, prevMaxLevel); for (i=0; iBuckets->GetNumberOfNeighbors(); i++) { nei = this->Buckets->GetPoint(i); if ( (cellIds = this->Tree[leafStart + nei[0] + nei[1]*this->NumberOfDivisions + nei[2]*numberOfBucketsPerPlane]) != nullptr ) { // do we still need to test this bucket? distance2ToBucket = this->Distance2ToBucket(x, nei); if (distance2ToBucket < refinedRadius2) { // still a viable bucket for (j=0; j < cellIds->GetNumberOfIds(); j++) { // get the cell cellId = cellIds->GetId(j); if (this->CellHasBeenVisited[cellId] != this->QueryNumber) { this->CellHasBeenVisited[cellId] = this->QueryNumber; // check whether we could be close enough to the cell by // testing the cell bounds if (this->CacheCellBounds) { distance2ToCellBounds = this->Distance2ToBounds(x, this->CellBounds[cellId]); } else { this->DataSet->GetCellBounds(cellId, cellBounds); distance2ToCellBounds = this->Distance2ToBounds(x, cellBounds); } if (distance2ToCellBounds < refinedRadius2) { this->DataSet->GetCell(cellId, cell); // make sure we have enough storage space for the weights nPoints = cell->GetPointIds()->GetNumberOfIds(); if (nPoints > nWeights) { if (nWeights > 6) { delete [] weights; } weights = new double[2*nPoints]; // allocate some extra room nWeights = 2*nPoints; } // evaluate the position to find the closest point tmpInside = cell->EvaluatePosition(x, point, subId, pcoords, dist2, weights); if ( dist2 < minDist2 ) { inside = tmpInside; closestCell = cellId; closestSubCell = subId; minDist2 = dist2; cachedPoint[0] = point[0]; cachedPoint[1] = point[1]; cachedPoint[2] = point[2]; refinedRadius = sqrt(minDist2); refinedRadius2 = minDist2; } }//if point close enough to cell bounds }//if cell has not been visited }//for each cell in bucket }//if bucket is within the current best distance }//if cells in bucket }//for each overlapping bucket // don't want to checker a smaller radius than we just checked so update // ii appropriately if (refinedRadius < currentRadius && ii > 2) //always check ii==1 { ii = static_cast( static_cast(ii) * (refinedRadius / currentRadius)) + 1; if (ii < 2) { ii = 2; } } }//for each radius in the radius schedule if ((closestCell != -1) && (minDist2 <= radius2)) { dist2 = minDist2; cellId = closestCell; subId = closestSubCell; closestPoint[0] = cachedPoint[0]; closestPoint[1] = cachedPoint[1]; closestPoint[2] = cachedPoint[2]; this->DataSet->GetCell(cellId, cell); returnVal = 1; } if (nWeights > 6) { delete [] weights; } return returnVal; } //---------------------------------------------------------------------------- // Internal function to get bucket neighbors at specified ""level"". The // bucket neighbors are indices into the ""leaf-node"" layer of the octree. // These indices must be offset by number of octants before the leaf node // layer before they can be used. Only those buckets with cells are returned. // void vtkCellLocator::GetBucketNeighbors(int ijk[3], int ndivs, int level) { int i, j, k, min, max, minLevel[3], maxLevel[3]; int nei[3]; int leafStart; int numberOfBucketsPerPlane; this->BuildLocatorIfNeeded(); numberOfBucketsPerPlane = this->NumberOfDivisions*this->NumberOfDivisions; leafStart = this->NumberOfOctants - numberOfBucketsPerPlane*this->NumberOfDivisions; // Initialize // this->Buckets->Reset(); // If at this bucket, just place into list // if ( level == 0 ) { if (this->Tree[leafStart + ijk[0] + ijk[1]*this->NumberOfDivisions + ijk[2]*numberOfBucketsPerPlane]) { this->Buckets->InsertNextPoint(ijk); } return; } // Create permutations of the ijk indices that are at the level // required. If these are legal buckets, add to list for searching. // for ( i=0; i<3; i++ ) { min = ijk[i] - level; max = ijk[i] + level; minLevel[i] = ( min > 0 ? min : 0); maxLevel[i] = ( max < (ndivs-1) ? max : (ndivs-1)); } for ( k= minLevel[2]; k <= maxLevel[2]; k++ ) { for ( j= minLevel[1]; j <= maxLevel[1]; j++ ) { for ( i= minLevel[0]; i <= maxLevel[0]; i++ ) { if (i == (ijk[0] + level) || i == (ijk[0] - level) || j == (ijk[1] + level) || j == (ijk[1] - level) || k == (ijk[2] + level) || k == (ijk[2] - level) ) { if (this->Tree[leafStart + i + j*this->NumberOfDivisions + k*numberOfBucketsPerPlane]) { nei[0]=i; nei[1]=j; nei[2]=k; this->Buckets->InsertNextPoint(nei); } } } } } } //---------------------------------------------------------------------------- // Internal method to find those buckets that are within distance specified. // Only those buckets outside of level radiuses of ijk are returned. The // bucket neighbors are indices into the ""leaf-node"" layer of the octree. // These indices must be offset by number of octants before the leaf node // layer before they can be used. Only buckets that have cells are placed // in the bucket list. // void vtkCellLocator::GetOverlappingBuckets(const double x[3], int vtkNotUsed(ijk)[3], double dist, int prevMinLevel[3], int prevMaxLevel[3]) { int i, j, k, nei[3], minLevel[3], maxLevel[3]; int leafStart, kFactor, jFactor; int numberOfBucketsPerPlane, jkSkipFlag, kSkipFlag; this->BuildLocatorIfNeeded(); numberOfBucketsPerPlane = this->NumberOfDivisions*this->NumberOfDivisions; leafStart = this->NumberOfOctants - numberOfBucketsPerPlane*this->NumberOfDivisions; // Initialize this->Buckets->Reset(); // Determine the range of indices in each direction for (i=0; i < 3; i++) { minLevel[i] = static_cast (static_cast (((x[i]-dist) - this->Bounds[2*i]) / this->H[i])); maxLevel[i] = static_cast (static_cast (((x[i]+dist) - this->Bounds[2*i]) / this->H[i])); if ( minLevel[i] < 0 ) { minLevel[i] = 0; } else if (minLevel[i] >= this->NumberOfDivisions ) { minLevel[i] = this->NumberOfDivisions - 1; } if ( maxLevel[i] >= this->NumberOfDivisions ) { maxLevel[i] = this->NumberOfDivisions - 1; } else if ( maxLevel[i] < 0 ) { maxLevel[i] = 0; } } if (minLevel[0] == prevMinLevel[0] && maxLevel[0] == prevMaxLevel[0] && minLevel[1] == prevMinLevel[1] && maxLevel[1] == prevMaxLevel[1] && minLevel[2] == prevMinLevel[2] && maxLevel[2] == prevMaxLevel[2] ) { return; } for ( k= minLevel[2]; k <= maxLevel[2]; k++ ) { kFactor = k*numberOfBucketsPerPlane; if (k >= prevMinLevel[2] && k <= prevMaxLevel[2]) { kSkipFlag = 1; } else { kSkipFlag = 0; } for ( j= minLevel[1]; j <= maxLevel[1]; j++ ) { if (kSkipFlag && j >= prevMinLevel[1] && j <= prevMaxLevel[1]) { jkSkipFlag = 1; } else { jkSkipFlag = 0; } jFactor = j*this->NumberOfDivisions; for ( i= minLevel[0]; i <= maxLevel[0]; i++ ) { if ( jkSkipFlag && i == prevMinLevel[0] ) { i = prevMaxLevel[0]; continue; } // if this bucket has any cells, add it to the list if (this->Tree[leafStart + i + jFactor + kFactor]) { nei[0]=i; nei[1]=j; nei[2]=k; this->Buckets->InsertNextPoint(nei); } } } } prevMinLevel[0] = minLevel[0]; prevMinLevel[1] = minLevel[1]; prevMinLevel[2] = minLevel[2]; prevMaxLevel[0] = maxLevel[0]; prevMaxLevel[1] = maxLevel[1]; prevMaxLevel[2] = maxLevel[2]; } //---------------------------------------------------------------------------- // number of buckets available int vtkCellLocator::GetNumberOfBuckets() { if (this->Tree) { return this->NumberOfOctants; } else { vtkWarningMacro(<<""Attempting to access Tree before Locator has been built""); return 0; } } //---------------------------------------------------------------------------- // Get the cells in a bucket. vtkIdList* vtkCellLocator::GetCells(int octantId) { // handle parents ? return this->Tree[octantId]; } //--------------------------------------------------------------------------- void vtkCellLocator::BuildLocator() { if (this->LazyEvaluation) return; this->ForceBuildLocator(); } //--------------------------------------------------------------------------- void vtkCellLocator::BuildLocatorIfNeeded() { if (this->LazyEvaluation) { if (!this->Tree || (this->MTime>this->BuildTime)) { this->Modified(); vtkDebugMacro(<< ""Forcing BuildLocator""); this->ForceBuildLocator(); } } } //--------------------------------------------------------------------------- void vtkCellLocator::ForceBuildLocator() { // // don't rebuild if build time is newer than modified and dataset modified time if ( (this->Tree) && (this->BuildTime>this->MTime) && (this->BuildTime>DataSet->GetMTime())) { return; } // don't rebuild if UseExistingSearchStructure is ON and a tree structure already exists if ( (this->Tree) && this->UseExistingSearchStructure) { this->BuildTime.Modified(); vtkDebugMacro(<< ""BuildLocator exited - UseExistingSearchStructure""); return; } this->BuildLocatorInternal(); } //--------------------------------------------------------------------------- // Method to form subdivision of space based on the cells provided and // subject to the constraints of levels and NumberOfCellsPerNode. // The result is directly addressable and of uniform subdivision. // void vtkCellLocator::BuildLocatorInternal() { double length, cellBounds[6], *boundsPtr; vtkIdType numCells; int ndivs, product; int i, j, k, ijkMin[3], ijkMax[3]; vtkIdType cellId, idx; int parentOffset; vtkIdList *octant; int numCellsPerBucket = this->NumberOfCellsPerNode; int prod, numOctants; double hTol[3]; vtkDebugMacro( << ""Subdividing octree..."" ); if ( !this->DataSet || (numCells = this->DataSet->GetNumberOfCells()) < 1 ) { vtkErrorMacro( << ""No cells to subdivide""); return; } // Make sure the appropriate data is available // if ( this->Tree ) { this->FreeSearchStructure(); } delete [] this->CellHasBeenVisited; this->CellHasBeenVisited = nullptr; this->FreeCellBounds(); // Size the root cell. Initialize cell data structure, compute // level and divisions. // const double *bounds = this->DataSet->GetBounds(); length = this->DataSet->GetLength(); for (i=0; i<3; i++) { this->Bounds[2*i] = bounds[2*i]; this->Bounds[2*i+1] = bounds[2*i+1]; if ( (this->Bounds[2*i+1] - this->Bounds[2*i]) <= (length/1000.0) ) { // bump out the bounds a little of if min==max this->Bounds[2*i] -= length/100.0; this->Bounds[2*i+1] += length/100.0; } } if ( this->Automatic ) { this->Level = static_cast( ceil(log(static_cast(numCells)/numCellsPerBucket) / (log(static_cast(8.0))))); } this->Level =(this->Level > this->MaxLevel ? this->MaxLevel : this->Level); // compute number of octants and number of divisions for (ndivs=1,prod=1,numOctants=1,i=0; iLevel; i++) { ndivs *= 2; prod *= 8; numOctants += prod; } this->NumberOfDivisions = ndivs; this->NumberOfOctants = numOctants; this->Tree = new vtkIdListPtr[numOctants]; memset (this->Tree, 0, numOctants*sizeof(vtkIdListPtr)); this->CellHasBeenVisited = new unsigned char [ numCells ]; this->ClearCellHasBeenVisited(); this->QueryNumber = 0; if (this->CacheCellBounds) { this->StoreCellBounds(); } // Compute width of leaf octant in three directions // for (i=0; i<3; i++) { this->H[i] = (this->Bounds[2*i+1] - this->Bounds[2*i]) / ndivs; hTol[i] = this->H[i]/100.0; } // Insert each cell into the appropriate octant. Make sure cell // falls within octant. // parentOffset = numOctants - (ndivs * ndivs * ndivs); product = ndivs * ndivs; boundsPtr = cellBounds; for (cellId=0; cellIdCellBounds) { boundsPtr = this->CellBounds[cellId]; } else { this->DataSet->GetCellBounds(cellId, cellBounds); } // find min/max locations of bounding box for (i=0; i<3; i++) { ijkMin[i] = static_cast( (boundsPtr[2*i] - this->Bounds[2*i] - hTol[i])/ this->H[i]); ijkMax[i] = static_cast( (boundsPtr[2*i+1] - this->Bounds[2*i] + hTol[i]) / this->H[i]); if (ijkMin[i] < 0) { ijkMin[i] = 0; } if (ijkMax[i] >= ndivs) { ijkMax[i] = ndivs-1; } } // each octant between min/max point may have cell in it for ( k = ijkMin[2]; k <= ijkMax[2]; k++ ) { for ( j = ijkMin[1]; j <= ijkMax[1]; j++ ) { for ( i = ijkMin[0]; i <= ijkMax[0]; i++ ) { idx = parentOffset + i + j*ndivs + k*product; this->MarkParents(reinterpret_cast(VTK_CELL_INSIDE),i,j,k, ndivs,this->Level); octant = this->Tree[idx]; if ( ! octant ) { octant = vtkIdList::New(); octant->Allocate(numCellsPerBucket,numCellsPerBucket/2); this->Tree[idx] = octant; } octant->InsertNextId(cellId); } } } } //for all cells this->BuildTime.Modified(); } //---------------------------------------------------------------------------- void vtkCellLocator::MarkParents(void* a, int i, int j, int k, int ndivs, int level) { int offset, prod, ii; vtkIdType parentIdx; for (offset=0, prod=1, ii=0; ii 0 ) { i = i >> 1; j = j >> 1; k = k >> 1; ndivs = ndivs >> 1; level--; parentIdx = offset + i + j*ndivs + k*ndivs*ndivs; // if it already matches just return if (a == this->Tree[parentIdx]) { return; } this->Tree[parentIdx] = static_cast(a); prod = prod >> 3; offset -= prod; } } //---------------------------------------------------------------------------- void vtkCellLocator::GenerateRepresentation(int level, vtkPolyData *pd) { vtkPoints *pts; vtkCellArray *polys; int l, i, j, k, ii, boundary[3]; vtkIdType idx = 0; vtkIdList *inside, *Inside[3] = {nullptr, nullptr, nullptr}; int numDivs=1; this->BuildLocatorIfNeeded(); if ( this->Tree == nullptr ) { vtkErrorMacro(<<""No tree to generate representation from""); return; } pts = vtkPoints::New(); pts->Allocate(5000); polys = vtkCellArray::New(); polys->Allocate(10000); // Compute idx into tree at appropriate level; determine if // faces of octants are visible. // int parentIdx = 0; int numOctants = 1; if ( level < 0 ) { level = this->Level; } for (l=0; l < level; l++) { numDivs *= 2; parentIdx += numOctants; numOctants *= 8; } //loop over all octabts generating visible faces for ( k=0; k < numDivs; k++) { for ( j=0; j < numDivs; j++) { for ( i=0; i < numDivs; i++) { this->GenerateIndex(parentIdx,numDivs,i,j,k,idx); inside = this->Tree[idx]; if ( !(boundary[0]=this->GenerateIndex(parentIdx,numDivs,i-1,j,k,idx))) { Inside[0] = this->Tree[idx]; } if ( !(boundary[1]=this->GenerateIndex(parentIdx,numDivs,i,j-1,k,idx))) { Inside[1] = this->Tree[idx]; } if ( !(boundary[2]=this->GenerateIndex(parentIdx,numDivs,i,j,k-1,idx))) { Inside[2] = this->Tree[idx]; } for (ii=0; ii < 3; ii++) { if ( boundary[ii] ) { if ( inside ) { this->GenerateFace(ii,numDivs,i,j,k,pts,polys); } } else { if ( (Inside[ii] && !inside) || (!Inside[ii] && inside) ) { this->GenerateFace(ii,numDivs,i,j,k,pts,polys); } } //those buckets on ""positive"" boundaries can generate faces specially if ( (i+1) >= numDivs && inside ) { this->GenerateFace(0,numDivs,i+1,j,k,pts,polys); } if ( (j+1) >= numDivs && inside ) { this->GenerateFace(1,numDivs,i,j+1,k,pts,polys); } if ( (k+1) >= numDivs && inside ) { this->GenerateFace(2,numDivs,i,j,k+1,pts,polys); } }//over negative faces }//over i divisions }//over j divisions }//over k divisions pd->SetPoints(pts); pts->Delete(); pd->SetPolys(polys); polys->Delete(); pd->Squeeze(); } //---------------------------------------------------------------------------- void vtkCellLocator::GenerateFace(int face, int numDivs, int i, int j, int k, vtkPoints *pts, vtkCellArray *polys) { int ii; vtkIdType ids[4]; double origin[3], x[3]; double h[3]; // define first corner; use ids[] as temporary array ids[0] = i; ids[1] = j; ids[2] = k; for (ii=0; ii<3; ii++) { h[ii] = (this->Bounds[2*ii+1] - this->Bounds[2*ii]) / numDivs; origin[ii] = this->Bounds[2*ii] + ids[ii]*h[ii]; } ids[0] = pts->InsertNextPoint(origin); if ( face == 0 ) //x face { x[0] = origin[0]; x[1] = origin[1] + h[1]; x[2] = origin[2]; ids[1] = pts->InsertNextPoint(x); x[0] = origin[0]; x[1] = origin[1] + h[1]; x[2] = origin[2] + h[2]; ids[2] = pts->InsertNextPoint(x); x[0] = origin[0]; x[1] = origin[1]; x[2] = origin[2] + h[2]; ids[3] = pts->InsertNextPoint(x); } else if ( face == 1 ) //y face { x[0] = origin[0] + h[0]; x[1] = origin[1]; x[2] = origin[2]; ids[1] = pts->InsertNextPoint(x); x[0] = origin[0] + h[0]; x[1] = origin[1]; x[2] = origin[2] + h[2]; ids[2] = pts->InsertNextPoint(x); x[0] = origin[0]; x[1] = origin[1]; x[2] = origin[2] + h[2]; ids[3] = pts->InsertNextPoint(x); } else //z face { x[0] = origin[0] + h[0]; x[1] = origin[1]; x[2] = origin[2]; ids[1] = pts->InsertNextPoint(x); x[0] = origin[0] + h[0]; x[1] = origin[1] + h[1]; x[2] = origin[2]; ids[2] = pts->InsertNextPoint(x); x[0] = origin[0]; x[1] = origin[1] + h[1]; x[2] = origin[2]; ids[3] = pts->InsertNextPoint(x); } polys->InsertNextCell(4,ids); } //---------------------------------------------------------------------------- void vtkCellLocator::ClearCellHasBeenVisited() { if (this->CellHasBeenVisited && this->DataSet) { memset(this->CellHasBeenVisited, 0, this->DataSet->GetNumberOfCells()); } } //---------------------------------------------------------------------------- void vtkCellLocator::ClearCellHasBeenVisited(vtkIdType id) { if (this->CellHasBeenVisited && this->DataSet && id < this->DataSet->GetNumberOfCells()) { this->CellHasBeenVisited[id] = 0; } } //---------------------------------------------------------------------------- // Calculate the distance between the point x to the bucket ""nei"". // // WARNING!!!!! Be very careful altering this routine. Simple changes to this // routine can make is 25% slower!!!! // double vtkCellLocator::Distance2ToBucket(const double x[3], int nei[3]) { double bounds[6]; bounds[0] = nei[0]*this->H[0] + this->Bounds[0]; bounds[1] = (nei[0]+1)*this->H[0] + this->Bounds[0]; bounds[2] = nei[1]*this->H[1] + this->Bounds[2]; bounds[3] = (nei[1]+1)*this->H[1] + this->Bounds[2]; bounds[4] = nei[2]*this->H[2] + this->Bounds[4]; bounds[5] = (nei[2]+1)*this->H[2] + this->Bounds[4]; return this->Distance2ToBounds(x, bounds); } //---------------------------------------------------------------------------- // Calculate the distance between the point x and the specified bounds // // WARNING!!!!! Be very careful altering this routine. Simple changes to this // routine can make it 25% slower!!!! double vtkCellLocator::Distance2ToBounds(const double x[3], double bounds[6]) { double distance; double deltas[3]; // Are we within the bounds? if (x[0] >= bounds[0] && x[0] <= bounds[1] && x[1] >= bounds[2] && x[1] <= bounds[3] && x[2] >= bounds[4] && x[2] <= bounds[5]) { return 0.0; } deltas[0] = deltas[1] = deltas[2] = 0.0; // dx // if (x[0] < bounds[0]) { deltas[0] = bounds[0] - x[0]; } else if (x[0] > bounds[1]) { deltas[0] = x[0] - bounds[1]; } // dy // if (x[1] < bounds[2]) { deltas[1] = bounds[2] - x[1]; } else if (x[1] > bounds[3]) { deltas[1] = x[1] - bounds[3]; } // dz // if (x[2] < bounds[4]) { deltas[2] = bounds[4] - x[2]; } else if (x[2] > bounds[5]) { deltas[2] = x[2] - bounds[5]; } distance = vtkMath::Dot(deltas, deltas); return distance; } //---------------------------------------------------------------------------- static bool vtkCellLocator_Inside(const double bounds[6], const double point[3]) { if (point[0]bounds[1] || point[1]bounds[3] || point[2]bounds[5]) return false; return true; } //---------------------------------------------------------------------------- vtkIdType vtkCellLocator::FindCell( double x[3], double vtkNotUsed(tol2), vtkGenericCell *cell, double pcoords[3], double *weights) { vtkIdList *cellIds; int ijk[3]; int subId; double dist2; double cellBounds[6]; this->BuildLocatorIfNeeded(); int leafStart = this->NumberOfOctants - this->NumberOfDivisions*this->NumberOfDivisions*this->NumberOfDivisions; // Find bucket point is in. // for (int j=0; j<3; j++) { ijk[j] = static_cast((x[j] - this->Bounds[2*j]) / this->H[j]); if (ijk[j] < 0) { ijk[j] = 0; } else if (ijk[j] >= this->NumberOfDivisions) { ijk[j] = this->NumberOfDivisions-1; } } // Search the bucket that the point is in. // if ((cellIds = this->Tree[leafStart + ijk[0] + ijk[1]*this->NumberOfDivisions + ijk[2]*this->NumberOfDivisions*this->NumberOfDivisions]) != nullptr ) { // query each cell for (int j=0; j < cellIds->GetNumberOfIds(); j++) { // get the cell int cellId = cellIds->GetId(j); // check whether we could be close enough to the cell by // testing the cell bounds if (this->CacheCellBounds) { if (this->InsideCellBounds(x, cellId)) { this->DataSet->GetCell(cellId, cell); if (cell->EvaluatePosition(x, nullptr, subId, pcoords, dist2, weights)==1) { return cellId; } } } else { this->DataSet->GetCellBounds(cellId, cellBounds); if (vtkCellLocator_Inside(cellBounds, x)) { this->DataSet->GetCell(cellId, cell); if (cell->EvaluatePosition(x, nullptr, subId, pcoords, dist2, weights)==1) { return cellId; } } } } } return -1; } //---------------------------------------------------------------------------- void vtkCellLocator::FindCellsWithinBounds(double *bbox, vtkIdList *cells) { this->BuildLocatorIfNeeded(); cells->Reset(); // Get the locator locations for the two extreme corners of the bounding box double p1[3], p2[3], *p[2]; p1[0] = bbox[0]; p1[1] = bbox[2]; p1[2] = bbox[4]; p2[0] = bbox[1]; p2[1] = bbox[3]; p2[2] = bbox[5]; p[0] = p1; p[1] = p2; int ijk[2][3]; // Find bucket the points are in // int i, j, k; for (i=0; i<2; i++) { for (j=0; j<3; j++) { ijk[i][j] = static_cast((p[i][j] - this->Bounds[2*j]) / this->H[j]); if (ijk[i][j] < 0) { ijk[i][j] = 0; } else if (ijk[i][j] >= this->NumberOfDivisions) { ijk[i][j] = this->NumberOfDivisions-1; } } } // Now loop over block to load in ids int leafStart = this->NumberOfOctants - this->NumberOfDivisions*this->NumberOfDivisions*this->NumberOfDivisions; vtkIdList *cellIds; vtkIdType idx; for (k=ijk[0][2]; k <= ijk[1][2]; k++) { for (j=ijk[0][1]; j <= ijk[1][1]; j++) { for (i=ijk[0][0]; i <= ijk[1][0]; i++) { if ( (cellIds = this->Tree[leafStart + i + j*this->NumberOfDivisions + k*this->NumberOfDivisions*this->NumberOfDivisions]) != nullptr ) { for ( idx=0; idx < cellIds->GetNumberOfIds(); idx++) { cells->InsertUniqueId( cellIds->GetId(idx) ); } } } } } } //---------------------------------------------------------------------------- void vtkCellLocator::FindCellsAlongLine(const double p1[3], const double p2[3], double vtkNotUsed(tol), vtkIdList *cells) { this->BuildLocatorIfNeeded(); cells->Reset(); double origin[3]; double direction1[3]; double direction2[3]; double direction3[3]; double hitPosition[3]; double hitCellBoundsPosition[3], cellBounds[6]; int hitCellBounds; double result; double bounds2[6]; int i, leafStart, prod, loop; vtkIdType cellId, cId; int idx; double tMax, dist[3]; int npos[3]; int pos[3]; int bestDir; double stopDist, currDist; double length, maxLength=0.0; // convert the line into i,j,k coordinates tMax = 0.0; for (i=0; i < 3; i++) { direction1[i] = p2[i] - p1[i]; length = this->Bounds[2*i+1] - this->Bounds[2*i]; if ( length > maxLength ) { maxLength = length; } origin[i] = (p1[i] - this->Bounds[2*i]) / length; direction2[i] = direction1[i]/length; bounds2[2*i] = 0.0; bounds2[2*i+1] = 1.0; tMax += direction2[i]*direction2[i]; } tMax = sqrt(tMax); // create a parametric range around the tolerance stopDist = tMax*this->NumberOfDivisions; for (i = 0; i < 3; i++) { direction3[i] = direction2[i]/tMax; } if (vtkBox::IntersectBox(bounds2, origin, direction2, hitPosition, result)) { // start walking through the octants prod = this->NumberOfDivisions*this->NumberOfDivisions; leafStart = this->NumberOfOctants - this->NumberOfDivisions*prod; // Clear the array that indicates whether we have visited this cell. // The array is only cleared when the query number rolls over. This // saves a number of calls to memset. this->QueryNumber++; if (this->QueryNumber == 0) { this->ClearCellHasBeenVisited(); this->QueryNumber++; // can't use 0 as a marker } // set up curr and stop dist currDist = 0; for (i = 0; i < 3; i++) { currDist += (hitPosition[i] - origin[i])*(hitPosition[i] - origin[i]); } currDist = sqrt(currDist)*this->NumberOfDivisions; // add one offset due to the problems around zero for (loop = 0; loop <3; loop++) { hitPosition[loop] = hitPosition[loop]*this->NumberOfDivisions + 1.0; pos[loop] = static_cast(hitPosition[loop]); // Adjust right boundary condition: if we intersect from the top, right, // or back; then pos must be adjusted to a valid octant index if (pos[loop] > this->NumberOfDivisions) { pos[loop] = this->NumberOfDivisions; } } idx = leafStart + pos[0] - 1 + (pos[1] - 1)*this->NumberOfDivisions + (pos[2] - 1)*prod; while ( (pos[0] > 0) && (pos[1] > 0) && (pos[2] > 0) && (pos[0] <= this->NumberOfDivisions) && (pos[1] <= this->NumberOfDivisions) && (pos[2] <= this->NumberOfDivisions) && (currDist < stopDist)) { if (this->Tree[idx]) { this->ComputeOctantBounds(pos[0]-1,pos[1]-1,pos[2]-1); for (cellId=0; cellId < this->Tree[idx]->GetNumberOfIds(); cellId++) { cId = this->Tree[idx]->GetId(cellId); if (this->CellHasBeenVisited[cId] != this->QueryNumber) { this->CellHasBeenVisited[cId] = this->QueryNumber; // check whether we intersect the cell bounds if (this->CacheCellBounds) { hitCellBounds = vtkBox::IntersectBox(this->CellBounds[cId], p1, direction1, hitCellBoundsPosition, result); } else { this->DataSet->GetCellBounds(cId, cellBounds); hitCellBounds = vtkBox::IntersectBox(cellBounds, p1, direction1, hitCellBoundsPosition, result); } if (hitCellBounds) { cells->InsertUniqueId(cId); } // if (hitCellBounds) } // if (!this->CellHasBeenVisited[cId]) } } // move to the next octant tMax = VTK_DOUBLE_MAX; bestDir = 0; for (loop = 0; loop < 3; loop++) { if (direction3[loop] > 0) { npos[loop] = pos[loop] + 1; dist[loop] = (1.0 - hitPosition[loop] + pos[loop])/direction3[loop]; if (dist[loop] == 0) { dist[loop] = 1.0/direction3[loop]; } if (dist[loop] < 0) { dist[loop] = 0; } if (dist[loop] < tMax) { bestDir = loop; tMax = dist[loop]; } } if (direction3[loop] < 0) { npos[loop] = pos[loop] - 1; dist[loop] = (pos[loop] - hitPosition[loop])/direction3[loop]; if (dist[loop] == 0) { dist[loop] = -0.01/direction3[loop]; } if (dist[loop] < 0) { dist[loop] = 0; } if (dist[loop] < tMax) { bestDir = loop; tMax = dist[loop]; } } } // update our position for (loop = 0; loop < 3; loop++) { hitPosition[loop] += dist[bestDir]*direction3[loop]; } currDist += dist[bestDir]; // now make the move, find the smallest distance // only cross one boundary at a time pos[bestDir] = npos[bestDir]; idx = leafStart + pos[0] - 1 + (pos[1]-1)*this->NumberOfDivisions + (pos[2]-1)*prod; } } } //---------------------------------------------------------------------------- void vtkCellLocator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } ",16329,True,3329.811470536111,median "/* Copyright (c) 2022 Jin Li, dragon-fly@qq.com 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 ""Const/Header.h"" #include ""Lua/LuaFromXml.h"" #include ""tinyxml2/SAXParser.h"" #include ""Lua/LuaEngine.h"" #include ""Basic/Content.h"" #include ""yuescript/yue_compiler.h"" NS_DOROTHY_BEGIN #define SWITCH_STR_START(str) switch (Switch::hash(str)) #define CASE_STR(str) case #str##_hash: #define CASE_STR_DOT(prename,name) case #prename"".""#name##_hash: #define SWITCH_STR_END static void Handler(const char* begin, const char* end) { #define CHECK_CDATA(name) \\ if (strncmp(begin, #name, sizeof(#name) / sizeof(char) - 1) == 0)\\ {\\ SAXParser::placeCDataHeader("""");\\ return;\\ } if (begin < end && *(begin-1) != '/') { CHECK_CDATA(Lua) CHECK_CDATA(Yue) } } static bool isVal(const char* value) { if (value && value[0] == '{') return false; return true; } #if DORA_DEBUG #define toVal(s,def) (oVal(s,def,element,#s).c_str()) #define Val(s) (oVal(s,nullptr,element,#s).c_str()) #else #define toVal(s,def) (oVal(s,def).c_str()) #define Val(s) (oVal(s,nullptr).c_str()) #endif static const char* _toBoolean(const char* str) { if (strcmp(str,""True"") == 0) return ""true""; if (strcmp(str,""False"") == 0) return ""false""; return str; } #define toBoolean(x) (_toBoolean(toVal(x,""False""))) #define toEase(x) (isVal(x) ? std::string(""Ease."")+Val(x) : Val(x)) #define toBlendFunc(x) (isVal(x) ? toVal(x,""Zero"") : Val(x)) #define toTextAlign(x) (isVal(x) ? std::string(""\\"""")+toVal(x,""Center"")+'\\""' : Val(x)) #define toText(x) (isVal(x) ? std::string(""\\"""")+Val(x)+'\\""' : Val(x)) #define Self_Check(name) \\ if (self.empty()) { self = getUsableName(#name); names.insert(self); }\\ if (firstItem.empty()) firstItem = self; // Vec2 #define Vec2_Define \\ const char* x = nullptr;\\ const char* y = nullptr; #define Vec2_Check \\ CASE_STR(X) { x = atts[++i]; break; }\\ CASE_STR(Y) { y = atts[++i]; break; } #define Vec2_Handle \\ items.push(std::string(""Vec2("")+toVal(x,""0"")+"",""+toVal(y,""0"")+"")""); // Object #define Object_Define \\ std::string self;\\ bool hasSelf = false;\\ bool ref = false; #define Object_Check \\ CASE_STR(Name) { hasSelf = true; self = atts[++i]; break; }\\ CASE_STR(Ref) { ref = strcmp(atts[++i],""True"") == 0; break; } // ActionBase #define ActionBase_Define \\ Object_Define\\ bool def = false; #define ActionBase_Check \\ Object_Check\\ CASE_STR(Def) { def = strcmp(atts[++i],""True"") == 0; break; } // Delay #define Delay_Define \\ ActionBase_Define\\ const char* time = nullptr; #define Delay_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; } #define Delay_Create #define Delay_Handle \\ oFunc func = {std::string(""Delay("")+toVal(time,""0"")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Delay_Finish // Scale #define Scale_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* start = nullptr;\\ const char* stop = nullptr;\\ const char* ease = nullptr; #define Scale_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(Start) { start = atts[++i]; break; }\\ CASE_STR(Stop) { stop = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define Scale_Create #define Scale_Handle \\ if (!stop) stop = start;\\ oFunc func = {std::string(""Scale("")+toVal(time,""0"")+"",""+Val(start)+"",""+Val(stop)+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Scale_Finish // Move #define Move_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* startX = nullptr;\\ const char* startY = nullptr;\\ const char* stopX = nullptr;\\ const char* stopY = nullptr;\\ const char* ease = nullptr; #define Move_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(StartX) { startX = atts[++i]; break; }\\ CASE_STR(StartY) { startY = atts[++i]; break; }\\ CASE_STR(StopX) { stopX = atts[++i]; break; }\\ CASE_STR(StopY) { stopY = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define Move_Create #define Move_Handle \\ oFunc func = {std::string(""Move("")+toVal(time,""0"")+"",Vec2(""+Val(startX)+"",""+Val(startY)+""),Vec2(""+Val(stopX)+"",""+Val(stopY)+"")""+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Move_Finish // Angle #define Angle_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* start = nullptr;\\ const char* stop = nullptr;\\ const char* ease = nullptr; #define Angle_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(Start) { start = atts[++i]; break; }\\ CASE_STR(Stop) { stop = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define Angle_Create #define Angle_Handle \\ if (!stop) stop = start;\\ oFunc func = {std::string(""Angle("")+toVal(time,""0"")+"",""+Val(start)+"",""+Val(stop)+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Angle_Finish // AngleX #define AngleX_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* start = nullptr;\\ const char* stop = nullptr;\\ const char* ease = nullptr; #define AngleX_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(Start) { start = atts[++i]; break; }\\ CASE_STR(Stop) { stop = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define AngleX_Create #define AngleX_Handle \\ if (!stop) stop = start;\\ oFunc func = {std::string(""AngleX("")+toVal(time,""0"")+"",""+Val(start)+"",""+Val(stop)+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define AngleX_Finish // AngleY #define AngleY_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* start = nullptr;\\ const char* stop = nullptr;\\ const char* ease = nullptr; #define AngleY_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(Start) { start = atts[++i]; break; }\\ CASE_STR(Stop) { stop = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define AngleY_Create #define AngleY_Handle \\ if (!stop) stop = start;\\ oFunc func = {std::string(""AngleY("")+toVal(time,""0"")+"",""+Val(start)+"",""+Val(stop)+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define AngleY_Finish // Opacity #define Opacity_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* start = nullptr;\\ const char* stop = nullptr;\\ const char* ease = nullptr; #define Opacity_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(Start) { start = atts[++i]; break; }\\ CASE_STR(Stop) { stop = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define Opacity_Create #define Opacity_Handle \\ if (!stop) stop = start;\\ oFunc func = {std::string(""Opacity("")+toVal(time,""0"")+"",""+Val(start)+"",""+Val(stop)+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Opacity_Finish // SkewX #define SkewX_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* start = nullptr;\\ const char* stop = nullptr;\\ const char* ease = nullptr; #define SkewX_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(Start) { start = atts[++i]; break; }\\ CASE_STR(Stop) { stop = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define SkewX_Create #define SkewX_Handle \\ if (!stop) stop = start;\\ oFunc func = {std::string(""SkewX("")+toVal(time,""0"")+"",""+Val(start)+"",""+Val(stop)+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define SkewX_Finish // SkewY #define SkewY_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* start = nullptr;\\ const char* stop = nullptr;\\ const char* ease = nullptr; #define SkewY_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(Start) { start = atts[++i]; break; }\\ CASE_STR(Stop) { stop = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define SkewY_Create #define SkewY_Handle \\ if (!stop) stop = start;\\ oFunc func = {std::string(""SkewY("")+toVal(time,""0"")+"",""+Val(start)+"",""+Val(stop)+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define SkewY_Finish // Tint #define Tint_Define \\ ActionBase_Define\\ const char* time = nullptr;\\ const char* start = nullptr;\\ const char* stop = nullptr;\\ const char* ease = nullptr; #define Tint_Check \\ ActionBase_Check\\ CASE_STR(Time) { time = atts[++i]; break; }\\ CASE_STR(Start) { start = atts[++i]; break; }\\ CASE_STR(Stop) { stop = atts[++i]; break; }\\ CASE_STR(Ease) { ease = atts[++i]; break; } #define Tint_Create #define Tint_Handle \\ if (!stop) stop = start;\\ oFunc func = {std::string(""Tint("")+toVal(time,""0"")+"",""+Val(start)+"",""+Val(stop)+(ease ? std::string("","")+toEase(ease) : """")+"")"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Tint_Finish // Show #define Show_Define \\ ActionBase_Define #define Show_Check \\ ActionBase_Check #define Show_Create #define Show_Handle \\ oFunc func = {""Show()"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Show_Finish // Hide #define Hide_Define \\ ActionBase_Define #define Hide_Check \\ ActionBase_Check #define Hide_Create #define Hide_Handle \\ oFunc func = {""Hide()"","""",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Hide_Finish // Event #define Event_Define \\ ActionBase_Define\\ const char* type = nullptr; #define Event_Check \\ ActionBase_Check\\ CASE_STR(Type) { type = atts[++i]; break; } #define Event_Create #define Event_Handle \\ oFunc func = {""Event(\\""""+(type ? std::string(type) : Slice::Empty)+""\\"")"","")"",def ? oFuncType::ActionDef : oFuncType::Action};\\ funcs.push(func); #define Event_Finish // Sequence #define Sequence_Define \\ ActionBase_Define #define Sequence_Check \\ ActionBase_Check #define Sequence_Create #define Sequence_Handle \\ items.push(""Sequence"");\\ funcs.push({"""","""",def ? oFuncType::ActionDef : oFuncType::Action}) #define Sequence_Finish // Spawn #define Spawn_Define \\ ActionBase_Define #define Spawn_Check \\ ActionBase_Check #define Spawn_Create #define Spawn_Handle \\ items.push(""Spawn"");\\ funcs.push({"""","""",def ? oFuncType::ActionDef : oFuncType::Action}) #define Spawn_Finish #define Add_To_Parent \\ if (!elementStack.empty()) {\\ const oItem& parent = elementStack.top();\\ if (!parent.name.empty())\\ {\\ fmt::format_to(std::back_inserter(stream), ""{}:addChild({}){}""sv, parent.name, self, nl());\\ }\\ else if (strcmp(parent.type,""Stencil"") == 0)\\ {\\ elementStack.pop();\\ if (!elementStack.empty())\\ {\\ const oItem& newParent = elementStack.top();\\ fmt::format_to(std::back_inserter(stream), ""{}.stencil = {}{}""sv, newParent.name, self, nl());\\ }\\ }\\ if (hasSelf && ref)\\ {\\ fmt::format_to(std::back_inserter(stream), ""{}.{} = {}{}""sv, firstItem, self, self, nl());\\ }\\ } // Node #define Node_Define \\ Object_Define\\ const char* width = nullptr;\\ const char* height = nullptr;\\ const char* x = nullptr;\\ const char* y = nullptr;\\ const char* z = nullptr;\\ const char* anchorX = nullptr;\\ const char* anchorY = nullptr;\\ const char* passColor = nullptr;\\ const char* passOpacity = nullptr;\\ const char* color3 = nullptr;\\ const char* opacity = nullptr;\\ const char* angle = nullptr;\\ const char* angleX = nullptr;\\ const char* angleY = nullptr;\\ const char* scaleX = nullptr;\\ const char* scaleY = nullptr;\\ const char* skewX = nullptr;\\ const char* skewY = nullptr;\\ const char* order = nullptr;\\ const char* tag = nullptr;\\ const char* transformTarget = nullptr;\\ const char* visible = nullptr;\\ const char* touchEnabled = nullptr;\\ const char* swallowTouches = nullptr;\\ const char* swallowMouseWheel = nullptr;\\ const char* renderGroup = nullptr;\\ const char* renderOrder = nullptr; #define Node_Check \\ Object_Check\\ CASE_STR(Width) { width = atts[++i]; break; }\\ CASE_STR(Height) { height = atts[++i]; break; }\\ CASE_STR(X) { x = atts[++i]; break; }\\ CASE_STR(Y) { y = atts[++i]; break; }\\ CASE_STR(Z) { z = atts[++i]; break; }\\ CASE_STR(AnchorX) { anchorX = atts[++i]; break; }\\ CASE_STR(AnchorY) { anchorY = atts[++i]; break; }\\ CASE_STR(PassColor) { passColor = atts[++i]; break; }\\ CASE_STR(PassOpacity) { passOpacity = atts[++i]; break; }\\ CASE_STR(Color3) { color3 = atts[++i]; break; }\\ CASE_STR(Opacity) { opacity = atts[++i]; break; }\\ CASE_STR(Angle) { angle = atts[++i]; break; }\\ CASE_STR(AngleX) { angleX = atts[++i]; break; }\\ CASE_STR(AngleY) { angleY = atts[++i]; break; }\\ CASE_STR(ScaleX) { scaleX = atts[++i]; break; }\\ CASE_STR(ScaleY) { scaleY = atts[++i]; break; }\\ CASE_STR(SkewX) { skewX = atts[++i]; break; }\\ CASE_STR(SkewY) { skewY = atts[++i]; break; }\\ CASE_STR(Order) { order = atts[++i]; break; }\\ CASE_STR(Tag) { tag = atts[++i]; break; }\\ CASE_STR(TransformTarget) { transformTarget = atts[++i]; break; }\\ CASE_STR(Visible) { visible = atts[++i]; break; }\\ CASE_STR(TouchEnabled) { touchEnabled = atts[++i]; break; }\\ CASE_STR(SwallowTouches) { swallowTouches = atts[++i]; break; }\\ CASE_STR(SwallowMouseWheel) { swallowMouseWheel = atts[++i]; break; }\\ CASE_STR(RenderGroup) { renderGroup = atts[++i]; break; }\\ CASE_STR(RenderOrder) { renderOrder = atts[++i]; break; } #define Node_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = Node(){}""sv, self, nl()); #define Node_Handle \\ if (anchorX && anchorY) fmt::format_to(std::back_inserter(stream), ""{}.anchor = Vec2({},{}){}""sv, self, Val(anchorX), Val(anchorY), nl());\\ else if (anchorX && !anchorY) fmt::format_to(std::back_inserter(stream), ""{}.anchor = Vec2({},{}.anchor.y){}""sv, self, Val(anchorX), self, nl());\\ else if (!anchorX && anchorY) fmt::format_to(std::back_inserter(stream), ""{}.anchor = Vec2({}.anchor.x,{}){}""sv, self, self, Val(anchorY), nl());\\ if (x) fmt::format_to(std::back_inserter(stream), ""{}.x = {}{}""sv, self, Val(x), nl());\\ if (y) fmt::format_to(std::back_inserter(stream), ""{}.y = {}{}""sv, self, Val(y), nl());\\ if (z) fmt::format_to(std::back_inserter(stream), ""{}.z = {}{}""sv, self, Val(z), nl());\\ if (passColor) fmt::format_to(std::back_inserter(stream), ""{}.passColor3 = {}{}""sv, self, toBoolean(passColor), nl());\\ if (passOpacity) fmt::format_to(std::back_inserter(stream), ""{}.passOpacity = {}{}""sv, self, toBoolean(passOpacity), nl());\\ if (color3) fmt::format_to(std::back_inserter(stream), ""{}.color3 = Color3({}){}""sv, self, Val(color3), nl());\\ if (opacity) fmt::format_to(std::back_inserter(stream), ""{}.opacity = {}{}""sv, self, Val(opacity), nl());\\ if (angle) fmt::format_to(std::back_inserter(stream), ""{}.angle = {}{}""sv, self, Val(angle), nl());\\ if (angleX) fmt::format_to(std::back_inserter(stream), ""{}.angleX = {}{}""sv, self, Val(angleX), nl());\\ if (angleY) fmt::format_to(std::back_inserter(stream), ""{}.angleY = {}{}""sv, self, Val(angleY), nl());\\ if (scaleX) fmt::format_to(std::back_inserter(stream), ""{}.scaleX = {}{}""sv, self, Val(scaleX), nl());\\ if (scaleY) fmt::format_to(std::back_inserter(stream), ""{}.scaleY = {}{}""sv, self, Val(scaleY), nl());\\ if (skewX) fmt::format_to(std::back_inserter(stream), ""{}.skewX = {}{}""sv, self, Val(skewX), nl());\\ if (skewY) fmt::format_to(std::back_inserter(stream), ""{}.skewY = {}{}""sv, self, Val(skewY), nl());\\ if (transformTarget) fmt::format_to(std::back_inserter(stream), ""{}.transformTarget = {}{}""sv, self, Val(transformTarget), nl());\\ if (visible) fmt::format_to(std::back_inserter(stream), ""{}.visible = {}{}""sv, self, toBoolean(visible), nl());\\ if (order) fmt::format_to(std::back_inserter(stream), ""{}.order = {}{}""sv, self, Val(order), nl());\\ if (tag) fmt::format_to(std::back_inserter(stream), ""{}.tag = {}{}""sv, self, toText(tag), nl());\\ if (width && height) fmt::format_to(std::back_inserter(stream), ""{}.size = Size({},{}){}""sv, self, Val(width), Val(height), nl());\\ else if (width && !height) fmt::format_to(std::back_inserter(stream), ""{}.width = {}{}""sv, self, Val(width), nl());\\ else if (!width && height) fmt::format_to(std::back_inserter(stream), ""{}.height = {}{}""sv, self, Val(height), nl());\\ if (touchEnabled) fmt::format_to(std::back_inserter(stream), ""{}.touchEnabled = {}{}""sv, self, toBoolean(touchEnabled), nl());\\ if (swallowTouches) fmt::format_to(std::back_inserter(stream), ""{}.swallowTouches = {}{}""sv, self, toBoolean(swallowTouches), nl());\\ if (swallowMouseWheel) fmt::format_to(std::back_inserter(stream), ""{}.swallowMouseWheel = {}{}""sv, self, toBoolean(swallowMouseWheel), nl());\\ if (renderGroup) fmt::format_to(std::back_inserter(stream), ""{}.renderGroup = {}{}""sv, self, toBoolean(renderGroup), nl());\\ if (renderOrder) fmt::format_to(std::back_inserter(stream), ""{}.renderOrder = {}{}""sv, self, Val(renderOrder), nl()); #define Node_Finish \\ Add_To_Parent // DrawNode #define DrawNode_Define \\ Node_Define #define DrawNode_Check \\ Node_Check #define DrawNode_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = DrawNode(){}""sv, self, nl()); #define DrawNode_Handle \\ Node_Handle #define DrawNode_Finish \\ Add_To_Parent // DrawNode.Dot #define Dot_Define \\ const char* x = nullptr;\\ const char* y = nullptr;\\ const char* radius = nullptr;\\ const char* color = nullptr; #define Dot_Check \\ CASE_STR(X) { x = atts[++i]; break; }\\ CASE_STR(Y) { y = atts[++i]; break; }\\ CASE_STR(Radius) { radius = atts[++i]; break; }\\ CASE_STR(Color) { color = atts[++i]; break; } #define Dot_Finish \\ if (!elementStack.empty())\\ {\\ fmt::format_to(std::back_inserter(stream),\\ ""{}:drawDot(Vec2({},{}),{},Color({})){}""sv,\\ elementStack.top().name, toVal(x,""0""), toVal(y,""0""), toVal(radius,""0.5""), Val(color), nl()\\ );\\ } // DrawNode.Polygon #define Polygon_Define \\ const char* fillColor = nullptr;\\ const char* borderWidth = nullptr;\\ const char* borderColor = nullptr; #define Polygon_Check \\ CASE_STR(FillColor) { fillColor = atts[++i]; break; }\\ CASE_STR(BorderWidth) { borderWidth = atts[++i]; break; }\\ CASE_STR(BorderColor) { borderColor = atts[++i]; break; } #define Polygon_Finish \\ if (!elementStack.empty())\\ {\\ oFunc func = {elementStack.top().name+"":drawPolygon({""s,\\ ""},Color(""s+Val(fillColor)+""),""s+toVal(borderWidth,""0"")+"",Color(""s+toVal(borderColor,"""")+""))""s+nl(), oFuncType::Polygon};\\ funcs.push(func);\\ items.push(""Polygon"");\\ } // DrawNode.Segment #define Segment_Define \\ const char* beginX = nullptr;\\ const char* beginY = nullptr;\\ const char* endX = nullptr;\\ const char* endY = nullptr;\\ const char* radius = nullptr;\\ const char* color = nullptr; #define Segment_Check \\ CASE_STR(BeginX) { beginX = atts[++i]; break; }\\ CASE_STR(BeginY) { beginY = atts[++i]; break; }\\ CASE_STR(EndX) { endX = atts[++i]; break; }\\ CASE_STR(EndY) { endY = atts[++i]; break; }\\ CASE_STR(Radius) { radius = atts[++i]; break; }\\ CASE_STR(Color) { color = atts[++i]; break; } #define Segment_Finish \\ if (!elementStack.empty())\\ {\\ fmt::format_to(std::back_inserter(stream),\\ ""{}:drawSegment(Vec2({},{}),Vec2({},{}),{},Color({})){}""sv,\\ elementStack.top().name, toVal(beginX,""0""), toVal(beginY,""0""),\\ toVal(endX,""0""), toVal(endY,""0""), toVal(radius,""0.5""), toVal(color,""""), nl()\\ );\\ } // Line #define Line_Define \\ Node_Define #define Line_Check \\ Node_Check #define Line_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = Line(){}""sv, self, nl()); #define Line_Handle \\ Node_Handle #define Line_Finish \\ Add_To_Parent\\ oFunc func = {std::string(self)+"":set({""s, ""},Color(0xffffffff))""s+nl(), oFuncType::Line};\\ funcs.push(func);\\ items.push(""Line""); // ClipNode #define ClipNode_Define \\ Node_Define\\ const char* alphaThreshold = nullptr;\\ const char* inverted = nullptr; #define ClipNode_Check \\ Node_Check\\ CASE_STR(AlphaThreshold) { alphaThreshold = atts[++i]; break; }\\ CASE_STR(Inverted) { inverted = atts[++i]; break; } #define ClipNode_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = ClipNode(){}""sv, self, nl()); #define ClipNode_Handle \\ Node_Handle\\ if (alphaThreshold) fmt::format_to(std::back_inserter(stream), ""{}.alphaThreshold = {}{}""sv, self, Val(alphaThreshold), nl());\\ if (inverted) fmt::format_to(std::back_inserter(stream), ""{}.inverted = {}{}""sv, toBoolean(inverted), nl()); #define ClipNode_Finish \\ Add_To_Parent // Label #define Label_Define \\ Node_Define\\ const char* text = nullptr;\\ const char* fontName = nullptr;\\ const char* fontSize = nullptr;\\ const char* textWidth = nullptr;\\ const char* spacing = nullptr;\\ const char* lineGap = nullptr;\\ const char* alignment = nullptr; #define Label_Check \\ Node_Check\\ CASE_STR(Text) { text = atts[++i]; break; }\\ CASE_STR(FontName) { fontName = atts[++i]; break; }\\ CASE_STR(FontSize) { fontSize = atts[++i]; break; }\\ CASE_STR(TextAlign) { alignment = atts[++i]; break; }\\ CASE_STR(TextWidth) { textWidth = atts[++i]; break; }\\ CASE_STR(Spacing) { spacing = atts[++i]; break; }\\ CASE_STR(LineGap) { lineGap = atts[++i]; break; } #define Label_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = Label({},{}){}""sv, self, toText(fontName), Val(fontSize), nl()); #define Label_Handle \\ Node_Handle\\ if (alignment) fmt::format_to(std::back_inserter(stream), ""{}.alignment = {}{}""sv, self, toTextAlign(alignment), nl());\\ if (textWidth) fmt::format_to(std::back_inserter(stream), ""{}.textWidth = {}{}""sv,self, strcmp(textWidth,""Auto"") == 0 ? ""Label.AutomaticWidth""s : Val(textWidth), nl());\\ if (lineGap) fmt::format_to(std::back_inserter(stream), ""{}.lineGap = {}{}""sv, self, Val(lineGap), nl());\\ if (spacing) fmt::format_to(std::back_inserter(stream), ""{}.spacing = {}{}""sv, self, Val(spacing), nl());\\ if (text && text[0]) fmt::format_to(std::back_inserter(stream), ""{}.text = {}{}""sv, self, toText(text), nl()); #define Label_Finish \\ Add_To_Parent // Sprite #define Sprite_Define \\ Node_Define\\ const char* file = nullptr;\\ const char* blendSrc = nullptr;\\ const char* blendDst = nullptr; #define Sprite_Check \\ Node_Check\\ CASE_STR(File) { file = atts[++i]; break; }\\ CASE_STR(BlendSrc) { blendSrc = atts[++i]; break; }\\ CASE_STR(BlendDst) { blendDst = atts[++i]; break; } #define Sprite_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = Sprite({}){}""sv, self, file ? toText(file) : std::string(), nl()); #define Sprite_Handle \\ Node_Handle\\ if (blendSrc && blendDst) fmt::format_to(std::back_inserter(stream), ""{}.blendFunc = BlendFunc(\\""{}\\"",\\""{}\\""){}""sv, self, toBlendFunc(blendSrc), toBlendFunc(blendDst), nl());\\ else if (blendSrc && !blendDst) fmt::format_to(std::back_inserter(stream), ""{}.blendFunc = BlendFunc(\\""{}\\"",\\""Zero\\""){}""sv, self, toBlendFunc(blendSrc), nl());\\ else if (!blendSrc && blendDst) fmt::format_to(std::back_inserter(stream), ""{}.blendFunc = BlendFunc(\\""Zero\\"",\\""{}\\""){}""sv, self, toBlendFunc(blendDst), nl()); #define Sprite_Finish \\ Add_To_Parent // Grid #define Grid_Define \\ Node_Define\\ const char* file = nullptr;\\ const char* blendSrc = nullptr;\\ const char* blendDst = nullptr;\\ const char* gridX = nullptr;\\ const char* gridY = nullptr; #define Grid_Check \\ Node_Check\\ CASE_STR(File) { file = atts[++i]; break; }\\ CASE_STR(BlendSrc) { blendSrc = atts[++i]; break; }\\ CASE_STR(BlendDst) { blendDst = atts[++i]; break; }\\ CASE_STR(GridX) { gridX = atts[++i]; break; }\\ CASE_STR(GridY) { gridY = atts[++i]; break; } #define Grid_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = Grid({}, {}, {}){}""sv, self, file ? toText(file) : std::string(), Val(gridX), Val(gridY), nl()); #define Grid_Handle \\ Node_Handle\\ if (blendSrc && blendDst) fmt::format_to(std::back_inserter(stream), ""{}.blendFunc = BlendFunc(\\""{}\\"",\\""{}\\""){}""sv, self, toBlendFunc(blendSrc), toBlendFunc(blendDst), nl());\\ else if (blendSrc && !blendDst) fmt::format_to(std::back_inserter(stream), ""{}.blendFunc = BlendFunc(\\""{}\\"",\\""Zero\\""){}""sv, self, toBlendFunc(blendSrc), nl());\\ else if (!blendSrc && blendDst) fmt::format_to(std::back_inserter(stream), ""{}.blendFunc = BlendFunc(\\""Zero\\"",\\""{}\\""){}""sv, self, toBlendFunc(blendDst), nl()); #define Grid_Finish \\ Add_To_Parent // Playable #define Playable_Define \\ Node_Define\\ const char* filename = nullptr;\\ const char* look = nullptr;\\ const char* loop = nullptr;\\ const char* play = nullptr;\\ const char* fliped = nullptr;\\ const char* speed = nullptr; #define Playable_Check \\ Node_Check\\ CASE_STR(File) { filename = atts[++i]; break; }\\ CASE_STR(Look) { look = atts[++i]; break; }\\ CASE_STR(Loop) { loop = atts[++i]; break; }\\ CASE_STR(Play) { play = atts[++i]; break; }\\ CASE_STR(Fliped) { fliped = atts[++i]; break; }\\ CASE_STR(Speed) { speed = atts[++i]; break; } #define Playable_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = Playable({}){}""sv, self, toText(filename), nl()); #define Playable_Handle \\ Node_Handle\\ if (look) fmt::format_to(std::back_inserter(stream), ""{}.look = \\""{}\\""{}""sv, self, Val(look), nl());\\ if (fliped) fmt::format_to(std::back_inserter(stream), ""{}.fliped = {}{}""sv, self, toBoolean(fliped), nl());\\ if (speed) fmt::format_to(std::back_inserter(stream), ""{}.speed = {}{}""sv, self, Val(speed), nl());\\ if (play) fmt::format_to(std::back_inserter(stream), ""{}:play(\\""{}\\""{}){}""sv, self, Val(play), loop ? std::string("","") + toBoolean(loop) : std::string(), nl()); #define Playable_Finish \\ Add_To_Parent // Menu #define Menu_Define \\ Node_Define\\ const char* enabled = nullptr; #define Menu_Check \\ Node_Check\\ CASE_STR(Enabled) { enabled = atts[++i]; break; } #define Menu_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = Menu(){}""sv, self, nl()); #define Menu_Handle \\ Node_Handle\\ if (enabled) fmt::format_to(std::back_inserter(stream), ""{}.enabled = {}{}""sv, self, toBoolean(enabled), nl()); #define Menu_Finish \\ Add_To_Parent // ModuleNode #define ModuleNode_Define \\ Object_Define #define ModuleNode_Check \\ Object_Check\\ default: { int index = i;attributes[atts[index]] = Slice(atts[++i]).trimSpace(); break; } #define ModuleNode_Create \\ fmt::format_to(std::back_inserter(stream), ""local {} = {}{{""sv, self, element); #define ModuleNode_Handle \\ auto it = attributes.begin();\\ while (it != attributes.end())\\ {\\ std::string str = std::string() + (char)tolower(it->first[0]) + it->first.substr(1) + "" = ""s;\\ char* p;\\ strtod(it->second.c_str(), &p);\\ if (*p == 0) str += it->second;\\ else\\ {\\ if (it->second == ""True""_slice) str += ""true""s;\\ else if (it->second == ""False""_slice) str += ""false""s;\\ else str += toText(it->second.c_str());\\ }\\ ++it;\\ if (it != attributes.end())\\ {\\ str += "", ""s;\\ }\\ fmt::format_to(std::back_inserter(stream), ""{}""sv, str);\\ }\\ attributes.clear();\\ fmt::format_to(std::back_inserter(stream), ""}}{}""sv, nl()); #define ModuleNode_Finish \\ if (!elementStack.empty())\\ {\\ const oItem& parent = elementStack.top();\\ if (!parent.name.empty())\\ {\\ fmt::format_to(std::back_inserter(stream), ""{}:addChild({}){}""sv, parent.name, self, nl());\\ if (hasSelf && ref)\\ {\\ fmt::format_to(std::back_inserter(stream), ""{}.{} = {}{}""sv, firstItem, self, self, nl());\\ }\\ }\\ else if (strcmp(parent.type,""Stencil"") == 0)\\ {\\ elementStack.pop();\\ if (!elementStack.empty())\\ {\\ const oItem& newParent = elementStack.top();\\ fmt::format_to(std::back_inserter(stream), ""{}.stencil = {}{}""sv, newParent.name, self, nl());\\ }\\ }\\ } // Import #define Import_Define \\ const char* module = nullptr;\\ const char* name = nullptr; #define Import_Check \\ CASE_STR(Module) { module = atts[++i]; break; }\\ CASE_STR(Name) { name = atts[++i]; break; } #define Import_Create \\ if (module) {\\ std::string mod(module);\\ size_t pos = mod.rfind('.');\\ std::string modStr = (name ? name : (pos == std::string::npos ? std::string(module) : mod.substr(pos+1)));\\ imported.insert(modStr);\\ fmt::format_to(std::back_inserter(requires), ""local {} = require(\\""{}\\""){}""sv, modStr, module, nl());\\ } // Item #define NodeItem_Define \\ bool ref = false;\\ const char* self = nullptr;\\ const char* width = nullptr;\\ const char* height = nullptr;\\ const char* x = nullptr;\\ const char* y = nullptr;\\ const char* z = nullptr;\\ const char* anchorX = nullptr;\\ const char* anchorY = nullptr;\\ const char* passColor = nullptr;\\ const char* passOpacity = nullptr;\\ const char* color3 = nullptr;\\ const char* opacity = nullptr;\\ const char* angle = nullptr;\\ const char* angleX = nullptr;\\ const char* angleY = nullptr;\\ const char* scaleX = nullptr;\\ const char* scaleY = nullptr;\\ const char* skewX = nullptr;\\ const char* skewY = nullptr;\\ const char* order = nullptr;\\ const char* tag = nullptr;\\ const char* transformTarget = nullptr;\\ const char* visible = nullptr;\\ const char* touchEnabled = nullptr;\\ const char* swallowTouches = nullptr;\\ const char* swallowMouseWheel = nullptr;\\ const char* renderGroup = nullptr;\\ const char* renderOrder = nullptr; #define NodeItem_Check \\ CASE_STR(Ref) { ref = strcmp(atts[++i],""True"") == 0; break; }\\ CASE_STR(Name) { self = atts[++i]; break; }\\ CASE_STR(Width) { width = atts[++i]; break; }\\ CASE_STR(Height) { height = atts[++i]; break; }\\ CASE_STR(X) { x = atts[++i]; break; }\\ CASE_STR(Y) { y = atts[++i]; break; }\\ CASE_STR(Z) { z = atts[++i]; break; }\\ CASE_STR(AnchorX) { anchorX = atts[++i]; break; }\\ CASE_STR(AnchorY) { anchorY = atts[++i]; break; }\\ CASE_STR(PassColor) { passColor = atts[++i]; break; }\\ CASE_STR(PassOpacity) { passOpacity = atts[++i]; break; }\\ CASE_STR(Color3) { color3 = atts[++i]; break; }\\ CASE_STR(Opacity) { opacity = atts[++i]; break; }\\ CASE_STR(Angle) { angle = atts[++i]; break; }\\ CASE_STR(AngleX) { angleX = atts[++i]; break; }\\ CASE_STR(AngleY) { angleY = atts[++i]; break; }\\ CASE_STR(ScaleX) { scaleX = atts[++i]; break; }\\ CASE_STR(ScaleY) { scaleY = atts[++i]; break; }\\ CASE_STR(SkewX) { skewX = atts[++i]; break; }\\ CASE_STR(SkewY) { skewY = atts[++i]; break; }\\ CASE_STR(Order) { order = atts[++i]; break; }\\ CASE_STR(Tag) { tag = atts[++i]; break; }\\ CASE_STR(TransformTarget) { transformTarget = atts[++i]; break; }\\ CASE_STR(Visible) { visible = atts[++i]; break; }\\ CASE_STR(TouchEnabled) { touchEnabled = atts[++i]; break; }\\ CASE_STR(SwallowTouches) { swallowTouches = atts[++i]; break; }\\ CASE_STR(SwallowMouseWheel) { swallowMouseWheel = atts[++i]; break; }\\ CASE_STR(RenderGroup) { renderGroup = atts[++i]; break; }\\ CASE_STR(RenderOrder) { renderOrder = atts[++i]; break; } #define NodeItem_Create \\ if (tag)\\ {\\ if (!self) self = tag;\\ fmt::format_to(std::back_inserter(stream), ""local {} = {}:getChildByTag(\\""{}\\""){}""sv, Val(self), elementStack.top().name, Val(tag), nl());\\ }\\ else\\ {\\ fmt::format_to(std::back_inserter(stream), ""local {} = {}.{}{}""sv, Val(self), elementStack.top().name, Val(self), nl());\\ }\\ if (self && self[0])\\ {\\ if (ref)\\ {\\ fmt::format_to(std::back_inserter(stream), ""{}.{} = {}{}""sv, firstItem, self, self, nl());\\ }\\ oItem item = { ""Item"", self };\\ elementStack.push(item);\\ } #define NodeItem_Handle \\ if (anchorX && anchorY) fmt::format_to(std::back_inserter(stream), ""{}.anchor = Vec2({},{}){}""sv, self, Val(anchorX), Val(anchorY), nl());\\ else if (anchorX && !anchorY) fmt::format_to(std::back_inserter(stream), ""{}.anchor = Vec2({},{}.anchor.y){}""sv, self, Val(anchorX), self, nl());\\ else if (!anchorX && anchorY) fmt::format_to(std::back_inserter(stream), ""{}.anchor = Vec2({}.anchor.x,{}){}""sv, self, self, Val(anchorY), nl());\\ if (x) fmt::format_to(std::back_inserter(stream), ""{}.x = {}{}""sv, self, Val(x), nl());\\ if (y) fmt::format_to(std::back_inserter(stream), ""{}.y = {}{}""sv, self, Val(y), nl());\\ if (z) fmt::format_to(std::back_inserter(stream), ""{}.z = {}{}""sv, self, Val(z), nl());\\ if (passColor) fmt::format_to(std::back_inserter(stream), ""{}.passColor = {}{}""sv, self, toBoolean(passColor), nl());\\ if (passOpacity) fmt::format_to(std::back_inserter(stream), ""{}.passOpacity = {}{}""sv, self, toBoolean(passOpacity), nl());\\ if (color3) fmt::format_to(std::back_inserter(stream), ""{}.color3 = Color3({}){}""sv, self, Val(color3), nl());\\ if (opacity) fmt::format_to(std::back_inserter(stream), ""{}.opacity = {}{}""sv, self, Val(opacity), nl());\\ if (angle) fmt::format_to(std::back_inserter(stream), ""{}.angle = {}{}""sv, self, Val(angle), nl());\\ if (angleX) fmt::format_to(std::back_inserter(stream), ""{}.angleX = {}{}""sv, self, Val(angleX), nl());\\ if (angleY) fmt::format_to(std::back_inserter(stream), ""{}.angleY = {}{}""sv, self, Val(angleY), nl());\\ if (scaleX) fmt::format_to(std::back_inserter(stream), ""{}.scaleX = {}{}""sv, self, Val(scaleX), nl());\\ if (scaleY) fmt::format_to(std::back_inserter(stream), ""{}.scaleY = {}{}""sv, self, Val(scaleY), nl());\\ if (skewX) fmt::format_to(std::back_inserter(stream), ""{}.skewX = {}{}""sv, self, Val(skewX), nl());\\ if (skewY) fmt::format_to(std::back_inserter(stream), ""{}.skewY = {}{}""sv, self, Val(skewY), nl());\\ if (transformTarget) fmt::format_to(std::back_inserter(stream), ""{}.transformTarget = {}{}""sv, self, Val(transformTarget), nl());\\ if (visible) fmt::format_to(std::back_inserter(stream), ""{}.visible = {}{}""sv, self, toBoolean(visible), nl());\\ if (order) fmt::format_to(std::back_inserter(stream), ""{}.order = {}{}""sv, self, Val(order), nl());\\ if (width && height) fmt::format_to(std::back_inserter(stream), ""{}.size = Size({},{}){}""sv, self, Val(width), Val(height), nl());\\ else if (width && !height) fmt::format_to(std::back_inserter(stream), ""{}.width = {}{}""sv, self, Val(width), nl());\\ else if (!width && height) fmt::format_to(std::back_inserter(stream), ""{}.height = {}{}""sv, self, Val(height), nl());\\ if (touchEnabled) fmt::format_to(std::back_inserter(stream), ""{}.touchEnabled = {}{}""sv, self, toBoolean(touchEnabled), nl());\\ if (swallowTouches) fmt::format_to(std::back_inserter(stream), ""{}.swallowTouches = {}{}""sv, self, toBoolean(swallowTouches), nl());\\ if (swallowMouseWheel) fmt::format_to(std::back_inserter(stream), ""{}.swallowMouseWheel = {}{}""sv, self, toBoolean(swallowMouseWheel), nl());\\ if (renderGroup) fmt::format_to(std::back_inserter(stream), ""{}.renderGroup = {}{}""sv, self, toBoolean(renderGroup), nl());\\ if (renderOrder) fmt::format_to(std::back_inserter(stream), ""{}.renderOrder = {}{}""sv, self, Val(renderOrder), nl()); // Slot #define Slot_Define \\ const char* name = nullptr;\\ const char* args = nullptr;\\ const char* perform = nullptr;\\ const char* loop = nullptr;\\ const char* target = nullptr; #define Slot_Check \\ CASE_STR(Name) { name = atts[++i]; break; }\\ CASE_STR(Args) { args = atts[++i]; break; }\\ CASE_STR(Target) { target = atts[++i]; break; }\\ CASE_STR(Perform) { perform = atts[++i]; break; }\\ CASE_STR(Loop) { loop = atts[++i]; break; } #define Slot_Create \\ std::string targetName;\\ std::string performAction;\\ if (perform)\\ {\\ targetName = target ? std::string(target) : elementStack.top().name;\\ performAction = targetName + "":perform(""s + perform + ')' + nl();\\ }\\ std::string loopAction;\\ if (""True""_slice == loop)\\ {\\ loopAction = fmt::format(""{}:slot(\\""ActionEnd\\"",function(_action_) if _action_ == {} then {}:perform({}) end end){}"", targetName, Val(perform), targetName, Val(perform), nl());\\ }\\ oFunc func = {elementStack.top().name + "":slot(""s + toText(name) + "",function(""s + (args ? args : """") + ')' + nl() + performAction + loopAction, ""end)""s, oFuncType::Slot};\\ funcs.push(func); #define Item_Define(name) name##_Define #define Item_Loop(name) \\ for (int i = 0; atts[i] != nullptr; i++)\\ {\\ SWITCH_STR_START(atts[i])\\ {\\ name##_Check\\ }\\ SWITCH_STR_END\\ } #define Item_Create(name) name##_Create #define Item_Handle(name) name##_Handle #define Item_Push(name) name##_Finish;oItem item = {#name,self,ref};elementStack.push(item); #define Item(name,var) \\ CASE_STR(name)\\ {\\ Item_Define(name)\\ Item_Loop(name)\\ Self_Check(var)\\ Item_Create(name)\\ Item_Handle(name)\\ Item_Push(name)\\ break;\\ } #define ItemDot_Push(prename,name) prename##_##name##_Finish;oItem item = {#prename"".""#name,self,ref};elementStack.push(item); #define ItemDot(prename,name,var) \\ CASE_STR_DOT(prename,name)\\ {\\ Item_Define(prename##_##name)\\ Item_Loop(prename##_##name)\\ Self_Check(var)\\ Item_Create(prename##_##name)\\ Item_Handle(prename##_##name)\\ ItemDot_Push(prename,name)\\ break;\\ } class XmlDelegator : public SAXDelegator { public: XmlDelegator(SAXParser* parser): codes(nullptr), currentLine(1), currentLinePos(nullptr), currentLineStr("" -- 1\\n""s), parser(parser) { } virtual void startElement(const char* name, const char** atts); virtual void endElement(const char* name); virtual void textHandler(const char* s, int len); std::string oVal(const char* value, const char* def = nullptr, const char* element = nullptr, const char* attr = nullptr); std::string compileYueCodes(const char* codes); public: std::string originalXml; int getLineNumber(const char* name, const char* start = nullptr); void updateLineNumber(const char* pos); std::string nl(); void clear() { currentLine = 1; currentLinePos = nullptr; currentLineStr = "" -- 1\\n""s; codes = nullptr; for (; !elementStack.empty(); elementStack.pop()); for (; !funcs.empty(); funcs.pop()); for (; !items.empty(); items.pop()); stream = fmt::memory_buffer(); requires = fmt::memory_buffer(); names.clear(); imported.clear(); firstItem.clear(); originalXml.clear(); } void begin() { lastError.clear(); fmt::format_to(std::back_inserter(stream), ""return function(args)""s + nl() + ""local _ENV = Dorothy(args)""s + nl()); } void end() { fmt::format_to(std::back_inserter(stream), ""return {}{}end""sv, firstItem, nl()); } std::string getResult() { if (lastError.empty()) { std::string requireStr = fmt::to_string(requires); return requireStr + fmt::to_string(stream); } return std::string(); } const std::string& getLastError() { return lastError; } private: std::string getUsableName(const char* baseName) { int index = 1; std::string base(baseName); std::string name; do { name = fmt::format(""{}{}"", base, index); auto it = names.find(name); if (it == names.end()) break; else index++; } while (true); return name; } private: struct oItem { const char* type; std::string name; bool ref; }; enum class oFuncType { Action, ActionDef, Polygon, Line, Slot }; struct oFunc { std::string begin; std::string end; oFuncType type; }; SAXParser* parser; int currentLine; const char* currentLinePos; std::string currentLineStr; // Script const char* codes; // Loader std::string firstItem; std::string lastError; std::stack funcs; std::stack items; std::stack elementStack; std::unordered_set names; std::unordered_set imported; std::unordered_map attributes; fmt::memory_buffer stream; fmt::memory_buffer requires; }; int XmlDelegator::getLineNumber(const char* name, const char* start) { const char* xml = parser->getBuffer(); int startIndex = start ? start - xml : 0; int stopIndex = name - xml; int line = 1; const char* str = originalXml.c_str(); for (int i = startIndex; i < stopIndex; i++) { if (str[i] == '\\n') { line++; } } return line; } std::string XmlDelegator::oVal(const char* value, const char* def, const char* element, const char* attr) { if (!value || !value[0]) { if (def) return std::string(def); else if (attr && element) { std::string num = fmt::format(""{}"", getLineNumber(element)); lastError += std::string(""Missing attribute "") + (char)toupper(attr[0]) + std::string(attr).substr(1) + "" for <"" + element + "">, at line "" + num + ""\\n""; } return std::string(); } if (value[0] == '{') { std::string valStr(value); if (valStr.back() != '}') return valStr; size_t start = 1; for (; valStr[start] == ' ' || valStr[start] == '\\t'; ++start); size_t end = valStr.size() - 2; for (; valStr[end] == ' ' || valStr[end] == '\\t'; --end); if (end < start) { if (attr && element) { std::string num = fmt::format(""{}"", getLineNumber(element)); lastError += std::string(""Missing attribute "") + (char)toupper(attr[0]) + std::string(attr).substr(1) + "" for <"" + element + "">, at line "" + num + ""\\n""; } return std::string(); } valStr = valStr.substr(start, end - start + 1); std::string newStr; start = 0; size_t i = 0; while (i < valStr.size()) { if ((valStr[i] == '$' || valStr[i] == '@') && i < valStr.size() - 1) { if (valStr[i] == '$') { std::string parent; if (!elementStack.empty()) { oItem top = elementStack.top(); if (!top.name.empty()) { parent = top.name; } else if (strcmp(top.type, ""Stencil"") == 0) { elementStack.pop(); if (!elementStack.empty()) { const oItem& newTop = elementStack.top(); parent = newTop.name; } elementStack.push(top); } } if (parent.empty() && element) { std::string num = fmt::format(""{}"", getLineNumber(element)); lastError += std::string(""The $ expression can`t be used in tag at line "") + num + ""\\n""; } newStr += valStr.substr(start, i - start); i++; start = i + 1; switch (valStr[i]) { case 'L': newStr += ""0""; break; case 'W': case 'R': newStr += parent + "".width""; break; case 'H': case 'T': newStr += parent + "".height""; break; case 'B': newStr += ""0""; break; case 'X': newStr += parent + "".width*0.5""; break; case 'Y': newStr += parent + "".height*0.5""; break; default: if (element) { std::string num = fmt::format(""{}"", getLineNumber(element)); lastError += std::string(""Invalid expression $"") + valStr[i] + "" at line "" + num + ""\\n""; } break; } } else { newStr += valStr.substr(start, i - start); i++; start = i + 1; switch (valStr[i]) { case 'L': newStr += ""0""; break; case 'W': case 'R': newStr += ""View.size.width""; break; case 'H': case 'T': newStr += ""View.size.height""; break; case 'B': newStr += ""0""; break; case 'X': newStr += ""View.size.width*0.5""; break; case 'Y': newStr += ""View.size.height*0.5""; break; default: if (element) { std::string num = fmt::format(""{}"", getLineNumber(element)); lastError += std::string(""Invalid expression @"") + valStr[i] + "" at line "" + num + ""\\n""; } break; } } } i++; } if (0 < start) { if (start < valStr.size()) newStr += valStr.substr(start); return newStr; } else return valStr; } else return std::string(value); } void XmlDelegator::updateLineNumber(const char* pos) { if (pos > currentLinePos) { int line = getLineNumber(pos, currentLinePos); if (line > 1) { currentLine += line - 1; currentLineStr = "" -- ""s + std::to_string(currentLine) + '\\n'; } currentLinePos = pos; } } std::string XmlDelegator::nl() { return currentLineStr; } void XmlDelegator::startElement(const char* element, const char** atts) { SWITCH_STR_START(element) { CASE_STR(Delay) CASE_STR(Scale) CASE_STR(Move) CASE_STR(Angle) CASE_STR(Opacity) CASE_STR(SkewX) CASE_STR(SkewY) CASE_STR(Tint) CASE_STR(Show) CASE_STR(Hide) CASE_STR(Event) CASE_STR(Sequence) CASE_STR(Spawn) { bool parentIsAction = !elementStack.empty() && strcmp(elementStack.top().type, ""Action"") == 0; if (parentIsAction) { updateLineNumber(element); } break; } default: { updateLineNumber(element); break; } } SWITCH_STR_END SWITCH_STR_START(element) { CASE_STR(Dorothy) { break; } Item(Node, node) Item(DrawNode, drawNode) Item(Line, line) Item(Sprite, sprite) Item(Grid, grid) Item(ClipNode, clipNode) Item(Label, label) Item(Playable, playable) Item(Menu, menu) Item(Delay, delay) Item(Scale, scale) Item(Move, move) Item(Angle, angle) Item(Opacity, opacity) Item(SkewX, skewX) Item(SkewY, skewY) Item(Tint, tint) Item(Show, show) Item(Hide, hide) Item(Event, event) Item(Sequence, sequence) Item(Spawn, spawn) CASE_STR(Vec2) { Item_Define(Vec2) Item_Loop(Vec2) Item_Handle(Vec2) break; } CASE_STR(Dot) { Item_Define(Dot) Item_Loop(Dot) Dot_Finish break; } CASE_STR(Polygon) { Item_Define(Polygon) Item_Loop(Polygon) Polygon_Finish break; } CASE_STR(Segment) { Item_Define(Segment) Item_Loop(Segment) Segment_Finish break; } CASE_STR(Stencil) { oItem item = { ""Stencil"" }; elementStack.push(item); break; } CASE_STR(Import) { Item_Define(Import) Item_Loop(Import) Import_Create break; } CASE_STR(Action) { oItem item = { ""Action"" }; elementStack.push(item); break; } CASE_STR(Item) { Item_Define(NodeItem) Item_Loop(NodeItem) Item_Create(NodeItem) Item_Handle(NodeItem) break; } CASE_STR(Slot) { Item_Define(Slot) Item_Loop(Slot) Item_Create(Slot) break; } CASE_STR(Lua) CASE_STR(Yue) { break; } default: { Item_Define(ModuleNode) Item_Loop(ModuleNode) Self_Check(item) Item_Create(ModuleNode) Item_Handle(ModuleNode) ModuleNode_Finish; oItem item = { element, self, ref }; elementStack.push(item); break; } } SWITCH_STR_END } std::string XmlDelegator::compileYueCodes(const char* codes) { yue::YueConfig config; config.lineOffset = currentLine - 2; config.reserveLineNumber = true; config.implicitReturnRoot = false; auto result = yue::YueCompiler{}.compile(fmt::format(""do{}{}"", nl(), codes), config); if (result.codes.empty()) { lastError += fmt::format(""failed to compile yue codes started at line {}\\n{}"", getLineNumber(codes), result.error); } return std::move(result.codes); } void XmlDelegator::endElement(const char *name) { SWITCH_STR_START(name) { CASE_STR(Yue) { std::string codeStr; if (codes) codeStr = compileYueCodes(codes); codes = nullptr; if (!funcs.empty() && funcs.top().type == oFuncType::Slot) { funcs.top().begin += codeStr; } else { fmt::format_to(std::back_inserter(elementStack.empty() ? requires : stream), ""{}""sv, codeStr); } return; } CASE_STR(Lua) { if (codes) { Slice luaCodes(codes); luaCodes.trimSpace(); std::string_view lcodes(luaCodes.begin(), luaCodes.size()); auto pos = lcodes.find(""[[""sv); if (pos == std::string::npos) { pos = lcodes.find(""[=""sv); } if (pos != std::string::npos) { lastError += fmt::format(""Lua multiline string is not supported at line {}.\\n"", getLineNumber(luaCodes.begin() + pos)); } auto lines = luaCodes.split(""\\n""); fmt::memory_buffer buf; std::string codeStr; if (!lines.empty()) { if (lines.size() == 1) { updateLineNumber(lines.begin()->begin()); codeStr = lines.front() + nl(); } else { if (!lines.begin()->empty()) { updateLineNumber(lines.begin()->begin()); fmt::format_to(std::back_inserter(buf), ""{}{}""sv, lines.front().toString(), nl()); } for (auto it = ++lines.begin(); it != lines.end(); ++it) { if (!it->empty()) { updateLineNumber(it->begin()); fmt::format_to(std::back_inserter(buf), ""{}{}""sv, it->toString(), nl()); } } codeStr = fmt::to_string(buf); } } if (!funcs.empty() && funcs.top().type == oFuncType::Slot) { funcs.top().begin += codeStr; } else { fmt::format_to(std::back_inserter(elementStack.empty() ? requires : stream), ""{}""sv, codeStr); } } codes = nullptr; return; } } SWITCH_STR_END if (elementStack.empty()) return; oItem currentData = elementStack.top(); if (strcmp(name, elementStack.top().type) == 0) elementStack.pop(); bool parentIsAction = !elementStack.empty() && strcmp(elementStack.top().type, ""Action"") == 0; SWITCH_STR_START(name) { CASE_STR(Slot) { oFunc func = funcs.top(); funcs.pop(); fmt::format_to(std::back_inserter(stream), ""{}{}{}""sv, func.begin, func.end, nl()); break; } // Action CASE_STR(Delay) CASE_STR(Scale) CASE_STR(Move) CASE_STR(Angle) CASE_STR(Opacity) CASE_STR(SkewX) CASE_STR(SkewY) CASE_STR(Tint) CASE_STR(Show) CASE_STR(Hide) CASE_STR(Event) { oFunc func = funcs.top(); funcs.pop(); if (parentIsAction) { fmt::format_to(std::back_inserter(stream), func.type == oFuncType::ActionDef ? ""local {} = {}{}""sv : ""local {} = Action({}){}""sv, currentData.name, func.begin, nl()); } else { items.push(func.begin); auto it = names.find(currentData.name); if (it != names.end()) names.erase(it); } break; } CASE_STR(Sequence) CASE_STR(Spawn) { oFunc func = funcs.top(); funcs.pop(); std::string tempItem = std::string(name) + ""(""; std::stack tempStack; while (items.top() != name) { tempStack.push(items.top()); items.pop(); } items.pop(); while (!tempStack.empty()) { tempItem += tempStack.top(); tempStack.pop(); if (!tempStack.empty()) tempItem += "",""; } tempItem += "")""; if (parentIsAction) { fmt::format_to(std::back_inserter(stream), func.type == oFuncType::ActionDef ? ""local {} = {}{}""sv : ""local {} = Action({}){}""sv, currentData.name, tempItem, nl()); } else { items.push(tempItem); auto it = names.find(currentData.name); if (it != names.end()) names.erase(it); } break; } CASE_STR(Polygon) CASE_STR(Line) { oFunc func = funcs.top(); funcs.pop(); fmt::format_to(std::back_inserter(stream), ""{}""sv, func.begin); std::stack tempStack; while (items.top() != name) { tempStack.push(items.top()); items.pop(); } items.pop(); while (!tempStack.empty()) { fmt::format_to(std::back_inserter(stream), ""{}""sv, tempStack.top()); tempStack.pop(); if (!tempStack.empty()) fmt::format_to(std::back_inserter(stream), "",""sv); } fmt::format_to(std::back_inserter(stream), ""{}""sv, func.end); break; } // Builtin node CASE_STR(Action) CASE_STR(Node) CASE_STR(DrawNode) CASE_STR(Sprite) CASE_STR(Grid) CASE_STR(ClipNode) CASE_STR(Label) CASE_STR(Playable) CASE_STR(Menu) CASE_STR(Vec2) CASE_STR(Dot) CASE_STR(Segment) CASE_STR(Stencil) CASE_STR(Import) CASE_STR(Item) { break; } default: { auto it = imported.find(name); if (it == imported.end()) { lastError += fmt::format(""Tag <{}> not imported, closed at line {}.\\n"", name, getLineNumber(name)); } break; } } SWITCH_STR_END if (parentIsAction && currentData.ref) { fmt::format_to(std::back_inserter(stream), ""{}.{} = {}{}""sv, firstItem, currentData.name, currentData.name, nl()); } } void XmlDelegator::textHandler(const char* s, int len) { updateLineNumber(s); codes = s; } XmlLoader::XmlLoader():_delegator(new XmlDelegator(&_parser)) { _parser.setDelegator(_delegator.get()); } XmlLoader::~XmlLoader() { } std::string XmlLoader::load(String filename) { auto data = SharedContent.load(filename); _delegator->originalXml = Slice(r_cast(data.first.get()), data.second).toString(); _delegator->begin(); SAXParser::setHeaderHandler(Handler); bool result = _parser.parseXml(_delegator->originalXml); SAXParser::setHeaderHandler(nullptr); _delegator->end(); std::string codes = result ? _delegator->getResult() : std::string(); _delegator->clear(); return codes; } std::string XmlLoader::loadXml(String xml) { _delegator->originalXml = xml.toString(); _delegator->begin(); SAXParser::setHeaderHandler(Handler); bool result = _parser.parseXml(_delegator->originalXml); SAXParser::setHeaderHandler(nullptr); _delegator->end(); std::string codes = result ? _delegator->getResult() : std::string(); _delegator->clear(); return codes; } std::string XmlLoader::getLastError() { const std::string& parserError = _parser.getLastError(); const std::string& dorothyError = _delegator->getLastError(); if (parserError.empty() && !dorothyError.empty()) { return std::string(""Xml document error\\n"") + dorothyError; } return parserError + dorothyError; } NS_DOROTHY_END ",16205,True,3024.4816963741687,median "//============================================================================ // // SSSS tt lll lll // SS SS tt ll ll // SS tttttt eeee ll ll aaaa // SSSS tt ee ee ll ll aa // SS tt eeeeee ll ll aaaaa -- ""An Atari 2600 VCS Emulator"" // SS SS tt ee ll ll aa aa // SSSS ttt eeeee llll llll aaaaa // // Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team // // See the file ""license"" for information on usage and redistribution of // this file, and for a DISCLAIMER OF ALL WARRANTIES. // // $Id: Console.cxx,v 1.128 2007/07/27 13:49:16 stephena Exp $ //============================================================================ #include #include #include #include #include ""AtariVox.hxx"" #include ""Booster.hxx"" #include ""Cart.hxx"" #include ""Console.hxx"" #include ""Control.hxx"" #include ""Driving.hxx"" #include ""Event.hxx"" //ALE #include ""EventHandler.hxx"" #include ""Joystick.hxx"" #include ""Keyboard.hxx"" #include ""M6502Hi.hxx"" #include ""M6502Low.hxx"" #include ""M6532.hxx"" #include ""MediaSrc.hxx"" #include ""Paddles.hxx"" #include ""Props.hxx"" #include ""PropsSet.hxx"" #include ""Settings.hxx"" //ALE #include ""Sound.hxx"" #include ""Switches.hxx"" #include ""System.hxx"" #include ""TIA.hxx"" //ALE #include ""FrameBuffer.hxx"" #include ""OSystem.hxx"" //ALE #include ""Menu.hxx"" //ALE #include ""CommandMenu.hxx"" #include ""Version.hxx"" #ifdef DEBUGGER_SUPPORT #include ""Debugger.hxx"" #endif #ifdef CHEATCODE_SUPPORT #include ""CheatManager.hxx"" #endif // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Console::Console(OSystem* osystem, Cartridge* cart, const Properties& props) : myOSystem(osystem), myProperties(props), myUserPaletteDefined(false) { myControllers[0] = 0; myControllers[1] = 0; myMediaSource = 0; mySwitches = 0; mySystem = 0; myEvent = 0; std::string seedStr = myOSystem->settings().getString(""random_seed"").c_str(); if (seedStr == ""time"") Random::seed(time(NULL)); else Random::seed(atoi(seedStr.c_str())); // Attach the event subsystem to the current console //ALE myEvent = myOSystem->eventHandler().event(); myEvent = myOSystem->event(); // Load user-defined palette for this ROM loadUserPalette(); // Setup the controllers based on properties const string& left = myProperties.get(Controller_Left); const string& right = myProperties.get(Controller_Right); // Swap the ports if necessary int leftPort, rightPort; if(myProperties.get(Console_SwapPorts) == ""NO"") { leftPort = 0; rightPort = 1; } else { leftPort = 1; rightPort = 0; } // Also check if we should swap the paddles plugged into a jack bool swapPaddles = myProperties.get(Controller_SwapPaddles) == ""YES""; // Construct left controller if(left == ""BOOSTER-GRIP"") { myControllers[leftPort] = new BoosterGrip(Controller::Left, *myEvent); } else if(left == ""DRIVING"") { myControllers[leftPort] = new Driving(Controller::Left, *myEvent); } else if((left == ""KEYBOARD"") || (left == ""KEYPAD"")) { myControllers[leftPort] = new Keyboard(Controller::Left, *myEvent); } else if(left == ""PADDLES"") { myControllers[leftPort] = new Paddles(Controller::Left, *myEvent, swapPaddles); } else { myControllers[leftPort] = new Joystick(Controller::Left, *myEvent); } // Construct right controller if(right == ""BOOSTER-GRIP"") { myControllers[rightPort] = new BoosterGrip(Controller::Right, *myEvent); } else if(right == ""DRIVING"") { myControllers[rightPort] = new Driving(Controller::Right, *myEvent); } else if((right == ""KEYBOARD"") || (right == ""KEYPAD"")) { myControllers[rightPort] = new Keyboard(Controller::Right, *myEvent); } else if(right == ""PADDLES"") { myControllers[rightPort] = new Paddles(Controller::Right, *myEvent, swapPaddles); } #ifdef ATARIVOX_SUPPORT else if(right == ""ATARIVOX"") { myControllers[rightPort] = new AtariVox(Controller::Right, *myEvent); } #endif else { myControllers[rightPort] = new Joystick(Controller::Right, *myEvent); } // Create switches for the console mySwitches = new Switches(*myEvent, myProperties); // Now, we can construct the system and components mySystem = new System(13, 6); // Inform the controllers about the system myControllers[0]->setSystem(mySystem); myControllers[1]->setSystem(mySystem); M6502* m6502; if(myOSystem->settings().getString(""cpu"") == ""low"") { m6502 = new M6502Low(1); } else { m6502 = new M6502High(1); } #ifdef DEBUGGER_SUPPORT m6502->attach(myOSystem->debugger()); #endif M6532* m6532 = new M6532(*this); TIA *tia = new TIA(*this, myOSystem->settings()); tia->setSound(myOSystem->sound()); mySystem->attach(m6502); mySystem->attach(m6532); mySystem->attach(tia); mySystem->attach(cart); // Remember what my media source is myMediaSource = tia; myCart = cart; myRiot = m6532; // Query some info about this console ostringstream buf; buf << "" Cart Name: "" << myProperties.get(Cartridge_Name) << endl << "" Cart MD5: "" << myProperties.get(Cartridge_MD5) << endl; // Auto-detect NTSC/PAL mode if it's requested myDisplayFormat = myProperties.get(Display_Format); buf << "" Display Format: "" << myDisplayFormat; if(myDisplayFormat == ""AUTO-DETECT"" || myOSystem->settings().getBool(""rominfo"")) { // Run the system for 60 frames, looking for PAL scanline patterns // We assume the first 30 frames are garbage, and only consider // the second 30 (useful to get past SuperCharger BIOS) // Unfortunately, this means we have to always enable 'fastscbios', // since otherwise the BIOS loading will take over 250 frames! mySystem->reset(); int palCount = 0; for(int i = 0; i < 60; ++i) { myMediaSource->update(); if(i >= 30 && myMediaSource->scanlines() > 285) ++palCount; } myDisplayFormat = (palCount >= 15) ? ""PAL"" : ""NTSC""; if(myProperties.get(Display_Format) == ""AUTO-DETECT"") buf << "" ==> "" << myDisplayFormat; } buf << endl << cart->about(); // Make sure height is set properly for PAL ROM if((myDisplayFormat == ""PAL"" || myDisplayFormat == ""SECAM"") && myProperties.get(Display_Height) == ""210"") myProperties.set(Display_Height, ""250""); // Reset, the system to its power-on state mySystem->reset(); // Bumper Bash requires all 4 directions //ALE const string& md5 = myProperties.get(Cartridge_MD5); //ALE bool allow = (md5 == ""aa1c41f86ec44c0a44eb64c332ce08af"" || //ALE md5 == ""1bf503c724001b09be79c515ecfcbd03""); //ALE myOSystem->eventHandler().allowAllDirections(allow); myAboutString = buf.str(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Console::~Console() { delete mySystem; delete mySwitches; delete myControllers[0]; delete myControllers[1]; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::toggleFormat() { int framerate = 60; if(myDisplayFormat == ""NTSC"") { myDisplayFormat = ""PAL""; myProperties.set(Display_Format, myDisplayFormat); mySystem->reset(); //ALE myOSystem->frameBuffer().showMessage(""PAL Mode""); framerate = 50; } else if(myDisplayFormat == ""PAL"") { myDisplayFormat = ""PAL60""; myProperties.set(Display_Format, myDisplayFormat); mySystem->reset(); //ALE myOSystem->frameBuffer().showMessage(""PAL60 Mode""); framerate = 60; } else if(myDisplayFormat == ""PAL60"") { myDisplayFormat = ""SECAM""; myProperties.set(Display_Format, myDisplayFormat); mySystem->reset(); //ALE myOSystem->frameBuffer().showMessage(""SECAM Mode""); framerate = 50; } else if(myDisplayFormat == ""SECAM"") { myDisplayFormat = ""NTSC""; myProperties.set(Display_Format, myDisplayFormat); mySystem->reset(); //ALE myOSystem->frameBuffer().showMessage(""NTSC Mode""); framerate = 60; } setPalette(myOSystem->settings().getString(""palette"")); myOSystem->setFramerate(framerate); myOSystem->sound().setFrameRate(framerate); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::toggleColorLoss() { bool colorloss = !myOSystem->settings().getBool(""colorloss""); myOSystem->settings().setBool(""colorloss"", colorloss); setColorLossPalette(colorloss); setPalette(myOSystem->settings().getString(""palette"")); string message = string(""PAL color-loss "") + (colorloss ? ""enabled"" : ""disabled""); //ALE myOSystem->frameBuffer().showMessage(message); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::togglePalette() { string palette, message; palette = myOSystem->settings().getString(""palette""); if(palette == ""standard"") // switch to z26 { palette = ""z26""; message = ""Z26 palette""; } else if(palette == ""z26"") // switch to user or standard { // If we have a user-defined palette, it will come next in // the sequence; otherwise loop back to the standard one if(myUserPaletteDefined) { palette = ""user""; message = ""User-defined palette""; } else { palette = ""standard""; message = ""Standard Stella palette""; } } else if(palette == ""user"") // switch to standard { palette = ""standard""; message = ""Standard Stella palette""; } else // switch to standard mode if we get this far { palette = ""standard""; message = ""Standard Stella palette""; } myOSystem->settings().setString(""palette"", palette); //ALE myOSystem->frameBuffer().showMessage(message); setPalette(palette); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::setPalette(const string& type) { // Look at all the palettes, since we don't know which one is // currently active uInt32* palettes[3][3] = { { &ourNTSCPalette[0], &ourPALPalette[0], &ourSECAMPalette[0] }, { &ourNTSCPaletteZ26[0], &ourPALPaletteZ26[0], &ourSECAMPaletteZ26[0] }, { 0, 0, 0 } }; if(myUserPaletteDefined) { palettes[2][0] = &ourUserNTSCPalette[0]; palettes[2][1] = &ourUserPALPalette[0]; palettes[2][2] = &ourUserSECAMPalette[0]; } // See which format we should be using int paletteNum = 0; if(type == ""standard"") paletteNum = 0; else if(type == ""z26"") paletteNum = 1; else if(type == ""user"" && myUserPaletteDefined) paletteNum = 2; // Now consider the current display format const uInt32* palette = (myDisplayFormat.compare(0, 3, ""PAL"") == 0) ? palettes[paletteNum][1] : (myDisplayFormat.compare(0, 5, ""SECAM"") == 0) ? palettes[paletteNum][2] : palettes[paletteNum][0]; //ALE myOSystem->frameBuffer().setTIAPalette(palette); myOSystem->p_export_screen->set_palette(palette); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::togglePhosphor() { const string& phosphor = myProperties.get(Display_Phosphor); //ALE int blend = atoi(myProperties.get(Display_PPBlend).c_str()); bool enable; if(phosphor == ""YES"") { myProperties.set(Display_Phosphor, ""No""); enable = false; //ALE myOSystem->frameBuffer().showMessage(""Phosphor effect disabled""); } else { myProperties.set(Display_Phosphor, ""Yes""); enable = true; //ALE myOSystem->frameBuffer().showMessage(""Phosphor effect enabled""); } //ALE myOSystem->frameBuffer().enablePhosphor(enable, blend); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::setProperties(const Properties& props) { myProperties = props; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::initializeVideo(bool full) { if(full) { string title = string(""Stella "") + STELLA_VERSION + "": \\"""" + myProperties.get(Cartridge_Name) + ""\\""""; // ALE myOSystem->frameBuffer().initialize(title, // ALE myMediaSource->width() << 1, // ALE myMediaSource->height()); } //ALE bool enable = myProperties.get(Display_Phosphor) == ""YES""; //ALE int blend = atoi(myProperties.get(Display_PPBlend).c_str()); //ALE myOSystem->frameBuffer().enablePhosphor(enable, blend); setColorLossPalette(myOSystem->settings().getBool(""colorloss"")); setPalette(myOSystem->settings().getString(""palette"")); myOSystem->setFramerate(getFrameRate()); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::initializeAudio() { // Initialize the sound interface. // The # of channels can be overridden in the AudioDialog box or on // the commandline, but it can't be saved. const string& sound = myProperties.get(Cartridge_Sound); uInt32 channels = (sound == ""STEREO"" ? 2 : 1); myOSystem->sound().close(); myOSystem->sound().setChannels(channels); myOSystem->sound().setFrameRate(getFrameRate()); myOSystem->sound().initialize(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /* Original frying research and code by Fred Quimby. I've tried the following variations on this code: - Both OR and Exclusive OR instead of AND. This generally crashes the game without ever giving us realistic ""fried"" effects. - Loop only over the RIOT RAM. This still gave us frying-like effects, but it seemed harder to duplicate most effects. I have no idea why, but munging the TIA regs seems to have some effect (I'd think it wouldn't). Fred says he also tried mangling the PC and registers, but usually it'd just crash the game (e.g. black screen, no way out of it). It's definitely easier to get some effects (e.g. 255 lives in Battlezone) with this code than it is on a real console. My guess is that most ""good"" frying effects come from a RIOT location getting cleared to 0. Fred's code is more likely to accomplish this than frying a real console is... Until someone comes up with a more accurate way to emulate frying, I'm leaving this as Fred posted it. -- B. */ void Console::fry() const { for (int ZPmem=0; ZPmem<0x100; ZPmem += rand() % 4) mySystem->poke(ZPmem, mySystem->peek(ZPmem) & (uInt8)rand() % 256); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::changeYStart(int direction) { Int32 ystart = atoi(myProperties.get(Display_YStart).c_str()); ostringstream strval; string message; if(direction == +1) // increase YStart { ystart++; if(ystart > 64) { //ALE myOSystem->frameBuffer().showMessage(""YStart at maximum""); return; } } else if(direction == -1) // decrease YStart { ystart--; if(ystart < 0) { //ALE myOSystem->frameBuffer().showMessage(""YStart at minimum""); return; } } else return; strval << ystart; myProperties.set(Display_YStart, strval.str()); ((TIA*)myMediaSource)->frameReset(); //ALE myOSystem->frameBuffer().refresh(); message = ""YStart ""; message += strval.str(); //ALE myOSystem->frameBuffer().showMessage(message); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::changeHeight(int direction) { Int32 height = atoi(myProperties.get(Display_Height).c_str()); ostringstream strval; string message; if(direction == +1) // increase Height { height++; if(height > 256) { //ALE myOSystem->frameBuffer().showMessage(""Height at maximum""); return; } } else if(direction == -1) // decrease Height { height--; if(height < 200) { //ALE myOSystem->frameBuffer().showMessage(""Height at minimum""); return; } } else return; strval << height; myProperties.set(Display_Height, strval.str()); ((TIA*)myMediaSource)->frameReset(); initializeVideo(); // takes care of refreshing the screen message = ""Height ""; message += strval.str(); //ALE myOSystem->frameBuffer().showMessage(message); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::toggleTIABit(TIA::TIABit bit, const string& bitname, bool show) const { bool result = ((TIA*)myMediaSource)->toggleBit(bit); string message = bitname + (result ? "" enabled"" : "" disabled""); //ALE myOSystem->frameBuffer().showMessage(message); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::enableBits(bool enable) const { ((TIA*)myMediaSource)->enableBits(enable); string message = string(""TIA bits"") + (enable ? "" enabled"" : "" disabled""); //ALE myOSystem->frameBuffer().showMessage(message); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::loadUserPalette() { const string& palette = myOSystem->paletteFile(); ifstream in(palette.c_str(), ios::binary); if(!in) return; // Make sure the contains enough data for the NTSC, PAL and SECAM palettes // This means 128 colours each for NTSC and PAL, at 3 bytes per pixel // and 8 colours for SECAM at 3 bytes per pixel in.seekg(0, ios::end); streampos length = in.tellg(); in.seekg(0, ios::beg); if(length < 128 * 3 * 2 + 8 * 3) { in.close(); cerr << ""ERROR: invalid palette file "" << palette << endl; return; } // Now that we have valid data, create the user-defined palettes uInt8 pixbuf[3]; // Temporary buffer for one 24-bit pixel for(int i = 0; i < 128; i++) // NTSC palette { in.read((char*)pixbuf, 3); uInt32 pixel = ((int)pixbuf[0] << 16) + ((int)pixbuf[1] << 8) + (int)pixbuf[2]; ourUserNTSCPalette[(i<<1)] = pixel; } for(int i = 0; i < 128; i++) // PAL palette { in.read((char*)pixbuf, 3); uInt32 pixel = ((int)pixbuf[0] << 16) + ((int)pixbuf[1] << 8) + (int)pixbuf[2]; ourUserPALPalette[(i<<1)] = pixel; } uInt32 secam[16]; // All 8 24-bit pixels, plus 8 colorloss pixels for(int i = 0; i < 8; i++) // SECAM palette { in.read((char*)pixbuf, 3); uInt32 pixel = ((int)pixbuf[0] << 16) + ((int)pixbuf[1] << 8) + (int)pixbuf[2]; secam[(i<<1)] = pixel; secam[(i<<1)+1] = 0; } uInt32* ptr = ourUserSECAMPalette; for(int i = 0; i < 16; ++i) { uInt32* s = secam; for(int j = 0; j < 16; ++j) *ptr++ = *s++; } in.close(); myUserPaletteDefined = true; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void Console::setColorLossPalette(bool loss) { // Look at all the palettes, since we don't know which one is // currently active uInt32* palette[9] = { &ourNTSCPalette[0], &ourPALPalette[0], &ourSECAMPalette[0], &ourNTSCPaletteZ26[0], &ourPALPaletteZ26[0], &ourSECAMPaletteZ26[0], 0, 0, 0 }; if(myUserPaletteDefined) { palette[6] = &ourUserNTSCPalette[0]; palette[7] = &ourUserPALPalette[0]; palette[8] = &ourUserSECAMPalette[0]; } for(int i = 0; i < 9; ++i) { if(palette[i] == 0) continue; // If color-loss is enabled, fill the odd numbered palette entries // with gray values (calculated using the standard RGB -> grayscale // conversion formula) for(int j = 0; j < 128; ++j) { uInt32 pixel = palette[i][(j<<1)]; if(loss) { uInt8 r = (pixel >> 16) & 0xff; uInt8 g = (pixel >> 8) & 0xff; uInt8 b = (pixel >> 0) & 0xff; uInt8 sum = (uInt8) (((float)r * 0.2989) + ((float)g * 0.5870) + ((float)b * 0.1140)); pixel = (sum << 16) + (sum << 8) + sum; } palette[i][(j<<1)+1] = pixel; } } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::getFrameRate() const { // Set the correct framerate based on the format of the ROM // This can be overridden by changing the framerate in the // VideoDialog box or on the commandline, but it can't be saved // (ie, framerate is now solely determined based on ROM format). int framerate = myOSystem->settings().getInt(""framerate""); if(framerate == -1) { if(myDisplayFormat == ""NTSC"" || myDisplayFormat == ""PAL60"") framerate = 60; else if(myDisplayFormat == ""PAL"" || myDisplayFormat == ""SECAM"") framerate = 50; else framerate = 60; } return framerate; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourNTSCPalette[256] = { 0x000000, 0, 0x4a4a4a, 0, 0x6f6f6f, 0, 0x8e8e8e, 0, 0xaaaaaa, 0, 0xc0c0c0, 0, 0xd6d6d6, 0, 0xececec, 0, 0x484800, 0, 0x69690f, 0, 0x86861d, 0, 0xa2a22a, 0, 0xbbbb35, 0, 0xd2d240, 0, 0xe8e84a, 0, 0xfcfc54, 0, 0x7c2c00, 0, 0x904811, 0, 0xa26221, 0, 0xb47a30, 0, 0xc3903d, 0, 0xd2a44a, 0, 0xdfb755, 0, 0xecc860, 0, 0x901c00, 0, 0xa33915, 0, 0xb55328, 0, 0xc66c3a, 0, 0xd5824a, 0, 0xe39759, 0, 0xf0aa67, 0, 0xfcbc74, 0, 0x940000, 0, 0xa71a1a, 0, 0xb83232, 0, 0xc84848, 0, 0xd65c5c, 0, 0xe46f6f, 0, 0xf08080, 0, 0xfc9090, 0, 0x840064, 0, 0x97197a, 0, 0xa8308f, 0, 0xb846a2, 0, 0xc659b3, 0, 0xd46cc3, 0, 0xe07cd2, 0, 0xec8ce0, 0, 0x500084, 0, 0x68199a, 0, 0x7d30ad, 0, 0x9246c0, 0, 0xa459d0, 0, 0xb56ce0, 0, 0xc57cee, 0, 0xd48cfc, 0, 0x140090, 0, 0x331aa3, 0, 0x4e32b5, 0, 0x6848c6, 0, 0x7f5cd5, 0, 0x956fe3, 0, 0xa980f0, 0, 0xbc90fc, 0, 0x000094, 0, 0x181aa7, 0, 0x2d32b8, 0, 0x4248c8, 0, 0x545cd6, 0, 0x656fe4, 0, 0x7580f0, 0, 0x8490fc, 0, 0x001c88, 0, 0x183b9d, 0, 0x2d57b0, 0, 0x4272c2, 0, 0x548ad2, 0, 0x65a0e1, 0, 0x75b5ef, 0, 0x84c8fc, 0, 0x003064, 0, 0x185080, 0, 0x2d6d98, 0, 0x4288b0, 0, 0x54a0c5, 0, 0x65b7d9, 0, 0x75cceb, 0, 0x84e0fc, 0, 0x004030, 0, 0x18624e, 0, 0x2d8169, 0, 0x429e82, 0, 0x54b899, 0, 0x65d1ae, 0, 0x75e7c2, 0, 0x84fcd4, 0, 0x004400, 0, 0x1a661a, 0, 0x328432, 0, 0x48a048, 0, 0x5cba5c, 0, 0x6fd26f, 0, 0x80e880, 0, 0x90fc90, 0, 0x143c00, 0, 0x355f18, 0, 0x527e2d, 0, 0x6e9c42, 0, 0x87b754, 0, 0x9ed065, 0, 0xb4e775, 0, 0xc8fc84, 0, 0x303800, 0, 0x505916, 0, 0x6d762b, 0, 0x88923e, 0, 0xa0ab4f, 0, 0xb7c25f, 0, 0xccd86e, 0, 0xe0ec7c, 0, 0x482c00, 0, 0x694d14, 0, 0x866a26, 0, 0xa28638, 0, 0xbb9f47, 0, 0xd2b656, 0, 0xe8cc63, 0, 0xfce070, 0 }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourPALPalette[256] = { 0x000000, 0, 0x2b2b2b, 0, 0x525252, 0, 0x767676, 0, 0x979797, 0, 0xb6b6b6, 0, 0xd2d2d2, 0, 0xececec, 0, 0x000000, 0, 0x2b2b2b, 0, 0x525252, 0, 0x767676, 0, 0x979797, 0, 0xb6b6b6, 0, 0xd2d2d2, 0, 0xececec, 0, 0x805800, 0, 0x96711a, 0, 0xab8732, 0, 0xbe9c48, 0, 0xcfaf5c, 0, 0xdfc06f, 0, 0xeed180, 0, 0xfce090, 0, 0x445c00, 0, 0x5e791a, 0, 0x769332, 0, 0x8cac48, 0, 0xa0c25c, 0, 0xb3d76f, 0, 0xc4ea80, 0, 0xd4fc90, 0, 0x703400, 0, 0x89511a, 0, 0xa06b32, 0, 0xb68448, 0, 0xc99a5c, 0, 0xdcaf6f, 0, 0xecc280, 0, 0xfcd490, 0, 0x006414, 0, 0x1a8035, 0, 0x329852, 0, 0x48b06e, 0, 0x5cc587, 0, 0x6fd99e, 0, 0x80ebb4, 0, 0x90fcc8, 0, 0x700014, 0, 0x891a35, 0, 0xa03252, 0, 0xb6486e, 0, 0xc95c87, 0, 0xdc6f9e, 0, 0xec80b4, 0, 0xfc90c8, 0, 0x005c5c, 0, 0x1a7676, 0, 0x328e8e, 0, 0x48a4a4, 0, 0x5cb8b8, 0, 0x6fcbcb, 0, 0x80dcdc, 0, 0x90ecec, 0, 0x70005c, 0, 0x841a74, 0, 0x963289, 0, 0xa8489e, 0, 0xb75cb0, 0, 0xc66fc1, 0, 0xd380d1, 0, 0xe090e0, 0, 0x003c70, 0, 0x195a89, 0, 0x2f75a0, 0, 0x448eb6, 0, 0x57a5c9, 0, 0x68badc, 0, 0x79ceec, 0, 0x88e0fc, 0, 0x580070, 0, 0x6e1a89, 0, 0x8332a0, 0, 0x9648b6, 0, 0xa75cc9, 0, 0xb76fdc, 0, 0xc680ec, 0, 0xd490fc, 0, 0x002070, 0, 0x193f89, 0, 0x2f5aa0, 0, 0x4474b6, 0, 0x578bc9, 0, 0x68a1dc, 0, 0x79b5ec, 0, 0x88c8fc, 0, 0x340080, 0, 0x4a1a96, 0, 0x5f32ab, 0, 0x7248be, 0, 0x835ccf, 0, 0x936fdf, 0, 0xa280ee, 0, 0xb090fc, 0, 0x000088, 0, 0x1a1a9d, 0, 0x3232b0, 0, 0x4848c2, 0, 0x5c5cd2, 0, 0x6f6fe1, 0, 0x8080ef, 0, 0x9090fc, 0, 0x000000, 0, 0x2b2b2b, 0, 0x525252, 0, 0x767676, 0, 0x979797, 0, 0xb6b6b6, 0, 0xd2d2d2, 0, 0xececec, 0, 0x000000, 0, 0x2b2b2b, 0, 0x525252, 0, 0x767676, 0, 0x979797, 0, 0xb6b6b6, 0, 0xd2d2d2, 0, 0xececec, 0 }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourSECAMPalette[256] = { 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff50ff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0 }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourNTSCPaletteZ26[256] = { 0x000000, 0, 0x505050, 0, 0x646464, 0, 0x787878, 0, 0x8c8c8c, 0, 0xa0a0a0, 0, 0xb4b4b4, 0, 0xc8c8c8, 0, 0x445400, 0, 0x586800, 0, 0x6c7c00, 0, 0x809000, 0, 0x94a414, 0, 0xa8b828, 0, 0xbccc3c, 0, 0xd0e050, 0, 0x673900, 0, 0x7b4d00, 0, 0x8f6100, 0, 0xa37513, 0, 0xb78927, 0, 0xcb9d3b, 0, 0xdfb14f, 0, 0xf3c563, 0, 0x7b2504, 0, 0x8f3918, 0, 0xa34d2c, 0, 0xb76140, 0, 0xcb7554, 0, 0xdf8968, 0, 0xf39d7c, 0, 0xffb190, 0, 0x7d122c, 0, 0x912640, 0, 0xa53a54, 0, 0xb94e68, 0, 0xcd627c, 0, 0xe17690, 0, 0xf58aa4, 0, 0xff9eb8, 0, 0x730871, 0, 0x871c85, 0, 0x9b3099, 0, 0xaf44ad, 0, 0xc358c1, 0, 0xd76cd5, 0, 0xeb80e9, 0, 0xff94fd, 0, 0x5d0b92, 0, 0x711fa6, 0, 0x8533ba, 0, 0x9947ce, 0, 0xad5be2, 0, 0xc16ff6, 0, 0xd583ff, 0, 0xe997ff, 0, 0x401599, 0, 0x5429ad, 0, 0x683dc1, 0, 0x7c51d5, 0, 0x9065e9, 0, 0xa479fd, 0, 0xb88dff, 0, 0xcca1ff, 0, 0x252593, 0, 0x3939a7, 0, 0x4d4dbb, 0, 0x6161cf, 0, 0x7575e3, 0, 0x8989f7, 0, 0x9d9dff, 0, 0xb1b1ff, 0, 0x0f3480, 0, 0x234894, 0, 0x375ca8, 0, 0x4b70bc, 0, 0x5f84d0, 0, 0x7398e4, 0, 0x87acf8, 0, 0x9bc0ff, 0, 0x04425a, 0, 0x18566e, 0, 0x2c6a82, 0, 0x407e96, 0, 0x5492aa, 0, 0x68a6be, 0, 0x7cbad2, 0, 0x90cee6, 0, 0x044f30, 0, 0x186344, 0, 0x2c7758, 0, 0x408b6c, 0, 0x549f80, 0, 0x68b394, 0, 0x7cc7a8, 0, 0x90dbbc, 0, 0x0f550a, 0, 0x23691e, 0, 0x377d32, 0, 0x4b9146, 0, 0x5fa55a, 0, 0x73b96e, 0, 0x87cd82, 0, 0x9be196, 0, 0x1f5100, 0, 0x336505, 0, 0x477919, 0, 0x5b8d2d, 0, 0x6fa141, 0, 0x83b555, 0, 0x97c969, 0, 0xabdd7d, 0, 0x344600, 0, 0x485a00, 0, 0x5c6e14, 0, 0x708228, 0, 0x84963c, 0, 0x98aa50, 0, 0xacbe64, 0, 0xc0d278, 0, 0x463e00, 0, 0x5a5205, 0, 0x6e6619, 0, 0x827a2d, 0, 0x968e41, 0, 0xaaa255, 0, 0xbeb669, 0, 0xd2ca7d, 0 }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourPALPaletteZ26[256] = { 0x000000, 0, 0x4c4c4c, 0, 0x606060, 0, 0x747474, 0, 0x888888, 0, 0x9c9c9c, 0, 0xb0b0b0, 0, 0xc4c4c4, 0, 0x000000, 0, 0x4c4c4c, 0, 0x606060, 0, 0x747474, 0, 0x888888, 0, 0x9c9c9c, 0, 0xb0b0b0, 0, 0xc4c4c4, 0, 0x533a00, 0, 0x674e00, 0, 0x7b6203, 0, 0x8f7617, 0, 0xa38a2b, 0, 0xb79e3f, 0, 0xcbb253, 0, 0xdfc667, 0, 0x1b5800, 0, 0x2f6c00, 0, 0x438001, 0, 0x579415, 0, 0x6ba829, 0, 0x7fbc3d, 0, 0x93d051, 0, 0xa7e465, 0, 0x6a2900, 0, 0x7e3d12, 0, 0x925126, 0, 0xa6653a, 0, 0xba794e, 0, 0xce8d62, 0, 0xe2a176, 0, 0xf6b58a, 0, 0x075b00, 0, 0x1b6f11, 0, 0x2f8325, 0, 0x439739, 0, 0x57ab4d, 0, 0x6bbf61, 0, 0x7fd375, 0, 0x93e789, 0, 0x741b2f, 0, 0x882f43, 0, 0x9c4357, 0, 0xb0576b, 0, 0xc46b7f, 0, 0xd87f93, 0, 0xec93a7, 0, 0xffa7bb, 0, 0x00572e, 0, 0x106b42, 0, 0x247f56, 0, 0x38936a, 0, 0x4ca77e, 0, 0x60bb92, 0, 0x74cfa6, 0, 0x88e3ba, 0, 0x6d165f, 0, 0x812a73, 0, 0x953e87, 0, 0xa9529b, 0, 0xbd66af, 0, 0xd17ac3, 0, 0xe58ed7, 0, 0xf9a2eb, 0, 0x014c5e, 0, 0x156072, 0, 0x297486, 0, 0x3d889a, 0, 0x519cae, 0, 0x65b0c2, 0, 0x79c4d6, 0, 0x8dd8ea, 0, 0x5f1588, 0, 0x73299c, 0, 0x873db0, 0, 0x9b51c4, 0, 0xaf65d8, 0, 0xc379ec, 0, 0xd78dff, 0, 0xeba1ff, 0, 0x123b87, 0, 0x264f9b, 0, 0x3a63af, 0, 0x4e77c3, 0, 0x628bd7, 0, 0x769feb, 0, 0x8ab3ff, 0, 0x9ec7ff, 0, 0x451e9d, 0, 0x5932b1, 0, 0x6d46c5, 0, 0x815ad9, 0, 0x956eed, 0, 0xa982ff, 0, 0xbd96ff, 0, 0xd1aaff, 0, 0x2a2b9e, 0, 0x3e3fb2, 0, 0x5253c6, 0, 0x6667da, 0, 0x7a7bee, 0, 0x8e8fff, 0, 0xa2a3ff, 0, 0xb6b7ff, 0, 0x000000, 0, 0x4c4c4c, 0, 0x606060, 0, 0x747474, 0, 0x888888, 0, 0x9c9c9c, 0, 0xb0b0b0, 0, 0xc4c4c4, 0, 0x000000, 0, 0x4c4c4c, 0, 0x606060, 0, 0x747474, 0, 0x888888, 0, 0x9c9c9c, 0, 0xb0b0b0, 0, 0xc4c4c4, 0 }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourSECAMPaletteZ26[256] = { 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0, 0x000000, 0, 0x2121ff, 0, 0xf03c79, 0, 0xff3cff, 0, 0x7fff00, 0, 0x7fffff, 0, 0xffff3f, 0, 0xffffff, 0 }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourUserNTSCPalette[256] = { 0 }; // filled from external file // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourUserPALPalette[256] = { 0 }; // filled from external file // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - uInt32 Console::ourUserSECAMPalette[256] = { 0 }; // filled from external file // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Console::Console(const Console& console) : myOSystem(console.myOSystem) { // TODO: Write this method assert(false); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Console& Console::operator = (const Console&) { // TODO: Write this method assert(false); return *this; } ",16275,True,3540.5814575891513,median "= About the project The Geb home page can be found at link:http://www.gebish.org[http://www.gebish.org]. == API reference The API reference can be found link:api/index.html[here]. == Support & development Support for Geb is offered on the link:mailto:geb-user@googlegroups.com[geb-user@googlegroups.com] mailing list, which can be subscribed to link:https://groups.google.com/forum/#!forum/geb-user[here]. Ideas and new features for Geb can be discussed on the link:mailto:geb-dev@googlegroups.com[geb-dev@googlegroups.com] mailing list, which can be subscribed to link:https://groups.google.com/d/forum/geb-dev[here]. == Credits === Committers * link:http://ldaley.com[Luke Daley] * link:http://blog.proxerd.pl[Marcin Erdmann] === Contributors * link:http://adhockery.blogspot.com/[Robert Fletcher] * link:http://pniederw.wordpress.com/[Peter Niederwieser] * github-profile:chris-prior[Chris Prior] * github-profile:zolotov[Alexander Zolotov] - TestNG Integration * link:http://c089.wordpress.com/[Christoph Neuroth] - Various fixes and patches * github-profile:antony[Antony Jones] - Various fixes and patches, doc improvements * github-profile:hennr[Jan-Hendrik Peters] - Doc improvements * link:http://fbflex.wordpress.com/[Tomás Lin] - Doc improvements * github-profile:measlyweasel[Jason Cahoon] - Bug fix around text matchers * link:http://refaktor.blogspot.com/[Tomasz Kalkosiński] - Doc improvements * github-profile:richdouglasevans[Rich Douglas Evans] - Doc improvements * github-profile:idurkan[Ian Durkan] - Doc improvements * github-profile:ColinHarrington[Colin Harrington] - Doc improvements * github-profile:bherrmann7[Bob Herrmann] - Doc improvements * github-profile:walterg2[George T Walters II] - Page option support for `withWindow()` * github-profile:craigatk[Craig Atkinson] - Doc improvements * github-profile:andyjduncan[Andy Duncan] - Fail fast when unexpected pages are encountered * github-profile:johnrengelman[John Engelman] - Grails integration improvements * github-profile:legart[Michael Legart] - Grails integration improvements * github-profile:graemerocher[Graeme Rocher] - Grails integration improvements * github-profile:craigatk[Craig Atkinson] - Bug fix around unexpected pages, fix for [issue:422[]] * github-profile:kgeis[Ken Geis] - Doc improvements * github-profile:kellyrob99[Kelly Robinson] - Additional configuration parameters for SauceLabs * github-profile:tygerpatch[Todd Gerspacher] - Doc improvements, Cleaned up settings.gradle * github-profile:davidmc24[David M. Carr] - BrowserStack integration * github-profile:tomdcc[Tom Dunstan] - Cucumber integration and related documentation * github-profile:brian428[Brian Kotek] - Doc improvements * github-profile:david-w-millar[David W Millar] - Doc improvements * github-profile:alincode[Ai-Lin Liou] - Doc improvements * github-profile:menonvarun[Varun Menon] - Selenium By selector support and related documentation, Support navigating to page instances in addition to classes * github-profile:adjohnson916[Anders D. Johnson] - Doc improvements * github-profile:azusa[Hiroyuki Ohnaka] - Doc improvements * github-profile:bodiam[Erik Pragt] - Initial migration of the manual to AsciiDoctor * github-profile:vijaybolleypally[Vijay Bolleypally] - Various fixes * github-profile:pierre-hilt[Pierre Hilt] - `hasNot()` filtering * github-profile:PoohSunny[Yotaro Takahashi] - Doc improvements * github-profile:jochenberger[Jochen Berger] - Better error reporting when trying to set a nonexistent select option * github-profile:matankatz[Matan Katz] - Support for setting the `forcelocal` flag for BrowserStack tunnel * github-profile:victorparmar[Victor Parmar] - Add configuration option for including cause string representation in message of `WaitTimeoutException` * github-profile:berardino[Berardino la Torre] - Fix incorrect delegation of waitFor() methods * github-profile:madmas[Markus Schlichting] - Doc fixes * github-profile:ahitrin[Andrey Hitrin] - Improvement to character replacing in report file names * github-profile:leo-13[Leo Fedorov] - Support for `reportOnTestFailureOnly` config option for Spock integration * github-profile:chrisbyrneham[Chris Byrneham] - Ability to specify proxy location and credentials to use with BrowserStack tunnel * github-profile:anshbansal[Aseem Bansal] - Doc improvements * github-profile:topr[Tomasz Przybysz] - Unwrapping module to its declared type * github-profile:thecodesmith[Brian Stewart] - Doc improvements * github-profile:JacobAae[Jacob Aae Mikkelsen] - Various fixes and improvements * github-profile:pradtke[Patrick Radtke] - Doc improvements * github-profile:leonard84[Leonard Brünings] - Fix for unexpected pages only being checked after at check fails for the expected page, added new composite text matchers * github-profile:mahileeb[Lee Butts] - Improved error message when trying to select null on a single-select select element * github-profile:rickirunge[Ricki Runge] - Ignore case of tag names passed as part of css selectors to `Navigator.filter()` * github-profile:jdmuriel[Jesús L. D. Muriel] - Doc fixes * github-profile:joschi[Jochen Schalanda] - Doc * github-profile:mkutz[Michael Kutz] - Addition of `{number-input-api}`, `{range-input-api}`, `{url-input-api}`, `{password-input-api}`, `{color-input-api}`, `{datetime-local-input-api}`, `{time-input-api}`, `{month-input-api}` and `{week-input-api}` * github-profile:kriegaex[Alexander Kriegisch] - Doc fixes * github-profile:topperfalkon[Harley Faggetter] - Doc fixes * github-profile:ArpitLT[Arpit Gupta] - Integration with LambdaTest * github-profile:JLLeitschuh[Jonathan Leitschuh] - Configure execution of Gradle Wrapper Validation GitHub Action on the project * github-profile:jrodalo[José Luis Rodríguez Alonso] - Website improvements * github-profile:sclassen[Stephan Classen] - Doc improvements * github-profile:pbielicki[Przemysław Bielicki] - Removal of deprecations from the build * github-profile:arixmkii[Arthur Sengileyev] - Dependency updates * github-profile:Vampire[Björn Kautler] - Various improvements == History This page lists the high level changes between versions of Geb. === {geb-version} ==== New features * Add an option to `waitFor()` to not throw `WaitTimeoutException` when the wait times out. [issue:644[]] * Cloud browser plugins are published to Gradle Plugin Portal. [issue:647[]] ==== Fixes * Fix a bug causing reports generated from within `cleanupSpec()` to not end up in the report group directory for the spec. [issue:661[]] === 5.1 ==== Improvements * Add support for Spock's parallel execution to `GebSpec` and `GebReportingSpec`. [issue:645[]] === 5.0 ==== Fixes * Fix a bug under Groovy 3 which caused PageInstanceNotInitializedException when ""container"" was used as a content element name. [issue:640[]] ==== Breaking changes * The `quitDriverOnBrowserReset` config option now default to true if driver caching is disabled. [issue:633[]] * Update Groovy to 3.0.8 and Spock to 2.0-groovy-3.0. [issue:619[]] * Don't make non-optional dependencies optional in various modules' POMs. [issue:638[]] === 4.1 ==== Fixes * Minor fix to confusing statement in the documentation section about finding and filtering web elements. [issue:625[]] * Improve information about IntelliJ support in the section on IDE authoring assistance in the manual. [issue:629[]] * Fix `Browser.go()` not to fail for non-hierarchical, opaque URIs. [issue:634[]] ==== New features * Add ability to compose multiple text matchers. [issue:631[]] * Add configuration option to quit the driver each time the browser instance is reset by `GebTestManager`. [issue:632[]] === 4.0 ==== Fixes * Fix failure reporting in Spock fixture methods. [issue:613[]] * Fix using constants (static final fields) is content definitions on Groovy 2.5.14. [issue:627[]] ==== New features * Add integration with JUnit 5. [issue:539[]] ==== Improvements * Introduce `{geb-test-manager-api}` to decrease code duplication between test framework integrations and make it easier for users to add integrations for additional frameworks. [issue:614[]] * Improve frame context management when nested withFrame() calls are used. [issue:612[]] ==== Breaking changes * Superclasses providing <> have been rewritten in a backwards incompatible way to benefit from introduction of `{geb-test-manager-api}`. [issue:614[]] * Geb no longer depends on `groovy-all` artifact but instead depends on `groovy`, `groovy-templates` and `groovy-macro` artifacts from `org.codehaus.groovy` group. [issue:618[]] * Update to Groovy 2.5.13. [issue:617[]] * Removed `geb.PageChangeListener` which was deprecated in favour of `geb.PageEventListener`. [issue:593[]] * Update to Gradle 6.7 and build the cloud browser Gradle plugin against it. [issue:622[]] * Rename tunnel id to tunnel name in the Gradle plugin for LambdaTest integration. [issue:606[]] === 3.4.1 ==== Fixes * Fix `Browser.setNetworkLatency()` on newer versions of Chrome. [issue:620[]] === 3.4 ==== New features * Add support for adding multiple test tasks per browser type to cloud browser gradle plugins. [issue:597[]] ==== Fixes * Fix an overflow for large `int` timeouts in `geb.Wait` causing `Browser.pause()` to fail and return instantly. [issue:605[]] * Update the message searched for in BrowserStack tunnel process output before considering it successfully as started after output changes in the latest version. [issue:607[]] * Update the message searched for in LambdaTest tunnel process output before considering it successfully as started after output changes in the latest version. [issue:608[]] * Fix detection of 64 bit architecture in Gradle tasks downloading BrowserStack and LambdaTest tunnel binaries. [issue:610[]] ==== Improvements * Make BrowserStack and LambdaTest tunnel ready messages configurable. [issue:611[]] === 3.3 ==== New features * Add ability to disable implicit assertions in particular waitFor block. [issue:578[]] * Add support to provide more information for UnexpectedPageException. [issue:596[]] * Add integration with LambdaTest. [issue:603[]] * Add a way to react when an unexpected page is encountered. [issue:598[]] * Add support for setting network throttling via setNetworkConditions Chrome command. [issue:602[]] ==== Fixes * `BindingUpdater` is not forwarding methods from `geb.textmatching.TextMatchingSupport` onto the `Browser` instance. [issue:601[]] ==== Improvements * Improve integration between cloud browser gradle plugins and driver factories. [issue:579[]] * Switch cloud driver factories to use https urls. [issue:599[]] * Pass SauceLabs credentials via capabilities and not the url. [issue:600[]] === 3.2 ==== Fixes * Unexpected pages are now only checked after checking that none of the pages passed to `Browser.page()` methods taking a list match. [issue:595[]] * Fix global atCheckWaiting in combination with to:[...] leading to potentially long delays. [issue:594[]] * Fix a MissingMethodException when `Browser.withFrame(Navigator, Class

, Closure)` is called. [issue:591[]] * Support accessing `Browser` instance from module base definitions. [issue:582[]] * Fix `withConfirm()` to work when accepting the dialog closes the window. [issue:568[]] === 3.1 ==== New features * Add a way to listen for navigator events. [issue:585[]] * Add a way to listen for page switching and at checking events. [issue:590[]] ==== Fixes * Add `Actions` methods added in WebDriver 3.x to `InteractDelegate` and expose the backing `Actions` instance. [issue:587[]] * Fix incorrect javadoc for `Configuration.isCacheDriverPerThread()`. [issue:592[]] === 3.0.1 ==== Fixes * Set the correct type of dependency on `groovy-all` in poms published for Geb artifacts. [issue:586[]] === 3.0 ==== Fixes * Use `Number` instead of `Double` for waitFor calls. [issue:570[]] * Make `RadioButtons` module extendable. [issue:562[]] * Fix selector optimisation when attributes map contains `GString` values. [issue:564[]] * Do not swallow the cause when instantiating `UnableToLoadException`. [issue:572[]] ==== New features * <>. [issue:557[]] * Support specifying data center specific hostname when using SauceLabsDriverFactory. [issue:573[]] * Allow specifying custom commandline switches for BrowserStack local tunnel command in geb-browserstack Gradle plugin. [issue:573[]] ==== Breaking changes * `geb.navigator.EmptyNavigator` class has been removed. [issue:557[]] * Signature of the method in `geb.navigator.factory.InnerNavigatorFactory` has been changed. [issue:557[]] * Multiple methods have been moved up from `geb.navigator.Locator` to `geb.navigator.BasicLocator`. [issue:557[]] * `geb.navigator.NonEmptyNavigator` has been renamed to `geb.navigator.DefaultNavigator`. [issue:557[]] * JUnit 3 support has been retired. [issue:532[]] * Update to Groovy 2.5.6. [issue:534[]] * Support for Groovy 2.3 has been removed. [issue:560[]] * Reports are now by default only taken only on test failure and not after every test. [issue:527[]] * Proxy settings for BrowserStackLocal, tunnel identifier and forcing all traffic through local machine are now configured in a different block when using geb-browserstack Gradle plugin. [issue:573[]] * Update to Spock 1.3, drop support for Spock 1.0. [issue:581[]] === 2.3.1 ==== Fixes * Fix setting value by text on multi select elements when the text within option tag contains trailing or leading spaces. [issue:563[]] === 2.3 ==== New features * Added form control modules for url, password and number inputs. [issue:548[]] * Added form control module for color inputs. [issue:549[]] * Added form control module for datetime-local inputs. [issue:550[]] * Added form control module for time inputs. [issue:554[]] * Added form control module for month inputs. [issue:552[]] * Added form control module for range inputs. [issue:551[]] * Added form control module for week inputs. [issue:553[]] * Added `focused()` method on `Navigable` which obtains a `Navigator` wrapping the active (focused) `WebElement`. [issue:546[]] * Ability to require at checkers to be defined even for pages that are implicitly at checked. [issue:541[]] ==== Fixes * Compatibility with latest Sauce Connect. [issue:559[]] ==== Improvements * Add an at() method to geb.Page which always throws MissingMethodException. [issue:543[]] * Improve signatures of methods in FrameSupport that take page objects to provide autocompletion inside of the closure passed as the last argument. [issue:540[]] * Resolve properties and methods in the closure passed to withNewWindow() and withWindow() against the browser. [issue:545[]] === 2.2 ==== New features * Make it more convenient to wait on something while reloading the page. [issue:499[]] * Added `waitCondition` content template option. [issue:342[]] * Added ability to disable use of tunnels in Gradle plugins for BrowserStack and SauceLabs. [issue:384[]] * Added `pause()` method to `Browser` class as an alternative to setting breakpoints when debugging. [issue:247[]] * Added ability to access names of content defined using the DSL at runtime. [issue:369[]] * Added ability to configure default values of content DSL template options. [issue:369[]] * Added ability to configure default values of options passed to `withWindow()` and `withNewWindow()`. [issue:406[]] * Added origin information to `TemplateDerivedPageContent` and `PageContentContainer`. [issue:446[]] * Added improved web storage support including management in test integrations. [issue:472[]] ==== Fixes * Fix translation of attribute map to css selector when finding elements for attribute value that is a GString. [issue:525[]] * Fix documentation around calling value() on unchecked checkboxes. [issue:520[]] * Make additional capabilities passed to cloud driver factory's `create()` method override the capabilities that are hardcoded for a particular cloud driver provider. [issue:372[]] * Fixed `getCheckedLabel()` on `RadioButtons` module to return label text instead of `null` when a checked radio button is wrapped by a label without a `for` attribute. [issue:530[]] * Fix links to manual sections that had non-unique ids. [issue:535[]] ==== Improvements * Support calling `GebReportingSpec#report(String)` from fixture methods. [issue:518[]] * Add method for performing assertions as part of an at check. [issue:405[]] * Document how to configure proxy to be used by the direct download API. [issue:371[]] * Enable taking reports for all windows if multiple are open. [issue:401[]] * Describe what constitutes a good at checker in the manual. [issue:512[]] * Document how to restart the browser mid-test. [issue:473[]] === 2.1 ==== New features * Added a form control module for search input. [issue:495[]] * Added a form control module for date input. [issue:496[]] * Added `FramesSourceReporter` which allows to report on the source content of each top level frame of the browser's current page. [issue:448[]] * Added form control modules for email and tel inputs. [issue:498[]] ==== Fixes * Fix reporting on failure in JUnit support when `reportOnTestFailureOnly` is set to true [issue:491[]] ==== Breaking changes * Actually remove `FileInput#getFile()` which was supposed to be removed for 2.0 but wasn't. [issue:503[]] === 2.0 ==== New features * Allow specifying the expected number of elements a content definition should return. [issue:149[]] ==== Fixes * Improved error message when trying to select null on a single-select select element. [issue:477[]] * Return a list of results instead of `null` from `newWindow()` methods taking a window matching specification closure. [issue:476[]] * Ignore case of tag names passed as part of css selectors to `Navigator.filter()` [issue:482[]] * Gracefully handle incorrectly encoded URIs returned from `WebDriver.getCurrentUrl()` when navigating to urls. [issue:492[]] ==== Improvements * Change signatures of methods from `FrameSupport` to be more strongly typed. [issue:470[]] ==== Breaking changes * Use Java 8 to compile the project. [issue:502[]] * Remove `FileInput#getFile()`. [issue:503[]] * Build using WebDriver 3.6.0. [issue:504[]] * Calling `click()` on empty navigators results in a `UnsupportedOperationException`. [issue:501[]] * Build using Spock 1.1. [issue:505[]] * Unchecked checkboxes return `null` as value for consistency with other input types. [issue:465[]] === 1.1.1 ==== Fixes * Do not double encode query parameters when building urls for arguments passed to `go()`, `to()` and `via()`. [issue:469[]] === 1.1 ==== Fixes * Delegate to `browser` instead of the module from blocks passed to `withFrame()` in module classes. [issue:461[]] * Fix implicit assertions in “at checkers” to not return `null` if the last call is to a void method. [issue:462[]] ==== Improvements * Support for selecting Edge as the browser using name in configuration. [issue:425[]] * Support for using url fragment identifiers when navigating to pages. [issue:463[]] * Unexpected pages are only checked after at check fails for the expected page. [issue:450[]] * Support equality checking between all core implementations of `Navigator`, based on comparing collections of web elements wrapped by them. [issue:459[]] * Support using label text to select checkboxes and using collections as value to select multiple checkboxes when dealing a number of checkboxes with the same name. [issue:460[]] ==== Deprecations * Grails 2.x plugin has been discontinued. [issue:456[]] === 1.0 ==== Fixes * Fix the direct field operator shortcut (`@`) for accessing element attributes to work on classes extending `Module`. [issue:438[]] * Fix reporting on failure only in `GebReportingSpec` to work with Spock 1.1. [issue:445[]] ==== Improvements * Add ability to unwrap modules returned from content dsl to their original type. [issue:434[]] * Add support for using attribute css selectors with navigator filtering methods like `filter()`, `not()`, `closest()`, etc. [issue:437[]] ==== Breaking changes * `geb.testng.GebTest` and `geb.testng.GebReportingTest` which were deprecated in 0.13.0 have been removed. * `isDisabled()`, `isEnabled()`, `isReadOnly()` and `isEditable()` methods of `Navigator` which were deprecated in 0.12.0 have been removed. * Loosely typed `module()` and `moduleList()` methods of the content DSL which were deprecated in 0.12.0 have been removed. === 0.13.1 ==== Fixes * Fix a MissingMethodException thrown from `Navigator.value()` when using Groovy versions < 2.4.0. [issue:422[]] * Don't unnecessarily synchronize methods of `CachingDirverFactory.ThreadLocalCache`. [issue:421[]] * Ensure `ConfigSlurper.parse(Script, URL)` is called in a thread safe way from `ConfigurationLoader`. [issue:423[]] === 0.13.0 ==== New features * `reportOnTestFailureOnly` config option is now also effective in Spock and JUnit4 integrations. [issue:92[]] * `isFocused()` method has been added to the `Navigator` class. [issue:208[]] * `InvalidPageContent` exception is thrown when a content is defined with a name that will result in that content being not accessible. [issue:109[]] [issue:122[]] * Ability to specify proxy location and credentials to use with BrowserStack tunnel. [issue:419[]] ==== Fixes * Fix a bug that caused reports for all but the last executed test class in TestNG integration to be wiped out. [issue:407[]] * Fix a bug preventing using module as a base of another module. [issue:411[]] * Restore `browser` property of `Module`. [issue:416[]] * Handle setting values of form elements that cause page change or reload when their value changes. [issue:155[]] ==== Improvements * Non-ASCII word characters are not longer replaced in report file names. [issue:399[]] * Change TestNG support to be based on traits. [issue:412[]] * Add `Navigator.moduleList()` methods as an alternative to the deprecated `moduleList()` methods available in the content DSL. [issue:402[]] * Add support for using Geb with Selendroid and other Selenium based frameworks for testing non-web applications. [issue:320[]] * Improve documentation for `Browser.clearCookies()` around what exactly is cleared, add a helper method for removing cookies across multiple domains. [issue:159[]] * Don't depend on UndefinedAtCheckerException for flow control. [issue:368[]] * Document that `Navigator.text()` returns the text of the element only if it's visible. [issue:403[]] * Make implementation of `interact()` less dynamic. [issue:190[]] * Improve documentation for `interact()`. [issue:207[]] * Don't unnecessarily request tag name and type attribute multiple times when setting text input values. [issue:417[]] * Improve usefulness of string representation of content elements. [issue:274[]] ==== Deprecations * `geb.testng.GebTest` and `geb.testng.GebReportingTest` have been deprecated in favour of `geb.testng.GebTestTrait` and `geb.testng.GebReportingTestTrait` respectively. ==== Breaking changes * Geb is now built with Groovy 2.4.5 and Spock 1.0-groovy-2.4. * The following `Navigator` methods now throw `SingleElementNavigatorOnlyMethodException` when called on a multi element `Navigator`: `hasClass(java.lang.String)`, `is(java.lang.String)`, `isDisplayed()`, `isDisabled()`, `isEnabled()`, `isReadOnly()`, `isEditable()`, `tag()`, `text()`, `getAttribute(java.lang.String)`, `attr(java.lang.String)`, `classes()`, `value()`, `click()`, `getHeight()`, `getWidth()`, `getX()`, `getY()`, `css(java.lang.String)`, `isFocused()`. [issue:284[]] === 0.12.2 ==== Fixes * Fix incorrect delegation in variant of `waitFor()` that takes timeout and interval. [issue:395[]] * Fix NPE on implicitly asserted statements that contain a safely navigated method call on null target. [issue:398[]] === 0.12.1 ==== Fixes * Change implementation of `waitFor()` method delegation so that IntelliJ does not complain that page and module classes supposedly need to implement it. [issue:391[]] * Properly handle class attribute when it's passed to `$()` together with a css selector. [issue:390[]] === 0.12.0 ==== New features * Support for finding elements using Webdriver's `{by-api}` selectors. [issue:348[]] * Support for navigating to page instances in addition to classes. [issue:310[]] * Support for using page instances as `page` option value of window switching methods. [issue:352[]] * Support for using page instances together with frame switching methods. [issue:354[]] * Support for using page instances with `Navigator.click()` methods. [issue:355[]] * Support for using page instances and lists of page instances as `page` option value of content templates. [issue:356[]] * New `Navigator.module(Class<? extends Module>)` and `Navigable.module(Class<? extends Module>)`. [issue:312[]] * New `Navigable.module(Module)` and `Navigable.module(Module)`. [issue:311[]] * Support for using `interact {}` blocks in modules. [issue:364[]] * Support page level `atCheckWaiting` configuration. [issue:287[]] * `Navigator` elements can now also be filtered using `hasNot()` method. [issue:370[]] * Custom implementation of `equals()` and `hashCode()` methods have been added to classes implementing `Navigator`. [issue:374[]] * Support setting `forcelocal` flag for BrowserStack tunnel. [issue:385[]] * Add configuration option for including cause string representation in message of `WaitTimeoutException`. [issue:386[]] ==== Improvements * Using unrecognized content template parameters result in an `InvalidPageContent` exception to make catching typos in them easier. [issue:377[]] * Improve error reporting when no at checkers pass if using multiple candidates for page switching. [issue:346[]] * Don't unnecessarily lookup root element for every baseless element lookup using `$()` in context of `Navigable`. [issue:306[]] * Attribute based searches are compiled to CSS selectors where possible. [issue:280[]] * Attribute based searches using an id, class or name are performed using an appropriate `By` selector where possible. [issue:333[]] ==== Fixes * Improved message thrown from Navigator.isDisabled() and Navigator.isReadOnly() when navigator does not contain a form element. [issue:345[]] * Browser.verifyAtIfPresent() should fail for at checkers returning false when implicit assertions are disabled. [issue:357[]] * Provide better error reporting when unexpected pages configuration is not a collection that contains classes which extend `Page`. [issue:270[]] * Don't fail when creating a report and driver's screenshot taking method returns null. [issue:292[]] * Classes that can define content should not throw custom exceptions from `propertyMissing()`. [issue:367[]] * “At checkers” of pages passed to `withFrame()` methods are now verified. [issue:358[]] ==== Breaking changes * `Page.toString()` now returns full page class name instead of its simple name. * `MissingPropertyException` is thrown instead of `UnresolvablePropertyException` when content with a given name is not found on page or module. * Geb is now built with Groovy 2.3.10 and Spock 1.0-groovy-2.3. ==== Deprecations * `module(Class<? extends Module>, Navigator base)` available in content DSL has been deprecated in favour of `Navigator.module(Class<? extends Module>)` and will be removed in a future version of Geb. * `module(Class<? extends Module>, Map args)` available in content DSL has been deprecated in favour of `Navigable.module(Module)` and will be removed in a future version of Geb. * `module(Class<? extends Module>, Navigator base, Map args)` available in content DSL has been deprecated in favour of `Navigator.module(Module)` and will be removed in a future version of Geb. * all variants of `moduleList()` method available in content DSL have been deprecated in favour of using `Navigator.module()` methods together with a `collect()` call and will be removed in a future version of Geb, see <> for examples [issue:362[]] * `isDisabled()`, `isEnabled()`, `isReadOnly()` and `isEditable()` methods of `Navigator` have been deprecated and will be removed in a future version of Geb. These methods are now available on the new <> module class. ==== Project related changes * User mailing list has moved to link:https://groups.google.com/d/forum/geb-user[Google Groups]. * The Book of Geb has been migrated to Asciidoctor and the examples have been made executable. [issue:350[]] === 0.10.0 ==== New features * New `css()` method on `Navigator` that allows to access CSS properties of elements. [issue:141[]] * Added attribute based methods to relative content navigators such as next(), children() etc. [issue:299[]] * Added signature that accepts `localIdentifier` to `BrowserStackDriverFactory.create`. [issue:332[]] * Added <> content definition option which allows specifying that page transition happens asynchronously. [issue:134[]] * Added support for explicitly specifying browser capabilities when using cloud browsers Gradle plugins. [issue:340[]] * Added an overloaded `create()` method on cloud driver factories that allow specifying browser capabilities in a map and don't require a string capabilities specification. [issue:281[]] ==== Fixes * Allow access to module properties from its content block. [issue:245[]] * Support setting of elements for WebDriver implementations that return uppercase tag name. [issue:318[]] * Use native binaries for running BrowserStack tunnel. [issue:326[]] * Update BrowserStack support to use command-line arguments introduced in tunnel version 3.1. [issue:332[]] * Fix PermGen memory leak when using groovy script backed configuration. [issue:335[]] * Don't fail in `Browser.isAt()` if at check waiting is enabled and it times out. [issue:337[]] * The value passed to `aliases` content option in documentation examples should be a String [issue:338[]] * Added `$()` method on Navigator with all signatures of `find()`. [issue:321[]] * `geb-saucelabs` plugin now uses a native version of SauceConnect. [issue:341[]] * Don't modify the predicate map passed to link:api/geb/navigator/BasicLocator.html#find(Map,%20java.lang.String)[""`Navigator.find(Map<String, Object>, String)`""]. [issue:339[]] * Functional tests implemented using JUnit and Geb run twice in Grails 2.3+. [issue:314[]] * Mention in the manual where snapshot artifacts can be downloaded from. [issue:305[]] * Document that `withNewWindow()` and `withWindow()` switch page back to the original one. [issue:279[]] * Fix selectors in documentation for manipulating checkboxes. [issue:268[]] ==== Project related changes * Updated cucumber integration example to use `cucumber-jvm` instead of the now defunct `cuke4duke`. [issue:324[]] * Setup CI for all of the example projects. [issue:188[]] * Incorporate the example projects into the main build. [issue:189[]] * Add a test crawling the site in search for broken links. [issue:327[]] * Document the link:https://github.com/geb/geb/blob/master/RELEASING.md[release process]. [issue:325[]] ==== Breaking changes * Use Groovy 2.3.6 to build Geb. [issue:330[]] * Format of browser specification passed to `BrowserStackBrowserFactory.create()` and `SauceLabsBrowserFactory.create()` has changed to be a string in Java properties file format defining the required browser capabilities. * `sauceConnect` configuration used with `geb-saucelabs` plugin should now point at a version of 'ci-sauce' artifact from 'com.saucelabs' group. === 0.9.3 ==== New features * Added `baseNavigatorWaiting` setting to prevent intermittent Firefox driver errors when creating base navigator. [issue:269[]] * Page content classes including `Module` now implement `Navigator` interface [issue:181[]] * Added some tests that guard performance by verifying which WebDriver commands are executed [issue:302[]] * Added link:http://www.browserstack.com[BrowserStack] integration [issue:307[]] * Added a shortcut to `Browser` for getting current url [issue:294[]] * Verify pages at checker when passed as an option to open a new window via `withWindow()` and `withNewWindow()` [issue:278[]] ==== Fixes * Ignore `atCheckWaiting` setting when checking for unexpected pages. [issue:267[]] * Added missing range variants of find/$ methods. [issue:283[]] * Migrated `UnableToLoadException` to java. [issue:263[]] * Exception thrown when trying to set value on an invalid element (non form control). [issue:286[]] * Support for jQuery methods like offset() and position() which return a native Javascript object. [issue:271[]] * Finding elements when passing ids with spaces in the predicates map to the $() method. [issue:308[]] ==== Breaking changes * Removed easyb support. [issue:277[]] * `MissingMethodException` is now thrown when using shortcut for obtaining a navigator based on a control name and the returned navigator is empty. [issue:239[]] * When using SauceLabs integration, the `allSauceTests` task was renamed to`allSauceLabsTests` * When using SauceLabs integration, the `geb.sauce.browser` system property was renamed to `geb.saucelabs.browser` * `Module` now implements `Navigator` instead of `Navigable` so `Navigator`'s methods can be called on it without having to first call `$()` to get the module's base `Navigator`. ==== Project related changes * Documentation site has been migrated to link:http://ratpack.io[Ratpack]. [issue:261[]] * Cross browser tests are now also executed using Safari driver [issue:276[]] * Artifact snapshots are uploaded and gebish.org is updated after every successful build in CI [issue:295[]] * Added a link:https://travis-ci.org/geb/geb[Travis CI build] that runs tests on submitted pull requests [issue:309[]] === 0.9.2 ==== New features * `page` and `close` options can be passed to `withWindow()` calls, see <> for more information. * Unexpected pages can be specified to fail fast when performing “at” checks. This feature was contributed at a Hackergarten thanks to Andy Duncan. See <> for details. [issue:70[]] * Support for running Geb using SauceLabs provided browsers, see <> for details. * New `isEnabled()` and `isEditable()` methods on `Navigator`. * Support for ephemeral port allocation with Grails integration * Compatibility with Grails 2.3 ==== Fixes * Default value of `close` option for `withNewWindow()` is set to `true` as specified in the documentation. [issue:258[]] ==== Breaking changes * `isDisabled()` now throws `UnsupportedOperationException` if called on an `EmptyNavigator` or on a `Navigator` that contains anything else than a button, input, option, select or textarea. * `isReadOnly()` now throws `UnsupportedOperationException` if called on an `EmptyNavigator` or on a `Navigator` that contains anything else than an input or a textarea. === 0.9.1 ==== Breaking changes * Explicitly calling `at()` with a page object will throw `UndefinedAtCheckerException` instead of silently passing if the page object does not define an at checker. * Passing a page with no at checker to `click(List<Class<? extends Page>>)` or as one of the pages in `to` template option will throw `UndefinedAtCheckerException`. ==== New features * Support for dealing with self-signed certificates in Download API using `SelfSignedCertificateHelper`. [issue:150[]] * Connections created when using Download API can be configured globally using `defaultDownloadConfig` configuration option. * New `atCheckWaiting` configuration option allowing to implictly wrap “at” checkers in `waitFor` calls. [issue:253[]] ==== Fixes * `containsWord()` and `iContainsWord()` now return expected results when matching against text that contains spaces [issue:254[]] * `has(Map<String, Object> predicates, String selector)` and `has(Map<String, Object> predicates)` were added to Navigator for consistency with `find()` and `filter()` [issue:256[]] * Also catch WaitTimeoutException when page verification has failed following a `click()` call [issue:255[]] * `not(Map<String, Object> predicates, String selector)` and `not(Map<String, Object> predicates)` were added to Navigator for consistency with `find()` and `filter()` [issue:257[]] * Make sure that `NullPointerException` is not thrown for incorrect driver implementations of getting current url without previously driving the browser to a url [issue:291[]] === 0.9.0 ==== New features * New `via()` method that behaves the same way as `to()` behaved previously - it sets the page on the browser and does not verify the at checker of that page[issue:249[]]. * It is now possible to provide your own `{navigator-api}` implementations by specifying a custom link:api/geb/navigator/factory/NavigatorFactory.html[`NavigatorFactory`], see <> for more information [issue:96[]]. * New variants of `withFrame()` method that allow to switch into frame context and change the page in one go and also automatically change it back to the original page after the call, see [switching pages and frames at once][switch-frame-and-page] in the manual [issue:213[]]. * `wait`, `page` and `close` options can be passed to `withNewWindow()` calls, see <> for more information [issue:167[]]. * Improved message of UnresolvablePropertyException to include a hint about forgetting to import the class [issue:240[]]. * Improved signature of `Browser.at()` and `Browser.to()` to return the exact type of the page that was asserted to be at / was navigated to. * link:api/geb/report/ReportingListener.html[`ReportingListener`] objects can be registered to observe reporting (see: <>) ==== Fixes * Fixed an issue where waitFor would throw a WaitTimeoutException even if the last evaluation before timeout returned a truthy value [issue:215[]]. * Fixed taking screenshots for reporting when the browser is not on a HTML page (e.g. XML file) [issue:126[]]. * Return the last evaluation value for a `(wait: true, required: false)` content instead of always returning null [issue:216[]]. * `isAt()` behaves the same as `at()` in regards to updating the browser's page instance to the given page type if its at checker is successful [issue:227[]]. * Handling of `select` elements has been reworked to be far more efficient [issue:229[]]. * Modules support accessing base attributes' values using @attributeName notation [issue:237[]]. * Use of text matchers in module base definitions is supported [issue:241[]]. * Reading of textareas have been updated so that the current value of the text field is returned, instead of the initial [issue:174[]]. ==== Breaking changes * `to(Class<? extends Page>)` method now changes the page on the browser and verifies the at checker of that page in one method call [issue:1[]], [issue:249[]]; use `via()` if you need the old behaviour * `getAttribute(String)` on `Navigator` now returns `null` for boolean attributes that are not present. * `at()` and `to()` methods on `Browser` now return a page instance if they succeed and `via()` method always returns a page instance [issue:217[]]. * `withFrame()` calls that don't take a page argument now change the browser page to what it was before the call, after the call [issue:222[]]. * due to performance improvements duplicate elements are not removed when creating new `Navigator`s anymore; the new `unique()` method on `Navigator` can be used to remove duplicates if needed [issue:223[]]. * `at(Page)` and `isAt(Page)` methods on `Browser` have been removed as they were inconsistent with the rest of the API [issue:242[]]. * Navigator's `click(Class<? extends Page>)` and `to:` content option now verify page after switching to the new one to stay consistent with the new behaviour of `to(Class<? extends Page>)` [issue:250[]]. * Reading an attribute that is not set on a navigator now returns an empty string across all drivers [issue:251[]]. === 0.7.2 ==== Fixes * Further fixes for Java 7 [issue:211[]]. === 0.7.1 ==== New features * Geb is now built with Groovy 1.8.6. This was forced to resolve [issue:194[]]. ==== Fixes * `startsWith()`, `contains()` etc. now work for selecting via element text now works for multiline (i.e. `<br/>`) text [issue:202[]] * Geb now works with Java 7 [issue:194[]]. === 0.7.0 ==== New features * Added support for indexes and ranges in `moduleList()` method * Form control shortcuts now also work on page and module content * Custom timeout message for `waitFor()` calls * Navigators can be composed also from content * Closure expressions passed to `waitFor()` calls are now transformed so that every statement in them is asserted - this provides better reporting on `waitFor()` timeouts. * `at` closure properties of Page classes are now transformed so that every statement in them is asserted - this provides better reporting on failed at checks * new `isAt()` method on Browser that behaves like `at()` used to behave before, i.e. does not throw AssertionError but returns `false` if at checking fails * `withAlert()` and `withConfirm()` now accept a `wait` option and the possible values are the same as for waiting content ==== Breaking changes * `click()` now instructs the browser to click *only on the first* element the navigator has matched * All `click()` method variants return the reciever * Content definitions with `required: false, wait: true` return `null` and do not throw `WaitTimeoutException` if the timeout expires * Assignment statements are not allowed anymore in closure expressions passed to `waitFor()` calls * `at()` now throws AssertionException if at checking fails instead of returning false === 0.6.3 ==== New features * Compatibility with Spock 0.6 === 0.6.2 ==== New features * New `interact()` function for mouse and keyboard actions which delegates to the WebDriver Actions class * New `moduleList()` function for repeating content * New `withFrame()` method for working with frames * New `withWindow()` and `withNewWindow()` methods for working with multiple windows * Added `getCurrentWindow()` and `getAvailableWindows()` methods to browser that delegate to the underlying driver instance * Content aliasing is now possible using `aliases` parameter in content DSL * If config script is not found a config class will be used if there is any - this is usefull if you run test using Geb from IDE * Drivers are now cached across the whole JVM, which avoids the browser startup cost in some situations * Added config option to disable quitting of cached browsers on JVM shutdown ==== Breaking changes * The `Page.convertToPath()` function is now responsible for adding a prefix slash if required (i.e. it's not added implicitly in `Page.getPageUrl()`) [GEB-139]. * Unchecked checkboxes now report their value as `false` instead of null === 0.6.1 ==== New features * Compatibility with at least Selenium 2.9.0 (version 0.6.0 of Geb did not work with Selenium 2.5.0 and up) * Attempting to set a select to a value that it does not contain now throws an exception * The waiting algorithm is now time based instead of number of retries based, which is better for blocks that are not near instant * Better support for working with already instantiated pages ==== Breaking changes * Using `<select>` elements with Geb now requires an explicit dependency on an extra WebDriver jar (see <>) * The `Navigator` `classes()` method now returns a `List` (instead of `Set`) and guarantees that it will be sorted alphabetically === 0.6 ==== New features * selenium-common is now a 'provided' scoped dependency of Geb * Radio buttons can be selected with their label text as well as their value attribute. * Select options can be selected with their text as well as their value attribute. * `Navigator.getAttribute` returns `null` rather than the empty string when an attribute is not found. * The `jquery` property on `Navigator` now returns whatever the jQuery method called on it returns. * All waitFor clauses now treat exceptions raised in the condition as an evaluation failure, instead of propagating the exception * Content can be defined with `wait: true` to make Geb implicitly wait for it when it is requested * Screenshots are now taken when reporting for all drivers that implement the `TakesScreenshot` interface (which is nearly all) * Added `BindingUpdater` class that can manage a groovy script binding for use with Geb * Added `quit()` and `close()` methods to browser that delegate to the underlying driver instance * `geb.Browser.drive()` methods now return the used `Browser` instance * The underlying WebElements of a Navigator are now retrievable * Added $() methods that take one or more Navigator or WebElement objects and returns a new Navigator composed of these objects * Added Direct Download API which can be used for directly downloading content (PDFs, CSVs etc.) into your Geb program (not via the browser) * Introduced new configuration mechanism for more flexible and environment sensitive configuration of Geb (e.g. driver implementation, base url) * Default wait timeout and retry interval is now configurable, and can now also use user configuration presets (e.g. quick, slow) * Added a “build adapter” mechanism, making it easier for build systems to take control of relevant configuration * The JUnit 3 integration now includes the test method name in the automatically generated reports * The reporting support has been rewritten, making it much friendlier to use outside of testing * Added the TestNG support (contributed by Alexander Zolotov) * Added the `height`, `width`, `x` and `y` properties to navigator objects and modules ==== Breaking changes * Raised minimum Groovy version to 1.7 * All failed waitFor clauses now throw a `geb.waiting.WaitTimeoutException` instead of `AssertionError` * Upgraded minimum version requirement of WebDriver to 2.0rc1 * The `onLoad()` and `onUnload()` page methods both have changed their return types from `def` to `void` * The Grails specific testing subclasses have been REMOVED. Use the direct equivalent instead (e.g `geb.spock.GebReportingSpec` instead of `grails.plugin.geb.GebSpec`) * The Grails plugin no longer depends on the test integration modules, you need to depend on the one you want manually * The `getBaseUrl()` method from testing subclasses has been removed, use the configuration mechanism * Inputs with no value now report their value as an empty string instead of `null` * Select elements that are not multiple select enabled no longer report their value as a 1 element list, but now as the value of the selected element (if no selection, `null` is returned) === 0.5.1 * Fixed problem with incorrectly compiled specs and the geb grails module === 0.5 ==== New features * Navigator objects now implement the Groovy truth (empty == false, non empty == true) * Introduced “js” short notation * Added “easyb” support (`geb-easyb`) and Grails support * Page change listening support through `geb.PageChangeListener` * `waitFor()` methods added, making dealing with dynamic pages easier * Support for `alert()` and `confirm()` dialogs * Added jQuery integration * Reporting integration classes (e.g. GebReportingSpec) now save a screenshot if using the FirefoxDriver * Added `displayed` property to navigator objects for determining visibility * Added `find` as an alias for `$` (e.g. `find("div.section")`) * Browser objects now implement the `page(List<Class>)` method that sets the page to the first type whose at-checker matches the page * The click() methods that take one or more page classes are now available on `Navigator` objects * Added page lifecycle methods `onLoad()`/`onUnload()` ==== Breaking changes * Exceptions raised in `drive()` blocks are no longer wrapped with `DriveException` * the `at(Class pageClass)` method no longer requires the existing page instance to be of that class (page will be updated if the given type matches) === 0.4 *Initial Public Release* :numbered: ",12096,False,2385.7631373301638,median "= PlanWithEase - User Guide :site-section: UserGuide :toc: :toc-title: :toc-placement: preamble :toclevels: 3 :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full :experimental: ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: endif::[] :repoURL: https://github.com/CS2113-AY1819S2-T09-1/main By: `Team T09-1` Since: `Feb 2019` Licence: `MIT` == Introduction *PlanWithEase* (PWE) is an application designed to help National University of Singapore (NUS) Information Security freshmen in creating a comprehensive degree plan according to the degree requirements. *PWE* is optimized for those who prefer using a Command Line Interface (CLI). The commands used to interact with *PWE* are designed to be simple and intuitive, so even those who are unfamiliar with CLI can use *PWE* with ease. *PWE* also comes with a clean Graphical User Interface (GUI) that presents information in an organized manner. Interested in using *PWE* to plan your degree easily? Jump to <> to get started! == Understanding This User Guide === Basic Information This user guide provides a quick start guide for you to easily setup and install *PlanWithEase*. You can find all the details of *PlanWithEase*'s features, tips, frequently asked questions and a summary of the available commands. To navigate between the different sections easily, you can use the <> above. The following symbols are used throughout this user guide: [NOTE] ==== This symbol denotes information that you may want to take note of. ==== [TIP] ==== This symbol denotes a tip which you may find useful when using our application. ==== [WARNING] ==== This symbol denotes a warning message which you need to be careful of when using our application. ==== Additionally, you may also encounter the following text styles: ==== * Commands, parameters and file paths will be in this `format` * Important messages will be *bold* * Undoable command will be in _italics_ * Keyboard buttons will be referred to as such: kbd:[F1] ==== === Navigating Around Our Application *PlanWithEase* comes with a very clean and easy to use Graphical User Interface, so don't worry even if you are a new user! You can expect to navigate around our application with ease! [[GUI]] .PlanWithEase's Graphical User Interface ifdef::env-github[] image::UiLabelled.png[width=""800""] endif::[] ifndef::env-github[] image::UiLabelled.png[width=""970""] endif::[] *PlanWithEase* has five main sections that you'll need to know before you get started!. + The five main sections are explained below. [cols=""<20%,25%,40%""] |==== |*Section*| *Name* | *Description* | 1 | Command Box | This is where you can enter and run commands. | 2 | Result Box | This provides you with information on whether a command is successful. If there are errors when running the command, information on how to rectify the errors will also be displayed in here. | 3 | Module List | This is where you can view the details of all the modules. You can use the commands in <> to make changes to the *Module List*. | 4 | Requirement Categories | This is where you can view your degree progress. You can use the commands in <> to make changes to the *Requirement Categories*. | 5 | Degree Plan | This is where you can view your degree plan. You can use the commands in <> to make changes to the *Degree Plan*. |==== == Quick Start . Ensure you have *Java version 9* installed in your Computer. . Download the latest `PWE.jar` link:{repoURL}/releases/latest[here]. . Copy the file to the folder you want to use as the home folder for *PlanWithEase*. . Double-click the file to start the app. The GUI should appear in a few seconds. + .Successful start up of *PlanWithEase* ifdef::env-github[] image::Ui.png[width=""800""] endif::[] ifndef::env-github[] image::Ui.png[width=""970""] endif::[] + . You can now try entering commands in the *command box* and press kbd:[Enter] to execute it! + e.g. typing *`help`* and pressing kbd:[Enter] will open the help window. . Below are some example commands you can try: * *`list`* : list and displays all modules in the *module list*. * **`add`**`name/Programming Methodology code/CS1010 credits/4` : adds a module named `Programming Methodology` with module code `CS1010`, which is assigned `4` modular credits, to the module list. * **`delete`**`3` : deletes the 3^rd^ module shown in the *module list*. * *`exit`* : exits the application . Refer to <> for details of each command. [[Features]] == Features In this section, the expected command format will be introduced, and you can expect to learn the various commands you can use. [NOTE] ==== Don't worry if you don't understand everything at once. + There are plentiful examples provided to aid your understanding of the commands' usage better. ==== *Command Format* * Words in `UPPER_CASE` are the parameters to be supplied by the user ** e.g. in `add name/NAME`, `NAME` is a parameter which can be used as: .. `add name/Programming Methodology` .. `add name/Web Security` * Items in square brackets are optional parameters ** e.g. `name/NAME [tag/TAG]` can be used as: .. `name/Database Systems tag/sql` (with optional `tag` parameter) .. `name/Database Systems` (without optional `tag` parameter) * Items with `…`​ after them are parameters that can be used multiple times (including zero times) ** e.g. `[tag/TAG]…` can be used as: .. `{nbsp}` (i.e. 0 times) .. `tag/programming` (i.e. 1 time) .. `tag/programming tag/algorithms`, etc. (i.e. many times) ** e.g. `[name/NAME NAME…]` can be used as: .. `{nbsp}` (i.e. 0 times) .. `name/Programming` (i.e. 1 time) .. `name/Programming Methodology`, etc. (i.e. many times) * Prefixed-parameters can be arranged in any order after all non-prefixed parameters (if any) ** e.g. if the command specifies `INDEX name/NAME code/CODE`: .. entering `INDEX code/CODE name/NAME` is also acceptable, but .. entering `name/NAME INDEX code/CODE` is *not acceptable* [WARNING] ==== Parameter values cannot be empty (unless otherwise stated). ==== === General Commands ==== Viewing help : `help` image:https://img.shields.io/badge/general-help-8774C1.svg[] Don't worry if you are feeling lost! You can use this User Guide document to gain a better understanding of *PlanWithEase*'s commands. To open this User Guide document, simply enter `help` in the *command box*. [TIP] ==== Alternatively, you can access this User Guide document by pressing kbd:[F1] or via the menu bar (as shown below). [[f1-help]] .Accessing help from menu bar image::helpLabelled.png[width=400] ==== ==== Listing entered commands : `history` image:https://img.shields.io/badge/general-history-8774C1.svg[] Want to check what commands you have entered previously? Simply enter `history` in the *command box*! The list of commands will be displayed in reverse chronological order (from most recent to earliest). + [TIP] ==== You can press the kbd:[↑] and kbd:[↓] arrows to display the previous and next input respectively in the *command box*. ==== // tag::undoredo[] ==== Undoing previous command: `undo` image:https://img.shields.io/badge/general-undo-8774C1.svg[] Made a critical mistake such as accidentally clearing all modules from *PlanWithEase* and you want to get the data back? + No problem! You can simply enter `undo` in the *command box* to restore PlanWithEase's data to the state before the previous _undoable_ command was executed! [NOTE] ==== _Undoable_ commands are commands that modifies the contents of PlanWithEase's data. + Below is a list of all _undoable_ commands in *PlanWithEase*. |==== | *General* | *Module Management* | *Requirement Tracker* | *Degree Plan Management* a| * `undo` * `redo` * `clear` * `reset` a| * `add` * `edit` * `delete` a| * `requirement_add` * `requirement_move` a| * `planner_add` * `planner_remove` * `planner_move` |==== ==== *Examples:* * `delete 1` (deletes first module in the displayed module list) + `list` (displays all modules in the module list) + `undo` (reverses the `delete 1` command) + * `find name/Programming` (finds modules with name containing the word `Programming` and displays them in the module list) + `list` (displays all modules in the module list) + `undo` (the `undo` command fails as there are no undoable commands executed previously) * `delete 1` (deletes first module in the displayed module list) + `clear` (clears all application data) + `undo` (reverses the `clear` command) + `undo` (reverses the `delete 1` command) + ==== Redoing previously undone command : `redo` image:https://img.shields.io/badge/general-redo-8774C1.svg[] Took too many steps back in time using the `undo` command and want to move forward in time again? + Use the `redo` command to reverse the most recent `undo` command! [WARNING] ==== Be careful when time travelling using the `undo` and `redo` command! + You may end up being stuck in the present and can't go back into the future using the `redo` command. This can happen if you you run an _undoable_ command (excluding `undo` and `redo`) when going back in time using the `undo` command! ==== *Examples:* * `delete 1` (deletes first module in the displayed module list) + `undo` (reverses the `delete 1` command) + `redo` (reapplies the `delete 1` command) + * `delete 1` (deletes first module in the displayed module list) + `redo` (the `redo` command fails as there are no `undo` commands executed previously) * `delete 1` (deletes first module in the displayed module list) + `clear` (clears all modules from the application) + `undo` (reverses the `clear` command) + `undo` (reverses the `delete 1` command) + `redo` (reapplies the `delete 1` command) + `redo` (reapplies the `clear` command) + // end::undoredo[] // tag::clear[] ==== Clearing modules : `clear` image:https://img.shields.io/badge/general-clear-8774C1.svg[] Want to clear all the modules in the *module list*, *requirement categories* or *degree plan*? You'll definitely want to use the `clear` command! The `clear` command allows you to remove all modules from the specified section (i.e. *module list*, *requirement categories*, *degree plan*). *Command Format:* `clear [requirement or planner]` + [NOTE] ==== If no parameters are specified, all modules in the *module list*, *requirement categories* and *degree plan* will be deleted. ==== [TIP] ==== If you want to delete all modules in the *module list* quickly, simply enter the `clear` command in the *command box* without specifying any parameters! + ==== *Command Usage:* [cols=""20%,35%,45%""] |==== |*Input* | *Behaviour* | *Expected Results* | `clear` | Clears all *modules* from the application | The *module list* will be emptied. Additionally, all modules in the *requirement categories* and *degree plan* will be removed. | `clear requirement` | Clears all *modules* in all *requirement categories* | The *requirement categories* will be emptied. |`clear planner`| Clears all *modules* in all *degree plan* | The *degree plan* will be emptied. |==== *Example:* Here's an example of how *PlanWithEase* would look like after executing the `clear` command. + Notice that a success message will be displayed after clearing all modules from *PlanWithEase*. Before running the `clear` command: [[beforeClear]] .Before executing the `clear` command. ifdef::env-github[] image::clearbefore.png[width=800] endif::[] ifndef::env-github[] image::clearbefore.png[width=970] endif::[] After entering `clear` and pressing kbd:[Enter]: [[afterClear]] .After executing the `clear` command. ifdef::env-github[] image::clearafter.png[width=800] endif::[] ifndef::env-github[] image::clearafter.png[width=970] endif::[] // end::clear[] ==== Reset the application: `reset` image:https://img.shields.io/badge/general-reset-8774C1.svg[] If you want to populate the program with our sample modules, you can enter `reset` in the *command box* + This will save you the trouble of adding new `module` again! [NOTE] ==== This will *discard* all changes you have made and populate the program with our sample modules. ==== [TIP] ==== If you unintentionally used this command, do use the `undo` command to revert back the changes ==== ==== Exiting PlanWithEase : `exit` image:https://img.shields.io/badge/general-exit-8774C1.svg[] If you want to exit *PlanWithEase*, you can enter `exit` in the *command box*. + Hope you had a wonderful experience using *PlanWithEase*. Do come back soon! // tag::module_management[] === Module Management In this section, you'll be introduced to commands that helps you to manage modules in *PlanWithEase*. Below is a list of command parameters that you can expect to use for commands in this section. [cols=""18%,37%,45%""] |====== |*Parameter*| *Description* | *Acceptable Range of Values* | `CODE` | Indicates the module code + (e.g. `CS2101`). | `CODE` should begin with two alphabets, followed by four digits, and may optionally end with an alphabet. + `CODE` is insensitive and must be unique | `NAME` | Indicates the name of the module + (e.g. `Effective Communication for Computing Professionals`). | `NAME` should only contain alphanumeric characters, punctuations (excluding ""("", "")"", ""&"", ""\\|"") and spaces. + Note that if you are using punctuations, you may want to consider replacing ""()"" with ""[]"", ""&"" with ""and"", and ""\\|"" with ""l"" (lowercase L) instead! + | `CREDITS` | Indicates the modular credits assigned to the module + (e.g. `4` Modular Credits). | `CREDITS` should be whole numbers between 0 to 999 (both inclusive). | `SEMESTER` | Indicates the semester which the module is offered in. + (e.g. Semester `1`) | `SEMESTER` should only be either `1`, `2`, `3` or `4`. + `3` and `4` indicates special term semesters 1 and 2 respectively. | `COREQUISITE` | Indicates the module code of a co-requisite module. + (e.g. `CS2101` is a co-requisite module of `CS2113T`) | `COREQUISITE` follow the same format as `CODE`. | `TAG` | Indicates the extra information to associate the module with (e.g. `Presentation`, `Email`). | `TAG` should only contain alphabets and numbers. |====== // end::module_management[] // tag::module_add[] ==== Adding modules : `add` image:https://img.shields.io/badge/module-add-blue.svg[] Before you can add modules to the *degree plan*, you'll need to add modules into the *module list* first. + It's easy to add a module into the *module list*! Here's how you can use the `add` command. *Command Format:* `add code/CODE name/NAME credits/CREDITS [sem/SEMESTER]… [coreq/COREQUISITE]… [tag/TAG]…` [WARNING] ==== Please note that you cannot add a new module which has a co-requisite module already existing in the *degree plan*. + You'll need to remove the module from the *degree plan* first before you can add the new module in with the co-requisite module specified. ==== *Example:* * `add code/GEH1074 name/Luck credits/4 sem/1 sem/2` + Adds a module named `Luck` with module code `GEH1074`, which is assigned `4` modular credits and is offered in semesters `1` and `2`, to the *module list*. .New module ""GEH1074 Luck"" added to *module list* successfully ifdef::env-github[] image::module_add_luck.png[width=800] endif::[] ifndef::env-github[] image::module_add_luck.png[width=970] endif::[] [NOTE] ==== When adding a module with a corequisite, if the module is added successfully, the co-requisite modules will be updated as well. ==== *Example:* + * `add name/Skills code/GEH1074T credits/4 sem/1 sem/2 coreq/GEH1074 tag/GEM tag/economics` + Adds a module named `Skills` with module code `GEH1074T`, which is assigned `4` modular credits and has module code `GEH1074` as a corequisite, to the module list. + Both modules (`GEH1074T` and `GEH1074`) will be updated to be co-requisites as shown below. .Module GEH1074T is added successfully; GEH1074T and GEH1074 are now co-requisites. ifdef::env-github[] image::module_add_coreq.png[width=800] endif::[] ifndef::env-github[] image::module_add_coreq.png[width=970] endif::[] // end::module_add[] // tag::module_edit[] ==== Editing modules : `edit` image:https://img.shields.io/badge/module-edit-blue.svg[] Want to change the module details? No problem! + You can use this handy `edit` command to update the module details to your liking. *Command Format:* `edit INDEX [name/NAME] [code/CODE] [credits/CREDITS] [sem/SEMESTER]… [coreq/COREQUISITE]… [tag/TAG]…` [NOTE] ==== * Edits the module at the specified `INDEX`. The index refers to the index number (beside the module code) shown in the displayed module list. * You need to provide at least one of the optional fields to edit. * Existing values will be updated to the input values. * When editing semesters/corequisites/tags, the existing semesters/corequisites/tags of the module will be removed (i.e adding of semesters/corequisites/tags is not cumulative.) * You can remove all the module's tags by typing `tag/` without specifying any tags after it. * Likewise, you can remove all module's co-requisites or semesters by typing `coreq/` and `sem/` respectively without specifying any values after the parameter prefix. ==== Examples: * `edit 1 name/Data Structures and Algorithms code/CS2040C` + Edits the name and code of the 1^st^ module in the displayed module list to be `Data Structures and Algorithms` and `CS2040C` respectively. + * `edit 2 code/CS2040C tag/` + Edits the code of the 2^nd^ module in the displayed module list to be `CS2040C` and clears all existing tags associated with the module. + * `edit 3 coreq/CS2105 coreq/CS2106 coreq/CS2107` + Edits the co-requisites of the 3^rd^ module in the displayed module list to be `CS2105`, `CS2106` and `CS2107`. + [NOTE] ==== Just like the `add` command, when editing the co-requisites of a module, the co-requisite modules will be updated as well. ==== *Example:* If `GEH1074` and `GEH1074T` are not co-requisites, running the command `edit 24 coreq/GEH1074T` will result in GEH1074 and GEH1074T being co-requisites. .GEH1074 and GEH1074T are being edited to be co-requisites. ifdef::env-github[] image::module_edit_coreq.png[width=800] endif::[] ifndef::env-github[] image::module_edit_coreq.png[width=970] endif::[] // end::module_edit[] // tag::module_delete[] ==== Deleting modules : `delete` image:https://img.shields.io/badge/module-delete-blue.svg[] Want to delete a module from the *module list*? Simply locate the module to be deleted in the *module list*, and then use the `delete` command! *Command Format:* `delete INDEX` [NOTE] ==== To choose which module you want to delete, include the index number (beside the module code) in the displayed module list. ==== [WARNING] ==== * The deleted module will be removed from both the requirement category assigned and the degree plan (where applicable). * Any modules with the deleted module as a co-requisite will be updated accordingly (i.e. deleted module is removed from the respective module's co-requisite list). ==== *Example:* If `GET1074T` and `GET1074` are co-requisite modules, deleting `GET1074` will cause `GET1074` 's list of co-requisite modules to be updated as well. .`GET1074` is removed from `GET1074` 's list of co-requisites. ifdef::env-github[] image::module_delete_coreq.png[width=800] endif::[] ifndef::env-github[] image::module_delete_coreq.png[width=970] endif::[] // end::module_delete[] // tag::find[] ==== Finding modules : `find` image:https://img.shields.io/badge/module-find-blue.svg[] Having trouble locating the modules you want? Make use of `find` command which allows you to find modules that have their names, code or credits matching the given search criteria. *Command Format:* `find [name/NAME] OPERATOR [code/CODE] OPERATOR [credits/CREDITS]` When this command is used, the application will display only those modules which satisfy the search criteria. The following table describes the valid prefixes that you can supply to the search criteria. |==== | *Prefix* | *Description* | `name/NAME` | Search for any module `name` which matches `NAME` | `code/CODE` | Search for any module `code` which matches `CODE` | `credits/CREDITS` | Search for any module `credits` which has `CREDITS` | `tag/TAG` | Search for any module `tag` which matches `TAG` | `sem/SEMESTER` | Search for any module that is being offered in `SEMESTER` |==== The following table describes the valid operators which you can supply to the search criteria. |==== | *Operator* | *Description* | *Precedence* | `&&` | Logical ""AND"" operation (both conditions A AND B must match) | Highest | `\\|\\|` | Logical ""OR"" operation (either conditions A OR B must match)| Lowest a| `(` and `)` | Search term surrounded by parenthesis will always be evaluated first. If there is a tie, the logical operator precedence will be taken into consideration. | N.A |==== The following examples describes how you could form a valid search criteria for the `find` command. |==== | *Single Prefix Usage* | *Expected Result* | `find name/NAME` | Returns modules containing `NAME` in their names | `find code/CODE` |Returns modules containing `CODE` in their codes | `find credits/CREDITS` | Returns modules having `CREDITS` in their credits |==== If you need multiple prefixes, the following table shows some examples on how it can be done. + Note that you will need to separate multiple prefixes with an operator. [TIP] ==== You could choose which search criteria having a higher priority by specifying parenthesis ==== |==== | *Multiple Prefix Usage* | *Expected Result* | `find name/NAME1 && name/NAME2` | Returns modules containing both `NAME1` and `NAME2` in their names. | `find name/NAME1 \\|\\| name/NAME2` | Returns modules containing both `NAME1` or `NAME2` in their names. | `find name/NAME && code/CODE` | Returns modules containing `NAME` in their name and `CODE` in their codes. | `find code/CODE \\|\\| (name/NAME && code/CODE2)` | Returns modules containing either `CODE` in their codes or `NAME` in their names and `CODE2` in their codes. |==== **** * The search is case insensitive. e.g `security` will match `Security` * Only full words will be matched. e.g. `CS` will not match `CS1231` * The order of the prefixes does not matter. e.g. `find code/CODE || name/NAME` returns the same result as `find name/NAME || code/CODE` **** Examples: * `find name/computer` + Displays all modules with names containing the word `computer` (e.g. `computer` and `Computer Security`) in the module list. .Finding modules with name contains `computer` ifdef::env-github[] image::find1.png[width=800] endif::[] ifndef::env-github[] image::find1.png[width=970] endif::[] * `find name/computer && name/Security` Displays all modules with names containing the word `computer` and `security` in the module list. .Finding modules with name contains `computer` and `security`. ifdef::env-github[] image::find2.png[width=800] endif::[] ifndef::env-github[] image::find2.png[width=970] endif::[] * `find (sem/1 || sem/4) && name/Programming` + Displays all modules with names containing `programming` and is offered in either semester `1` or `4` in the module list. .Finding modules with names containing `programming` and is offered in either semester `1` or `4`. ifdef::env-github[] image::find3.png[width=800] endif::[] ifndef::env-github[] image::find3.png[width=970] endif::[] [TIP] ==== If you wish to search for module name with exact name `Information Security`, you could do so via the following command `find name/information security` Do note that if you prefer to search for module name containing both `Information` and `Security` but in any order, you can do the following command. `find name/Information && name/Security` + This command will return you modules with both name keywords. (e.g. `Security in Information Privacy`) ==== // end::find[] ==== Listing all modules : `list` image:https://img.shields.io/badge/module-list-blue.svg[] Shows a list of all modules in the *module list*. + *Command Format:* `list` [TIP] ==== This command is useful if you want to display all modules in the *module list* after doing a `find` command. ==== *Example:* Running the `list` command: .All modules are displayed in the *module list*. ifdef::env-github[] image::module_list.png[width=800] endif::[] ifndef::env-github[] image::module_list.png[width=970] endif::[] ==== Selecting modules : `select` image:https://img.shields.io/badge/module-select-blue.svg[] Selects the module identified by the index number used in the displayed module list. + *Command Format:* `select INDEX` **** * Selects the module at the specified `INDEX`. * The index refers to the index number shown in the displayed module list. * The index *must be a positive integer* `1, 2, 3, …` **** Examples: * `list` + `select 2` + Selects the 2nd module in the displayed module list. * `find Programming` + `select 1` + Selects the 1st module in the results of the `find` command. // tag::requirementtracker[] === Requirement Tracker The requirement tracker allows you to manage and and track your degree requirements so that you are always on-track for graduation! This section contains the various commands that you can use in this application to add, remove, move and list modules to and from the specified requirement categories in this application. The following table describes the parameters you may use for the commands in this section. [cols=""<20%,35%,35%""] |====== |*Parameter*| *Description* | *Acceptable Range of Values* | `NAME` | Indicates the name of degree requirement category (e.g. `IT Professionalism`). | `NAME` must be one of the following values: + 1. `Computing Foundation` + 2. `Information Security Requirements` + 3. `Information Security Electives` + 4. `Computing Breadth` + 5. `IT Professionalism` + 6. `Mathematics` + 7. `General Education` + 8. `Unrestricted Electives` | `CODE` | Indicates the module code (e.g. `CS2101`). | `CODE` must begin with two or three alphabets, followed by four digits, and may optionally end with an alphabet. |====== [WARNING] ==== `NAME` and `CODE` (where applicable) must not be empty or blank. ==== [NOTE] ==== * Both `NAME` and `CODE` parameters are case insensitive. (e.g. `computing foundation` will match `Computing Foundation`) * `CODE` is treated as uppercase (e.g. cs1010 is treated as CS1010), and should be unique. * Only full words will be matched. (e.g. `foundation` will not match `Computing Foundation`) ==== // end::requirementtracker[] // tag::requirementadd[] ==== Adding modules : `requirement_add` image:https://img.shields.io/badge/requirement-add-8AB702.svg[] Want to see if you have fulfilled a particular degree requirement category?​ Simply add the module code to a degree requirement category using the `requirement_add` command to find out. *Command Format:* `requirement_add name/NAME code/CODE [code/CODE]…` *Examples:* * `requirement_add name/IT Professionalism code/IS4231` + Adds the module code `IS4231` to the degree requirement category `IT Professionalism`. The two images below this command describes what you should see when you execute the above command image::RequirementAddCommand.png[] image::RequirementAddCommandAfter.png[] * `requirement_add name/Computing Foundation code/CS1231 code/CS2100` + Adds module codes `CS1231` and `CS2100` to the degree requirement category `Computing Foundation`. // end::requirementadd[] // tag::requirementremove[] ==== Removing modules : `requirement_remove` image:https://img.shields.io/badge/requirement-remove-8AB702.svg[] Want to remove a module code from the degree requirement category? `requirement_remove` will help you to remove the specified module code from the degree requirement category. *Command Format:* `requirement_remove code/CODE [code/CODE]…` [TIP] ==== If you want to delete the module entirely, simply use the `delete` command instead! The changes will be reflected in the degree requirement category as well. ==== *Examples:* * `requirement_remove code/IS4231` + Removes the module code `IS4231` from the degree requirement category. The two images below this command describes what you should see when you execute the above command image::RequirementRemoveCommand.png[] image::RequirementRemoveCommandAfter.png[] * `requirement_remove code/CS1231 code/CS2100` + Removes module codes `CS1231` and `CS2100` from the degree requirement category. // end::requirementremove[] // tag::requirementmove[] ==== Moving modules between requirement categories : `requirement_move` image:https://img.shields.io/badge/requirement-move-8AB702.svg[] Having seconds thoughts about which degree requirement category the module code should be classified under? Or simply added the module code to the wong degree requirement category? No worries, `requirement_move` will allow you to move the specified module to another degree requirement category. *Command Format:* `requirement_move name/NAME code/CODE [code/CODE]…` [WARNING] ==== The `CODE` specified must be already added to a degree requirement category! ==== [NOTE] ==== Unlike the `planner_move` command, modules that are co-requisites will not be moved together. ==== *Examples:* * `requirement_move name/Computing Breadth code/IS4231` + Moves the module code `IS4231` to the degree requirement category `Computing Breadth. The two images below this command describes what you should see when you execute the above command image::RequirementMoveCommand.png[] image::RequirementMoveCommandAfter.png[] * `requirement_move name/Computing Foundation code/CS1231 code/CS2100` + Moves module codes `CS1231` and `CS2100` to the degree requirement category `Computing Foundation`. // end::requirementmove[] // tag::requirementlist[] ==== Listing all requirement categories : `requirement_list` image:https://img.shields.io/badge/requirement-list-8AB702.svg[] Shows a list of all degree requirement categories in the application and the module codes added into each degree requirement category. *Command Format:* `requirement_list` *Examples:* * `requirement_list` The image below this command describes what you should see when you execute the above command image::RequirementListCommand.png[] // end::requirementlist[] //tag::degreeplanmanagement[] === Degree Plan Management The following table describes the parameters you may use for commands in this section. [cols=""<20%,35%,35%""] |====== |*Parameter*| *Description* | *Acceptable Range of Values* | `CODE` | Indicates the module code + (e.g. `CS2101`). | `CODE` should begin with two alphabets, followed by four digits, and may optionally end with an alphabet. | `YEAR` | Indicates the year of one of the semesters in the degree plan. + (e.g. `1`) | `YEAR` should only be either 1, 2, 3 or 4. + | `SEMESTER` | Indicates the semester of one of the semesters in the degree plan. + (e.g. `1`) | `SEMESTER` should only be either 1, 2, 3 or 4. + 3 and 4 indicates special term semesters 1 and 2 respectively. |====== [WARNING] ==== * `YEAR`, `SEMESTER` and `CODE` (if specified) must not be empty. + * `CODE` is case insensitive, and is treated as uppercase (e.g. `cs1010` is treated as `CS1010`), and should be unique. ==== //end::degreeplanmanagement[] //tag::planner-add-remove[] ==== Adding modules : `planner_add` image:https://img.shields.io/badge/planner-add-F17D3F.svg[] Want to add modules to the *degree plan*? + Make use of the `planner_add` command to add one or multiple modules to the *degree plan*. *Command Format:* `planner_add year/YEAR sem/SEMESTER code/CODE [code/CODE]…` [NOTE] ==== * 3 and 4 for `SEMESTER` indicates special term semesters 1 and 2 respectively. * All the module(s) to be added *must exist in the module list*. * All the module(s) to add *must not have duplicate(s)* in the *degree plan*. * For the following two points, `added to the valid semester` is defined as: The semesters in which module(s) are offered should contain the semester to which the module(s) are added. * The module(s) *must be added to the valid semester*. * The co-requisite(s) of the module(s) added *must be added to the valid semester*. * After adding, the updated *degree plan* will be displayed. ==== *Examples:* * `planner_add year/1 sem/3 code/CS1010` + Adds module `CS1010` to year 1 semester 3 (special term semester 1) of the *degree plan*. * `planner_add year/1 sem/4 code/CS1231 code/CS2040C` + Adds modules `CS1231` and `CS2040C` to year 1 semester 4 (special term semester 2) of the *degree plan*. * `planner_add year/1 sem/2 code/CS2113T code/CS2107` + Adds modules `CS2113T` and `CS2107` to year 1 semester 2 of the *degree plan*. ==== Removing modules : `planner_remove` image:https://img.shields.io/badge/planner-remove-F17D3F.svg[] Want to remove modules from the *degree plan*? + Make use of `planner_remove` command to remove one or multiple modules from the *degree plan*. + *Command Format:* `planner_remove code/CODE [code/CODE]…` [NOTE] ==== * All the module(s) to remove *must exist in the degree plan*. * After removing, the updated *degree plan* will be displayed. ==== *Examples:* * `planner_remove code/CS1231` + Removes module `CS1231` from the *degree plan*. * `planner_remove code/CS2100 code/CS2040C` + Removes modules `CS2100` and `CS2040C` from the *degree plan*. //end::planner-add-remove[] //tag::plannermove[] ==== Moving a module between semesters: `planner_move` image:https://img.shields.io/badge/planner-move-F17D3F.svg[] Any change in your decision? Want to take your module in other semester instead? + No worry! Simply use `planner_move` command to move your module in the degree plan along with its co-requisite(s) between the semesters by providing your module code and a semester you want to move your module to. + *Command Format:* `planner_move year/YEAR sem/SEMESTER code/CODE` [NOTE] ==== When moving a module with co-requisites, if the module is moved successfully, the co-requisite modules will be moved as well. ==== *Examples:* * `planner_move year/1 sem/2 code/CS1231` + Moves module CS1231 along with its co-requisite(s) to year 1 semester 2. * `planner_move year/2 sem/1 code/CS1231` + Moves module CS1231 along with its co-requisite(s) to year 2 semester 1. Before the `planner_move` command: [[beforePlannerMove]] .Before executing the `planner_move` command. ifdef::env-github[] image::plannermove1.png[width=800] endif::[] ifndef::env-github[] image::plannermove1.png[width=970] endif::[] After entering `planner_move` and pressing kbd:[Enter]: .After executing the `planner_move` command. ifdef::env-github[] image::plannermove2.png[width=800] endif::[] ifndef::env-github[] image::plannermove2.png[width=970] endif::[] Note that co-requste of the module is moved too: .After executing the `planner_move` command. ifdef::env-github[] image::plannermove3.png[width=800] endif::[] ifndef::env-github[] image::plannermove3.png[width=970] endif::[] //tag::plannershow[] ==== Showing semesters based on year/semester: `planner_show` image:https://img.shields.io/badge/planner-show-F17D3F.svg[] Having trouble locating semesters you want? + Simply use `planner_show` command. It will only show you the semesters you want to see. + *Command Format:* `planner_list [y/YEAR] OPERATOR [s/SEMESTER`] When this command is used, the application will display only those semesters which satisfy the search criteria. The following table describes the valid prefixes that you can use to supply to the search criteria. |==== | *Prefix* | *Description* | `year/YEAR` | Search for any semester `year` which matches `YEAR` | `sem/SEMESTER` | Search for any semester `sem` which matches `SEMESTER` |==== The following table describes the valid operators which you can to use supply to the search criteria. |==== | *Operator* | *Description* | *Precedence* | `&&` | Logical ""AND"" operation (both conditions A AND B must match) | Highest | `\\|\\|` | Logical ""OR"" operation (either conditions A OR B must match)| Lowest |==== The following examples describes how you could form a valid search criteria for the `planner_show` command. |==== | *Single Prefix Usage* | *Expected Result* | `planner_show year/YEAR` | Shows only semesters that are in year `YEAR` | `planner_show sem/SEMESTER` | Shows only semesters that are in semester `SEMESTER` |==== If you need multiple prefixes, the following table shows you how you could do it. + Note that you will need to separate multiple prefixes with an operator. [TIP] ==== You could choose which search criteria having a higher priority by specifying parenthesis ==== |==== | *Multiple Prefix Usage* | *Expected Result* | `planner_show year/YEAR1 \\|\\| year/YEAR2` | Shows only semesters that are in years `YEAR1` or `YEAR2`. | `planner_show sem/SEMESTER1 \\|\\| sem/SEMESTER2` | Shows only semesters that are in semester `SEMESTER1` or `SEMESTER`. | `planner_show sem/SEMESTER && (year/YEAR1 \\|\\| year/YEAR2)` | Shows only semesters that are in year `YEAR1` semester `SEMESTER` or `YEAR2` semester `SEMESTER`. |==== **** * The order of the prefixes does not matter. e.g. `planner_show sem/SEMESTER || year/YEAR` returns the same result as `planner_show year/YEAR || sem/SEMESTER` **** *Examples:* * `planner_show year/1` + Shows any semesters having the year `1` (e.g. `Year 1 Semester 1`, `Year 1 Semester 2` ...) in the degree plan. * `planner_show sem/1` + Shows any semesters having the year `1` (e.g. `Year 1 Semester 1`, `Year 2 Semester 1` ...) in the degree plan. * `planner_show year/1 || year/2` + Shows any semesters having the year `1` or year `2` in the degree plan. * `planner_show sem/1 || sem/2` + Shows any semesters having the semester `1` or semester `2` in the degree plan. * `planner_show year/1 && sem/1` + Shows a semester having the year `1` and semester `1` (e.g. `Year 1 Semester 1`)in the degree plan. * `planner_show sem/1 && (year/1 || year/2)` + Shows a semester having the year `1` semester `1` and year `2` semester `1` (e.g. `Year 1 Semester 1` and `Year 2 Semester 2`) in the degree plan. Before the `planner_show` command: [[beforePlannerShow]] .Before executing the `planner_show` command. ifdef::env-github[] image::plannershow1.png[width=800] endif::[] ifndef::env-github[] image::plannershow1.png[width=970] endif::[] After entering `planner_show` and pressing kbd:[Enter]: .After executing the `planner_show` command. ifdef::env-github[] image::plannershow2.png[width=800] endif::[] ifndef::env-github[] image::plannershow2.png[width=970] endif::[] //end::plannershow[] //tag::plannerlist[] ==== Listing all semesters: `planner_list` image:https://img.shields.io/badge/planner-list-F17D3F.svg[] Maybe you need to list all your semesters back after using `planner_show`? + Simply enter `planner_list` into the application! + It wil show you a list of all semesters in degree plan. *Command Format:* `planner_list` //end::plannerlist[] //tag::planner-suggest[] ==== Using degree plan to suggest modules : `planner_suggest` image:https://img.shields.io/badge/planner-suggest-F17D3F.svg[] Having trouble identifying modules to add to the *degree plan*? + Make use of `planner_suggest` command to find out recommended modules to add to the *degree plan*. + *Command Format:* `planner_suggest credits/CREDITS [tag/TAG]…` When this command is successfully executed, the *result box* will display modules recommended. [NOTE] ==== * *Maximum 10* modules are recommended in the recommendation list. * In addition to the recommendation list, supplementary information on the specific modules with matching tags and credits is given as two additional lists. The modules in the two additional lists are all from the recommendation list. * Modules recommended in all 3 aforementioned lists are sorted according to the following criteria: ** For modules with different number of tags that match the desirable tags (matching tags), modules with more matching tags will be sorted to the front of the list. ** If modules have the same number of matching tags but different credits, modules with the credits closer to the desirable credits will be sorted to the front of the list. ** If modules have the same number of matching tags and credits, they will be sorted according to alphabetical order. ** If `tag/TAG` is not supplied as a parameter in the command, modules will be sorted according to credits and alphabetical order only. * All modules in the recommendation list and the two additional lists are modules not found in the degree plan. ==== *Examples:* * `planner_suggest credits/4` + Suggests maximum 10 modules not found in the degree plan, prioritizing modules with credits closer to 4. If tie, prioritizes according to alphabetical order. * `planner_suggest credits/2 tag/algorithms` + Suggests maximum 10 modules not found in the degree plan, prioritizing modules with tag `algorithms`. If tie, prioritizes according to credits closer to 2. If tie again, prioritizes according to alphabetical order. //end::planner-suggest[] == Future Enhancements `[coming in v2.0]` These are features that will come in future releases of *PlanWithEase* === Module Prerequisites `prereq/` We aim to provide the support of `prerequisites` for our *Module Management*. + This changes will allow our users to indicate a module prerequisites and we can handle its dependency for the users before they add the module into the *Degree Plan*. === Auto-create Degree Plan `autoplan` We plan to implement this feature to allow an automated planning, we can make use of users feedback and current treads based on module popularity then create the degree plan for the users. == FAQ *Q*: How do I save my data in the application? + *A*: You do need to save the data manually. Whenever you run any commands that makes changes, *PlanWithEase*'s data are saved automatically in the `data` directory. == Command Summary This section provides a quick references for all commands available in *PlanWithEase*. === General Commands The table below shows a list of general commands. |==== | *Task* | *Purpose* | *Command* | *Example* | *Clear* | Clear the modules data | `clear` | `clear` |*Help* | Displays the User Guide | `help` | `help` | *History* | Get a list of command entered | `history` | `history` | *Undo* | Undo your previously action| `undo` | `undo` | *Redo* | Redo your previous action | `redo` | `redo` |==== === Degree Plan Commands The table below shows a list of commands which helps you to manage the degree plan. |==== | *Task* | *Purpose* |*Command* | *Example* |*Add module(s) to degree plan* | Add module(s) to degree plan based on module code and academic year a| `planner_add year/YEAR sem/SEMESTER code/CODE [code/CODE]…` a| `planner_add year/1 sem/2 code/CS1010 code/CS2113T` |*Remove module(s) from degree plan*| Remove module(s) from degree plan based on the module code a| `planner_remove code/CODE [code/CODE]…` a| `planner_remove code/CS1231 code/CS1010` | *Move module between semesters in the degree plan* | Move module between the semesters based on year and semester. a| `planner_move year/YEAR sem/SEMESTER code/CODE` a| `planner_move year/1 sem/2 code/CS1231` |*List all semesters in the degree plan* | List all semesters in the degree plan a| `planner_list` a| `planner_list` |*List specific semesters in the degree plan* | List specific semesters in the degree plan based on your search term. a| `planner_show [year/YEAR] OPERATOR [sem/SEMESTER]` a| `planner_show sem/2 && ( year/1 \\|\\|year/2 )` | *Suggest available modules* | Suggest available modules from the module lists based on input argument. a| `planner_suggest credits/CREDITS [tag/TAG]…` a| `planner_suggest credits/4 tag/maths` |==== === Requirement Tracker Commands The table below shows a list of command which helps you to manage and track your degree requirements. |==== |*Task* | *Purpose* |*Command* | *Example* | *Add module(s) to a requirement category* | Add module(s) to the specified requirement category based on the module code provided. a| `requirement_add name/NAME code/CODE [code/CODE]…` a| `requirement_add name/IT Professionalism code/IS4231` | *Remove module(s) from the requirement category* | Remove module(s) from the requirement category based on the module code provided. a| `requirement_remove code/CODE [code/CODE]…` a| `requirement_remove code/IS4231` | *Move module(s) between requirement categories* | Move module(s) between the requirement categories from any requirement categories to a specified requirement categories. a| `requirement_move name/NAME code/CODE [code/CODE]…` a| `requirement_move name/IT Professionalism code/IS4231` | *List all requirement categories in the application* | List all requirement categories in the application and the module(s) added to each requirement categories a| `requirement_list` a| `requirement_list` |==== ",12050,False,2316.302355358174,median "/*============================================================================ MetaIO Copyright 2000-2010 Insight Software Consortium Distributed under the OSI-approved BSD License (the ""License""); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #ifdef _MSC_VER # pragma warning(disable : 4702) #endif #include ""metaUtils.h"" #include ""metaCommand.h"" #include #include #if (METAIO_USE_NAMESPACE) namespace METAIO_NAMESPACE { #endif #ifdef METAIO_USE_LIBXML2 # include # include # include # include # include # include #endif MetaCommand::MetaCommand() { m_HelpCallBack = nullptr; m_OptionVector.clear(); m_Version = ""Not defined""; m_Date = ""Not defined""; m_Name = """"; m_Author = ""Not defined""; m_Description = """"; m_Acknowledgments = """"; m_Category = """"; m_ParsedOptionVector.clear(); m_Verbose = true; m_FailOnUnrecognizedOption = false; m_GotXMLFlag = false; m_DisableDeprecatedWarnings = false; } /** Extract the date from a CVS Date keyword/value pair. */ std::string MetaCommand::ExtractDateFromCVS(std::string date) { std::string newdate; for (int i = 7; i < static_cast(date.size()) - 1; i++) { newdate += date[i]; } return newdate; } void MetaCommand::DisableDeprecatedWarnings() { m_DisableDeprecatedWarnings = true; } void MetaCommand::SetDateFromCVS(std::string cvsDate) { this->SetDate(this->ExtractDateFromCVS(std::move(cvsDate)).c_str()); } /** Extract the version from a CVS Revision keyword/value pair. */ std::string MetaCommand::ExtractVersionFromCVS(std::string version) { std::string newversion; for (int i = 11; i < static_cast(version.size()) - 1; i++) { newversion += version[i]; } return newversion; } void MetaCommand::SetVersionFromCVS(std::string cvsVersion) { this->SetVersion(this->ExtractVersionFromCVS(std::move(cvsVersion)).c_str()); } /** */ bool MetaCommand::SetOption(const Option& option) { // need to add some tests here to check if the option is not defined yet m_OptionVector.push_back(option); return true; } bool MetaCommand::SetOption(std::string name, const std::string& shortTag, bool required, std::string description, std::vector fields) { // need to add some tests here to check if the option is not defined yet // Short tag can be empty as long as the long tag is defined. // This is checked in the Parse() command /*if(tag == """") { std::cout << ""Tag cannot be empty : use AddField() instead."" << std::endl; return false; }*/ if (!m_DisableDeprecatedWarnings && shortTag.size() > 1) { std::cout << ""Warning: as of August 23, 2007 MetaCommand::SetOption()"" << "" is expecting a shortTag of exactly one character."" << "" You should use the SetOptionLongTag(optionName,longTagName)"" << "" if you want to use a longer tag. The longtag will be"" << "" referred to as --LongTag and the short tag as -ShortTag."" << "" Replace -"" << shortTag.c_str() << "" by --"" << shortTag.c_str() << std::endl; } Option option; option.name = std::move(name); option.tag = shortTag; option.longtag = """"; option.fields = std::move(fields); option.required = required; option.description = std::move(description); option.userDefined = false; option.complete = false; m_OptionVector.push_back(option); return true; } bool MetaCommand::SetOption(const std::string& name, const std::string& shortTag, bool required, std::string description, TypeEnumType type, std::string defVal, DataEnumType externalData) { // need to add some tests here to check if the option is not defined yet // Short tag can be empty as long as the long tag is defined. // This is checked in the Parse() command /* if(tag == """") { std::cout << ""Tag cannot be empty : use AddField() instead."" << std::endl; return false; }*/ if (!m_DisableDeprecatedWarnings && shortTag.size() > 1) { std::cout << ""Warning: as of August 23, 2007 MetaCommand::SetOption() "" << "" is expecting a shortTag of exactly one character."" << "" You should use the SetOptionLongTag(optionName,longTagName)"" << "" if you want to use a longer tag. The longtag will be "" << "" referred to as --LongTag and the short tag as -ShortTag "" << "" Replace -"" << shortTag.c_str() << "" by --"" << shortTag.c_str() << std::endl; } Option option; option.tag = shortTag; option.longtag = """"; option.name = name; option.required = required; option.description = std::move(description); option.userDefined = false; option.complete = false; // Create a field without description as a flag Field field; if (type == LIST) { field.name = ""NumberOfValues""; } else { field.name = name; } field.externaldata = externalData; field.type = type; field.value = std::move(defVal); field.userDefined = false; field.required = true; field.rangeMin = """"; field.rangeMax = """"; option.fields.push_back(field); m_OptionVector.push_back(option); return true; } /** Add a field */ bool MetaCommand::AddField(const std::string& name, std::string description, TypeEnumType type, DataEnumType externalData, std::string rangeMin, std::string rangeMax) { // need to add some tests here to check if the option is not defined yet Option option; option.tag = """"; option.longtag = """"; // Create a field without description with the specified type Field field; field.name = name; field.type = type; field.required = true; field.userDefined = false; field.externaldata = externalData; field.rangeMin = std::move(rangeMin); field.rangeMax = std::move(rangeMax); option.fields.push_back(field); option.required = true; option.name = name; option.description = std::move(description); option.userDefined = false; option.complete = false; m_OptionVector.push_back(option); return true; } /** For backward compatibility */ bool MetaCommand::AddField(const std::string& name, const std::string& description, TypeEnumType type, bool externalData) { if (externalData) { return this->AddField(name, description, type, DATA_IN); } else { return this->AddField(name, description, type, DATA_NONE); } } /** Collect all the information until the next tag * \\warning this function works only if the field is of type String */ void MetaCommand::SetOptionComplete(const std::string& optionName, bool complete) { auto it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { (*it).complete = complete; return; } ++it; } } /** Add a field to a given an option */ bool MetaCommand::AddOptionField(const std::string& optionName, const std::string& name, TypeEnumType type, bool required, const std::string& defVal, const std::string& description, DataEnumType externalData) { auto it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { // Create a field without description with the specified type Field field; field.name = name; field.type = type; field.required = required; field.value = defVal; field.description = description; field.userDefined = false; field.externaldata = externalData; field.rangeMin = """"; field.rangeMax = """"; // If this is the first field in the list we replace the current field if ((*it).fields[0].type == FLAG) { (*it).fields[0] = field; } else { (*it).fields.push_back(field); } return true; } ++it; } return false; } /** Set the range of an option */ bool MetaCommand::SetOptionRange(const std::string& optionName, const std::string& name, const std::string& rangeMin, const std::string& rangeMax) { auto it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { std::vector & fields = (*it).fields; auto itField = fields.begin(); while (itField != fields.end()) { if ((*itField).name == name) { (*itField).rangeMin = rangeMin; (*itField).rangeMax = rangeMax; return true; } ++itField; } } ++it; } return false; } /** Set the range of an option */ bool MetaCommand::SetOptionEnumerations(const std::string& optionName, const std::string& name, const std::string& optionEnums) { auto it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { std::vector & fields = (*it).fields; auto itField = fields.begin(); while (itField != fields.end()) { if ((*itField).name == name) { (*itField).rangeMin = optionEnums; return true; } ++itField; } } ++it; } return false; } /** Return the value of the option as a boolean */ bool MetaCommand::GetValueAsBool(const std::string& optionName, const std::string& fieldName) { std::string fieldname = fieldName; if (fieldName.empty()) { fieldname = optionName; } OptionVector::const_iterator it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { auto itField = (*it).fields.begin(); while (itField != (*it).fields.end()) { if ((*itField).name == fieldname) { if ((*itField).value == ""true"" || (*itField).value == ""1"" || (*itField).value == ""True"" || (*itField).value == ""TRUE"") { return true; } return false; } ++itField; } } ++it; } return false; } /** Return the value of the option as a bool */ bool MetaCommand::GetValueAsBool(Option option, const std::string& fieldName) { std::string fieldname = fieldName; if (fieldName.empty()) { fieldname = option.name; } std::vector::const_iterator itField = option.fields.begin(); while (itField != option.fields.end()) { if ((*itField).name == fieldname) { if ((*itField).value == ""true"" || (*itField).value == ""1"" || (*itField).value == ""True"" || (*itField).value == ""TRUE"") { return true; } return false; } ++itField; } return false; } /** Return the value of the option as a float */ float MetaCommand::GetValueAsFloat(const std::string& optionName, const std::string& fieldName) { std::string fieldname = fieldName; if (fieldName.empty()) { fieldname = optionName; } OptionVector::const_iterator it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { auto itField = (*it).fields.begin(); while (itField != (*it).fields.end()) { if ((*itField).name == fieldname) { return static_cast(atof((*itField).value.c_str())); } ++itField; } } ++it; } return 0; } /** Return the value of the option as a float */ float MetaCommand::GetValueAsFloat(Option option, const std::string& fieldName) { std::string fieldname = fieldName; if (fieldName.empty()) { fieldname = option.name; } std::vector::const_iterator itField = option.fields.begin(); while (itField != option.fields.end()) { if ((*itField).name == fieldname) { return static_cast(atof((*itField).value.c_str())); } ++itField; } return 0; } /** Return the value of the option as a int */ int MetaCommand::GetValueAsInt(const std::string& optionName, const std::string& fieldName) { std::string fieldname = fieldName; if (fieldName.empty()) { fieldname = optionName; } OptionVector::const_iterator it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { auto itField = (*it).fields.begin(); while (itField != (*it).fields.end()) { if ((*itField).name == fieldname) { return atoi((*itField).value.c_str()); } ++itField; } } ++it; } return 0; } /** Return the value of the option as a int */ int MetaCommand::GetValueAsInt(Option option, const std::string& fieldName) { std::string fieldname = fieldName; if (fieldName.empty()) { fieldname = option.name; } std::vector::const_iterator itField = option.fields.begin(); while (itField != option.fields.end()) { if ((*itField).name == fieldname) { return atoi((*itField).value.c_str()); } ++itField; } return 0; } /** Return the value of the option as a string */ std::string MetaCommand::GetValueAsString(const std::string& optionName, const std::string& fieldName) { std::string fieldname = fieldName; if (fieldName.empty()) { fieldname = optionName; } OptionVector::const_iterator it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { auto itField = (*it).fields.begin(); while (itField != (*it).fields.end()) { if ((*itField).name == fieldname) { return (*itField).value; } ++itField; } } ++it; } return """"; } /** Return the value of the option as a string */ std::string MetaCommand::GetValueAsString(Option option, const std::string& fieldName) { std::string fieldname = fieldName; if (fieldName.empty()) { fieldname = option.name; } std::vector::const_iterator itField = option.fields.begin(); while (itField != option.fields.end()) { if ((*itField).name == fieldname) { return (*itField).value; } ++itField; } return """"; } /** Return the value of the option as a list of strings */ std::list MetaCommand::GetValueAsList(Option option) { std::list results; results.clear(); std::vector::const_iterator itField = option.fields.begin(); ++itField; while (itField != option.fields.end()) { results.push_back((*itField).value); ++itField; } return results; } std::list MetaCommand::GetValueAsList(const std::string& optionName) { OptionVector::const_iterator it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { return this->GetValueAsList(*it); } ++it; } std::list empty; empty.clear(); return empty; } bool MetaCommand::GetOptionWasSet(const Option& option) { if (option.userDefined) { return true; } return false; } bool MetaCommand::GetOptionWasSet(const std::string& optionName) { OptionVector::const_iterator it = m_ParsedOptionVector.begin(); while (it != m_ParsedOptionVector.end()) { if ((*it).name == optionName) { return true; } ++it; } return false; } /** List the current options */ void MetaCommand::ListOptions() { OptionVector::const_iterator it = m_OptionVector.begin(); int i = 0; while (it != m_OptionVector.end()) { std::cout << ""Option #"" << i << std::endl; std::cout << "" Name: "" << (*it).name.c_str() << std::endl; if (!(*it).tag.empty()) { std::cout << "" Tag: "" << (*it).tag.c_str() << std::endl; } if (!(*it).longtag.empty()) { std::cout << "" LongTag: "" << (*it).longtag.c_str() << std::endl; } std::cout << "" Description: "" << (*it).description.c_str() << std::endl; if ((*it).required) { std::cout << "" Required: true"" << std::endl; } else { std::cout << "" Required: false"" << std::endl; } std::cout << "" Number of expected values: "" << (*it).fields.size() << std::endl; auto itField = (*it).fields.begin(); while (itField != (*it).fields.end()) { std::cout << "" Field Name: "" << (*itField).name.c_str() << std::endl; std::cout << "" Description: "" << (*itField).description.c_str() << std::endl; std::cout << "" Type: "" << MetaCommand::TypeToString((*itField).type).c_str() << std::endl; std::cout << "" Value: "" << (*itField).value.c_str() << std::endl; if ((*itField).type == ENUM) { std::cout << "" Enum list: "" << (*itField).rangeMin.c_str() << std::endl; } else { std::cout << "" RangeMin: "" << (*itField).rangeMin.c_str() << std::endl; std::cout << "" RangeMax: "" << (*itField).rangeMax.c_str() << std::endl; } if ((*itField).externaldata) { std::cout << "" External Data: true"" << std::endl; } else { std::cout << "" External Data: false"" << std::endl; } if ((*itField).required) { std::cout << "" Required: true"" << std::endl; } else { std::cout << "" Required: false"" << std::endl; } if ((*itField).userDefined) { std::cout << "" User Defined: true"" << std::endl; } else { std::cout << "" User Defined: false"" << std::endl; } ++itField; } std::cout << std::endl; i++; ++it; } if (m_HelpCallBack != nullptr) { m_HelpCallBack(); } } /** List the current options in xml format */ void MetaCommand::ListOptionsXML() { OptionVector::const_iterator it = m_OptionVector.begin(); int i = 0; while (it != m_OptionVector.end()) { std::cout << """" << std::endl; i++; ++it; } } /** Used by ListOptionsSlicerXML */ void MetaCommand::WriteXMLOptionToCout(const std::string& optionName, unsigned int & index) { OptionVector::const_iterator it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if (!strcmp((*it).name.c_str(), optionName.c_str())) { break; } ++it; } auto itField = (*it).fields.begin(); std::string optionType; if ((*itField).type == MetaCommand::STRING && ((*itField).externaldata == MetaCommand::DATA_IN || (*itField).externaldata == MetaCommand::DATA_OUT)) { optionType = ""image""; } else if ((*itField).type == MetaCommand::FLAG) { optionType = ""boolean""; } else if ((*itField).type == MetaCommand::INT) { optionType = ""integer""; } else if ((*itField).type == MetaCommand::ENUM) { optionType = ""string-enumeration""; } else { optionType = MetaCommand::TypeToString((*itField).type); } std::cout << ""<"" << optionType.c_str() << "">"" << std::endl; std::cout << """" << (*it).name.c_str() << """" << std::endl; // Label is the description for now std::string label = (*it).label; if (label.empty()) { label = (*it).name; } std::cout << """" << std::endl; std::cout << """" << (*it).description.c_str() << """" << std::endl; if (!(*it).tag.empty()) // use the single by default flag if any { std::cout << """" << (*it).tag.c_str() << """" << std::endl; } else if (!(*it).longtag.empty()) { std::cout << """" << (*it).longtag.c_str() << """" << std::endl; } else { std::cout << """" << index << """" << std::endl; index++; } if (!(*itField).value.empty()) { std::cout << """" << (*itField).value.c_str() << """" << std::endl; } if ((*itField).externaldata == MetaCommand::DATA_IN) { std::cout << ""input"" << std::endl; } else if ((*itField).externaldata == MetaCommand::DATA_OUT) { std::cout << ""output"" << std::endl; } if ((*itField).type == MetaCommand::ENUM) { std::vector enumVector; MET_StringToVector((*itField).rangeMin, enumVector); std::vector::iterator itenum; itenum = enumVector.begin(); while (itenum != enumVector.end()) { std::cout << """" << (*itenum).c_str() << """" << std::endl; ++itenum; } } // Write out the closing tag std::cout << """" << std::endl; } /** List the current options in Slicer's xml format (www.slicer.org) */ void MetaCommand::ListOptionsSlicerXML() { std::cout << R""()"" << std::endl; std::cout << """" << std::endl; std::cout << "" "" << m_Category.c_str() << """" << std::endl; std::cout << "" "" << m_Name.c_str() << """" << std::endl; std::cout << "" "" << std::endl; std::cout << "" "" << m_Description.c_str() << std::endl; std::cout << "" "" << std::endl; std::cout << "" "" << m_Version.c_str() << """" << std::endl; std::cout << "" "" << m_Author.c_str() << """" << std::endl; std::cout << "" "" << std::endl; std::cout << "" "" << std::endl; std::cout << "" "" << std::endl; std::cout << "" "" << m_Acknowledgments.c_str() << std::endl; std::cout << "" "" << std::endl; // Organize by group first // Keep a list of options unsigned int index = 0; std::vector GroupedOptionVector; ParameterGroupVector::const_iterator itGroup = m_ParameterGroup.begin(); while (itGroup != m_ParameterGroup.end()) { if ((*itGroup).advanced == true) { std::cout << "" "" << std::endl; } else { std::cout << "" "" << std::endl; } std::cout << "" "" << std::endl; if ((*itGroup).description.empty()) { std::cout << "" "" << (*itGroup).name.c_str() << """" << std::endl; } else { std::cout << "" "" << (*itGroup).description.c_str() << """" << std::endl; } auto itOption = (*itGroup).options.begin(); while (itOption != (*itGroup).options.end()) { this->WriteXMLOptionToCout(*itOption, index); GroupedOptionVector.push_back(*itOption); ++itOption; } std::cout << "" "" << std::endl; ++itGroup; } // Then take the remaining options if (m_OptionVector.size() > GroupedOptionVector.size()) { std::cout << "" "" << std::endl; std::cout << "" "" << std::endl; std::cout << "" Input/output parameters"" << std::endl; OptionVector::const_iterator it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { bool optionIsGrouped = false; std::vector::const_iterator itGroupedOption = GroupedOptionVector.begin(); while (itGroupedOption != GroupedOptionVector.end()) { if (!strcmp((*itGroupedOption).c_str(), (*it).name.c_str())) { optionIsGrouped = true; break; } ++itGroupedOption; } if (!optionIsGrouped) { this->WriteXMLOptionToCout((*it).name, index); } ++it; } // end loop option std::cout << "" "" << std::endl; } // end m_OptionVector.size()>GroupedOptionVector.size() std::cout << """" << std::endl; } /** Internal small XML parser */ std::string MetaCommand::GetXML(const char * buffer, const char * desc, unsigned long pos) { std::string begin = ""<""; begin += desc; begin += "">""; std::string end = """"; std::string buf = buffer; auto posb = static_cast(buf.find(begin, pos)); if (posb == -1) { return """"; } auto pose = static_cast(buf.find(end, static_cast(posb))); if (pose == -1) { return """"; } return buf.substr(posb + begin.size(), pose - posb - begin.size()); } /** Given an XML buffer fill in the command line arguments */ bool MetaCommand::ParseXML(const char * buffer) { m_OptionVector.clear(); std::string buf = this->GetXML(buffer, ""option"", 0); long pos = 0; while (!buf.empty()) { Option option; option.userDefined = false; option.complete = false; option.name = this->GetXML(buf.c_str(), ""name"", 0); option.tag = this->GetXML(buf.c_str(), ""tag"", 0); option.longtag = this->GetXML(buf.c_str(), ""longtag"", 0); option.description = this->GetXML(buf.c_str(), ""description"", 0); if (atoi(this->GetXML(buf.c_str(), ""required"", 0).c_str()) == 0) { option.required = false; } else { option.required = true; } unsigned int n = static_cast(atoi(this->GetXML(buf.c_str(), ""nvalues"", 0).c_str())); // Now check the fields long posF = static_cast(buf.find("""")); for (unsigned int i = 0; i < n; i++) { std::string f = this->GetXML(buf.c_str(), ""field"", static_cast(posF)); Field field; field.userDefined = false; field.name = this->GetXML(f.c_str(), ""name"", 0); field.description = this->GetXML(f.c_str(), ""description"", 0); field.value = this->GetXML(f.c_str(), ""value"", 0); field.type = MetaCommand::StringToType(this->GetXML(f.c_str(), ""type"", 0).c_str()); if (atoi(this->GetXML(f.c_str(), ""external"", 0).c_str()) == 0) { field.externaldata = DATA_NONE; } else { if (atoi(this->GetXML(f.c_str(), ""external"", 0).c_str()) == 1) { field.externaldata = DATA_IN; } else { field.externaldata = DATA_OUT; } } if (atoi(this->GetXML(f.c_str(), ""required"", 0).c_str()) == 0) { field.required = false; } else { field.required = true; } option.fields.push_back(field); posF += static_cast(f.size() + 8); } m_OptionVector.push_back(option); pos += static_cast(buf.size() + 17); buf = this->GetXML(buffer, ""option"", static_cast(pos)); } return true; } /** List the current options */ void MetaCommand::ListOptionsSimplified(bool extended) { if (extended) { std::cout << "" System tags: "" << std::endl << "" [ -v ] or [ -h ]"" << std::endl << "" = List options in short format"" << std::endl << "" [ -V ] or [ -H ]"" << std::endl << "" = List options in long format"" << std::endl << "" [ -vxml ] or [ -hxml ] or [ -exportXML ]"" << std::endl << "" = List options in xml format for BatchMake"" << std::endl << "" [ --xml ]"" << std::endl << "" = List options in xml format for Slicer"" << std::endl << "" [ -vgad ] or [ -hgad ] or [ -exportGAD ]"" << std::endl << "" = List options in Grid Application Description format"" << std::endl << "" [ -version ]"" << std::endl << "" = return the version number"" << std::endl << "" [ -date ]"" << std::endl << "" = return the cvs checkout date"" #ifdef METAIO_USE_LIBXML2 << std::endl << "" [ --loadArguments filename ]"" << "" = load the arguments from an XML file"" #endif << std::endl; } int count = 0; int ntags = 0; int nfields = 0; OptionVector::const_iterator it; it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if (!(*it).tag.empty() || !(*it).longtag.empty()) { ntags++; } else { nfields++; } ++it; } while (count < 2) { if (count == 0) { if (ntags > 0) { std::cout << "" Command tags: "" << std::endl; } else { count++; } } if (count == 1) { if (nfields > 0) { std::cout << "" Command fields: "" << std::endl; } else { count++; } } count++; it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((count == 1 && (!(*it).tag.empty() || !(*it).longtag.empty())) || (count == 2 && ((*it).tag.empty() && (*it).longtag.empty()))) { if (!(*it).required) { std::cout << "" [ ""; } else { std::cout << "" ""; } if (!(*it).tag.empty()) { std::cout << ""-"" << (*it).tag.c_str() << "" ""; } if (!(*it).longtag.empty()) { std::cout << ""--"" << (*it).longtag.c_str() << "" ""; } auto itField = (*it).fields.begin(); while (itField != (*it).fields.end()) { // only display the type if it's not a FLAG if ((*itField).type != FLAG) { if ((*itField).required) { std::cout << ""< ""; } else { std::cout << ""[ ""; } std::cout << (*itField).name.c_str(); if ((*itField).required) { std::cout << "" > ""; } else { std::cout << "" ] ""; } } ++itField; } if (!(*it).required) { std::cout << ""]""; } std::cout << std::endl; if (!(*it).description.empty()) { std::cout << "" = "" << (*it).description.c_str(); std::cout << std::endl; itField = (*it).fields.begin(); while (itField != (*it).fields.end()) { if (!(*itField).description.empty() || !(*itField).value.empty()) { std::cout << "" With: "" << (*itField).name.c_str(); if (!(*itField).description.empty()) { std::cout << "" = "" << (*itField).description.c_str(); } if (!(*itField).value.empty()) { std::cout << "" (Default = "" << (*itField).value.c_str() << "")""; } std::cout << std::endl; } ++itField; } } } ++it; } } if (m_HelpCallBack != nullptr) { m_HelpCallBack(); } } /** Get the option by ""-""+tag * or by ""--""+longtag */ bool MetaCommand::OptionExistsByMinusTag(const std::string& minusTag) { OptionVector::const_iterator it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { std::string tagToSearch = ""-""; tagToSearch += (*it).tag; std::string longtagToSearch = ""--""; longtagToSearch += (*it).longtag; std::string longtagToSearchBackwardCompatible = ""-""; longtagToSearchBackwardCompatible += (*it).longtag; // WARNING: This is for backward compatibility but a warning // is going to be thrown if used so that people can adjust if (tagToSearch == minusTag || longtagToSearch == minusTag || longtagToSearchBackwardCompatible == minusTag) { return true; } ++it; } return false; } /** Get the option by ""-""+tag * or by ""--""+longtag */ MetaCommand::Option * MetaCommand::GetOptionByMinusTag(const std::string& minusTag) { auto it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { std::string tagToSearch = ""-""; tagToSearch += (*it).tag; std::string longtagToSearch = ""--""; longtagToSearch += (*it).longtag; std::string longtagToSearchBackwardCompatible = ""-""; longtagToSearchBackwardCompatible += (*it).longtag; // WARNING: This is for backward compatibility but a warning // is going to be thrown if used so that people can adjust if (tagToSearch == minusTag || longtagToSearch == minusTag || longtagToSearchBackwardCompatible == minusTag) { return &(*it); } ++it; } return nullptr; } /** Get the option by tag */ MetaCommand::Option * MetaCommand::GetOptionByTag(const std::string& tag) { auto it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).tag == tag || (*it).longtag == tag) { return &(*it); } ++it; } return nullptr; } /** Return the option id. i.e the position in the vector */ long MetaCommand::GetOptionId(Option * option) { auto it = m_OptionVector.begin(); unsigned long i = 0; while (it != m_OptionVector.end()) { if (&(*it) == option) { return i; } i++; ++it; } return -1; } /** Export the current command line arguments to a Grid Application * Description file */ bool MetaCommand::ExportGAD(bool dynamic) { std::cout << ""Exporting GAD file...""; OptionVector options = m_OptionVector; if (dynamic) { options = m_ParsedOptionVector; } if (m_Name.empty()) { std::cout << ""Set the name of the application using SetName()"" << std::endl; return false; } std::string filename = m_Name; filename += "".gad.xml""; std::ofstream file; #ifdef __sgi file.open(filename.c_str(), std::ios::out); #else file.open(filename.c_str(), std::ios::binary | std::ios::out); #endif if (!file.rdbuf()->is_open()) { std::cout << ""Cannot open file for writing: "" << filename.c_str() << std::endl; return false; } file << R""()"" << std::endl; file << """" << std::endl; file << R""()"" << std::endl; file << """" << std::endl; file << std::endl; unsigned int order = 1; // Write out the input data to be transferred OptionVector::const_iterator it = options.begin(); while (it != options.end()) { auto itFields = (*it).fields.begin(); while (itFields != (*it).fields.end()) { if ((*itFields).externaldata == DATA_IN) { file << R""( "" << std::endl; file << R""( "" << std::endl; file << R""( )"" << std::endl; file << R""( "" << std::endl; file << R""( )"" << std::endl; file << R""( )"" << std::endl; file << R""( "" << std::endl; std::string datapath = (*itFields).value; auto slash = static_cast(datapath.find_last_of('/')); if (slash > 0) { datapath = datapath.substr(static_cast(slash + 1), datapath.size() - slash - 1); } slash = static_cast(datapath.find_last_of('\\\\')); if (slash > 0) { datapath = datapath.substr(static_cast(slash + 1), datapath.size() - slash - 1); } file << R""( "" << std::endl; file << "" "" << std::endl; file << std::endl; order++; } ++itFields; } ++it; } file << R""( "" << std::endl; file << R""( "" << std::endl; file << R""( "" << std::endl; // Write out the arguments that are not data it = options.begin(); while (it != options.end()) { // Find if this is a non data field bool isData = false; auto itFields = (*it).fields.begin(); while (itFields != (*it).fields.end()) { if ((*itFields).externaldata != DATA_NONE) { isData = true; break; } ++itFields; } if (isData) { ++it; continue; } file << "" "" << std::endl; // Now writes the value of the arguments itFields = (*it).fields.begin(); while (itFields != (*it).fields.end()) { file << "" "" << std::endl; ++itFields; } file << "" "" << std::endl; ++it; } file << "" "" << std::endl; order++; file << std::endl; // Write out the input data to be transferred it = options.begin(); while (it != options.end()) { auto itFields = (*it).fields.begin(); while (itFields != (*it).fields.end()) { if ((*itFields).externaldata == DATA_OUT) { file << R""( "" << std::endl; file << R""( "" << std::endl; file << R""( )"" << std::endl; file << R""( "" << std::endl; file << R""( )"" << std::endl; file << R""( )"" << std::endl; std::string datapath = (*itFields).value; auto slash = static_cast(datapath.find_last_of('/')); if (slash > 0) { datapath = datapath.substr(static_cast(slash + 1), datapath.size() - slash - 1); } slash = static_cast(datapath.find_last_of('\\\\')); if (slash > 0) { datapath = datapath.substr(static_cast(slash + 1), datapath.size() - slash - 1); } file << R""( "" << std::endl; file << R""( "" << std::endl; file << "" "" << std::endl; file << std::endl; order++; } ++itFields; } ++it; } file << "" "" << std::endl; file << "" "" << std::endl; file << """" << std::endl; file.close(); std::cout << ""done"" << std::endl; return true; } /** Parse the command line */ bool MetaCommand::Parse(int argc, char ** const argv) { m_GotXMLFlag = false; m_ExecutableName = argv[0]; auto slash = static_cast(m_ExecutableName.find_last_of('/')); if (slash > 0) { m_ExecutableName = m_ExecutableName.substr(static_cast(slash + 1), m_ExecutableName.size() - slash - 1); } slash = static_cast(m_ExecutableName.find_last_of('\\\\')); if (slash > 0) { m_ExecutableName = m_ExecutableName.substr(static_cast(slash + 1), m_ExecutableName.size() - slash - 1); } // Fill in the results m_ParsedOptionVector.clear(); bool inArgument = false; std::string tag; unsigned long currentField = 0; // current field position long currentOption = 0; // id of the option to fill unsigned int valuesRemaining = 0; unsigned int optionalValuesRemaining = 0; bool isComplete = false; // check if the option should be parse until // the next tag is found std::string completeString; bool exportGAD = false; for (unsigned int i = 1; i < static_cast(argc); i++) { if (!strcmp(argv[i], ""-V"") || !strcmp(argv[i], ""-H"")) { std::cout << ""Usage : "" << argv[0] << std::endl; this->ListOptions(); return true; } // List the options if using -v if (!strcmp(argv[i], ""-v"") || !strcmp(argv[i], ""-h"")) { std::cout << ""Usage : "" << argv[0] << std::endl; this->ListOptionsSimplified(); return true; } // List the options if using -v if (!strcmp(argv[i], ""--loadArguments"")) { if ((i + 1) >= static_cast(argc)) { std::cout << ""--loadArguments expected a filename as argument"" << std::endl; return false; } MetaCommand::LoadArgumentsFromXML(argv[i + 1]); i++; continue; } if (!strcmp(argv[i], ""-vxml"") || !strcmp(argv[i], ""-hxml"") || !strcmp(argv[i], ""-exportXML"") || !strcmp(argv[i], ""--vxml"") || !strcmp(argv[i], ""--hxml"") || !strcmp(argv[i], ""--exportXML"")) { this->ListOptionsXML(); continue; } if (!strcmp(argv[i], ""--xml"")) { this->ListOptionsSlicerXML(); m_GotXMLFlag = true; return false; } if (!strcmp(argv[i], ""-version"")) { std::cout << ""Version: "" << m_Version.c_str() << std::endl; continue; } if (!strcmp(argv[i], ""-date"")) { std::cout << ""Date: "" << m_Date.c_str() << std::endl; continue; } if (!strcmp(argv[i], ""-exportGAD"") || !strcmp(argv[i], ""-vgad"") || !strcmp(argv[i], ""-hgad"")) { this->ExportGAD(); exportGAD = true; continue; } // If this is a tag if (argv[i][0] == '-' && (atof(argv[i]) == 0) && (strlen(argv[i]) > 1)) { // if we have a tag before the expected values we throw an exception if (valuesRemaining != 0) { if (!isComplete) { if (optionalValuesRemaining > 0) { valuesRemaining = 0; m_OptionVector[currentOption].userDefined = true; m_ParsedOptionVector.push_back(m_OptionVector[currentOption]); } else { std::cout << ""Found tag "" << argv[i] << "" before end of value list!"" << std::endl; return false; } } else { m_OptionVector[currentOption].fields[0].value = completeString; m_OptionVector[currentOption].fields[0].userDefined = true; m_OptionVector[currentOption].userDefined = true; m_ParsedOptionVector.push_back(m_OptionVector[currentOption]); valuesRemaining = 0; } } inArgument = false; // New tag so we add the previous values to the tag tag = argv[i]; // Check if the tag is in the list if (this->OptionExistsByMinusTag(tag)) { inArgument = true; // We check the number of mandatory and optional values for // this tag std::vector::const_iterator fIt = this->GetOptionByMinusTag(tag)->fields.begin(); while (fIt != this->GetOptionByMinusTag(tag)->fields.end()) { if (!(*fIt).required) { optionalValuesRemaining++; } valuesRemaining++; ++fIt; } currentOption = this->GetOptionId(this->GetOptionByMinusTag(tag)); if (currentOption < 0) { std::cout << ""Error processing tag "" << tag.c_str() << "". Tag exists but cannot find its Id."" << std::endl; } else { isComplete = m_OptionVector[currentOption].complete; if (m_OptionVector[currentOption].fields[0].type == FLAG) { // the tag exists by default m_OptionVector[currentOption].fields[0].value = ""true""; valuesRemaining = 0; optionalValuesRemaining = 0; inArgument = false; } else if (m_OptionVector[currentOption].fields[0].type == LIST) { inArgument = true; auto valuesInList = static_cast(atoi(argv[++i])); m_OptionVector[currentOption].fields[0].value = argv[i]; valuesRemaining += valuesInList - 1; char optName[255]; for (unsigned int j = 0; j < valuesInList; j++) { snprintf(optName, sizeof(optName), ""%03u"", j); this->AddOptionField(m_OptionVector[currentOption].name, optName, STRING); } } } } else { if (m_Verbose) { std::cout << ""The tag "" << tag.c_str() << "" is not a valid argument : skipping this tag"" << std::endl; } if (m_FailOnUnrecognizedOption) { return false; } } if (inArgument) { i++; } } else if (!inArgument) // If this is a field { // Look for the field to add auto it = m_OptionVector.begin(); unsigned long pos = 0; bool found = false; while (it != m_OptionVector.end()) { if ((pos >= currentField) && ((*it).tag.empty() && (*it).longtag.empty())) { currentOption = pos; valuesRemaining = static_cast((*it).fields.size()); found = true; break; } pos++; ++it; } if (!found && m_Verbose) { std::cout << ""Too many arguments specified in your command line! "" << ""Skipping extra argument: "" << argv[i] << std::endl; } inArgument = true; currentField = static_cast(currentOption + 1); } // We collect the values if (isComplete && static_cast(i) < argc) { if (completeString.empty()) { completeString = argv[i]; } else { completeString += "" ""; completeString += argv[i]; } } else if (inArgument && i < static_cast(argc) && (valuesRemaining > 0)) { // We check that the current value is not a tag. // This might be the case when we have optional fields if (this->OptionExistsByMinusTag(argv[i]) && optionalValuesRemaining > 0) { valuesRemaining = 0; optionalValuesRemaining = 0; i--; // the outter loop will take care of incrementing it. } else if (currentOption >= 0 && currentOption < static_cast(m_OptionVector.size())) { auto s = m_OptionVector[currentOption].fields.size(); // We change the value only if this is not a tag if (this->OptionExistsByMinusTag(argv[i])) { std::cout << ""Option "" << m_OptionVector[currentOption].name.c_str() << "" expect a value and got tag: "" << argv[i] << std::endl; this->ListOptionsSimplified(false); return false; } m_OptionVector[currentOption].fields[s - (valuesRemaining)].value = argv[i]; m_OptionVector[currentOption].fields[s - (valuesRemaining)].userDefined = true; if (!m_OptionVector[currentOption].fields[s - (valuesRemaining)].required) { optionalValuesRemaining--; } valuesRemaining--; } else if (valuesRemaining > 0) { valuesRemaining--; } } else if (valuesRemaining == optionalValuesRemaining && i == static_cast(argc) && (optionalValuesRemaining > 0)) // if this is the last argument and all the remaining values are optionals { if (this->OptionExistsByMinusTag(argv[i - 1])) { valuesRemaining = 0; optionalValuesRemaining = 0; } } if (valuesRemaining == 0) { inArgument = false; m_OptionVector[currentOption].userDefined = true; m_ParsedOptionVector.push_back(m_OptionVector[currentOption]); } } // end loop command line arguments if (isComplete) // If we are still in the isComplete mode we add the option { m_OptionVector[currentOption].fields[0].value = completeString; m_OptionVector[currentOption].fields[0].userDefined = true; m_OptionVector[currentOption].userDefined = true; m_ParsedOptionVector.push_back(m_OptionVector[currentOption]); valuesRemaining = 0; } if (optionalValuesRemaining > 0 && optionalValuesRemaining == valuesRemaining) { valuesRemaining = 0; m_OptionVector[currentOption].userDefined = true; m_ParsedOptionVector.push_back(m_OptionVector[currentOption]); } if (valuesRemaining > 0) { std::cout << ""Not enough parameters for "" << m_OptionVector[currentOption].name.c_str() << std::endl; std::cout << ""Usage: "" << argv[0] << std::endl; this->ListOptionsSimplified(false); return false; } // Check if the options with required arguments are defined auto it = m_OptionVector.begin(); bool requiredAndNotDefined = false; while (it != m_OptionVector.end()) { if ((*it).required) { // First check if the option is actually defined if (!(*it).userDefined) { std::cout << ""Option "" << (*it).name.c_str() << "" is required but not defined"" << std::endl; requiredAndNotDefined = true; ++it; continue; } // Check if the values are defined std::vector::const_iterator itFields = (*it).fields.begin(); bool defined = true; while (itFields != (*it).fields.end()) { if ((*itFields).value.empty()) { defined = false; } ++itFields; } if (!defined) { if (!(*it).tag.empty() || !(*it).longtag.empty()) { std::cout << ""Field "" << (*it).tag.c_str() << "" is required but not defined"" << std::endl; } else { std::cout << ""Field "" << (*it).name.c_str() << "" is required but not defined"" << std::endl; } requiredAndNotDefined = true; } } ++it; } if (requiredAndNotDefined) { // std::cout << ""Command: "" << argv[0] << std::endl; this->ListOptionsSimplified(false); return false; } // Check if the values are in range (if the range is defined) auto itParsed = m_ParsedOptionVector.begin(); bool valueInRange = true; while (itParsed != m_ParsedOptionVector.end()) { std::vector::const_iterator itFields = (*itParsed).fields.begin(); while (itFields != (*itParsed).fields.end()) { // Check only if this is a number if (((*itFields).type == INT || (*itFields).type == FLOAT || (*itFields).type == CHAR) && (!(*itFields).value.empty())) { // Check the range min if (((!(*itFields).rangeMin.empty()) && (atof((*itFields).rangeMin.c_str()) > atof((*itFields).value.c_str()))) || ((!(*itFields).rangeMax.empty()) && (atof((*itFields).rangeMax.c_str()) < atof((*itFields).value.c_str())))) { std::cout << (*itParsed).name.c_str() << ""."" << (*itFields).name.c_str() << "" : Value ("" << (*itFields).value.c_str() << "") "" << ""is not in the range ["" << (*itFields).rangeMin.c_str() << "","" << (*itFields).rangeMax.c_str() << ""]"" << std::endl; valueInRange = false; } } ++itFields; } ++itParsed; } if (!valueInRange) { return false; } // If everything is ok if (exportGAD) { this->ExportGAD(true); return false; // prevent from running the application } return true; } /** Return the string representation of a type */ std::string MetaCommand::TypeToString(TypeEnumType type) { switch (type) { case INT: return ""int""; case FLOAT: return ""float""; case STRING: return ""string""; case LIST: return ""list""; case FLAG: return ""flag""; case BOOL: return ""boolean""; case IMAGE: return ""image""; case FILE: return ""file""; case ENUM: return ""enum""; case CHAR: default: return ""not defined""; } } /** Return a type given a string */ MetaCommand::TypeEnumType MetaCommand::StringToType(const char * type) { if (!strcmp(type, ""int"")) { return INT; } else if (!strcmp(type, ""float"")) { return FLOAT; } else if (!strcmp(type, ""string"")) { return STRING; } else if (!strcmp(type, ""list"")) { return LIST; } else if (!strcmp(type, ""flag"")) { return FLAG; } else if (!strcmp(type, ""bool"")) { return BOOL; } else if (!strcmp(type, ""image"")) { return IMAGE; } else if (!strcmp(type, ""enum"")) { return ENUM; } else if (!strcmp(type, ""file"")) { return FILE; } return INT; // by default } /** Set the long flag for the option */ bool MetaCommand::SetOptionLongTag(const std::string& optionName, const std::string& longTag) { auto itOption = m_OptionVector.begin(); while (itOption != m_OptionVector.end()) { if (!strcmp((*itOption).name.c_str(), optionName.c_str())) { (*itOption).longtag = longTag; return true; } ++itOption; } return false; } /** Set the label for the option */ bool MetaCommand::SetOptionLabel(const std::string& optionName, const std::string& label) { auto itOption = m_OptionVector.begin(); while (itOption != m_OptionVector.end()) { if (!strcmp((*itOption).name.c_str(), optionName.c_str())) { (*itOption).label = label; return true; } ++itOption; } return false; } /** Set the group for a field or an option * If the group doesn't exist it is automatically created. */ bool MetaCommand::SetParameterGroup(const std::string& optionName, const std::string& groupName, std::string groupDescription, bool advanced) { // Check if the group exists ParameterGroup * group = nullptr; auto it = m_ParameterGroup.begin(); while (it != m_ParameterGroup.end()) { if (!strcmp((*it).name.c_str(), groupName.c_str())) { group = &(*it); } ++it; } bool optionExists = false; unsigned int index = 0; OptionVector::const_iterator itOption = m_OptionVector.begin(); while (itOption != m_OptionVector.end()) { if (!strcmp((*itOption).name.c_str(), optionName.c_str())) { optionExists = true; break; } index++; ++itOption; } if (!optionExists) { std::cout << ""The option "" << optionName.c_str() << "" doesn't exist"" << std::endl; return false; } if (!group) { ParameterGroup pgroup; pgroup.name = groupName; pgroup.description = std::move(groupDescription); pgroup.advanced = advanced; pgroup.options.push_back(optionName); m_ParameterGroup.push_back(pgroup); } else { group->options.push_back(optionName); } return true; } /** Load arguments from XML file */ bool MetaCommand::LoadArgumentsFromXML(const char * filename, bool createMissingArguments) { #ifdef METAIO_USE_LIBXML2 xmlDocPtr doc; xmlNodePtr cur; doc = xmlParseFile(filename); if (doc == nullptr) { std::cerr << ""Cannot parse XML file"" << std::endl; return false; } cur = xmlDocGetRootElement(doc); if (cur == nullptr) { std::cerr << ""XML document is empty"" << std::endl; xmlFreeDoc(doc); return false; } if (xmlStrcmp(cur->name, (const xmlChar *)""MetaCommand"")) { std::cerr << ""document of the wrong type. Root node should be MetaCommand"" << std::endl; xmlFreeDoc(doc); return false; } xmlCleanupParser(); // Simple parsing (two levels hierarchy) cur = cur->children; while (cur) { xmlNodePtr child = cur->children; if (child) { xmlNodePtr subargument = child->next; while (subargument) { xmlNodePtr subargumentChild = subargument->children; if (subargumentChild && subargumentChild->content) { this->SetOptionValue((const char *)cur->name, (const char *)subargument->name, (const char *)subargumentChild->content, createMissingArguments); } subargument = subargument->next; } if (child->content) { this->SetOptionValue( (const char *)cur->name, (const char *)cur->name, (const char *)child->content, createMissingArguments); } } cur = cur->next; } xmlFreeDoc(doc); #else std::cout << ""LoadArguments("" << filename << "") requires libxml2"" << std::endl; if (createMissingArguments) { } #endif return true; } /** Set the value of an option or a field * This is used when importing command line arguments * from XML */ bool MetaCommand::SetOptionValue(const char * optionName, const char * name, const char * value, bool createMissingArgument) { auto it = m_OptionVector.begin(); while (it != m_OptionVector.end()) { if ((*it).name == optionName) { (*it).userDefined = true; std::vector & fields = (*it).fields; auto itField = fields.begin(); while (itField != fields.end()) { if ((*itField).name == name) { (*itField).userDefined = true; (*itField).value = value; return true; } ++itField; } } ++it; } if (createMissingArgument) { Option option; option.tag = """"; option.longtag = optionName; option.name = optionName; option.required = false; option.description = """"; option.userDefined = true; option.complete = false; Field field; field.name = name; field.externaldata = DATA_NONE; field.type = STRING; field.value = value; field.userDefined = true; field.required = false; field.rangeMin = """"; field.rangeMax = """"; option.fields.push_back(field); m_OptionVector.push_back(option); } return false; } #if (METAIO_USE_NAMESPACE) }; #endif ",16352,True,2996.860544174557,median "== CMMN 1.1 === What is CMMN? The Case Management Model and Notation (CMMN) is a standard notation and formal specification by the link:$$http://www.omg.org/spec/CMMN/$$[Object Management Group] for representing case models. Flowable contains: * A CMMN 1.1 modeler to create CMMN 1.1 case models * A Java engine that can import and execute CMMN 1.1 case models * A demonstration UI that executes the case models, allowing users to see and complete human tasks (and their forms) === Basic concepts and terminology The following figure shows a simple CMMN 1.1 diagram: image::images/cmmn-basic-concepts.png[align=""center""] A *case model* is always visualized as some sort of _folder_ that contains all the case elements. Every case model contains a *plan model* onto which items will be _planned_. The elements of a plan model are called *plan items*. Each _plan item_ has a *plan item definition* that gives its type and possible configuration options at runtime. For example, in the figure above, there are three *human task* plan items and one *milestone*. Other examples of plan items are _process tasks, case tasks and stages_. After having deployed a case model to the Flowable CMMN engine, it's possible to start *case instances* based on this case model. The plan items defined in the case model similarly have *plan item instance* runtime representations that are exposed by, and can be queried using, the Flowable API. Plan item instances have a state lifecycle that is defined in the CMMN 1.1 specification and is core to how the engine works. Please check out section 8.4.2 of the CMMN 1.1 specification for all the details. Plan items can have _sentries_: a plan item is said to have _entry criteria_ when a sentry ""guards"" its activation. These criteria specify conditions that must be satisfied to _trigger the sentry_. For example, in the figure above, the ""Milestone One"" plan item is _available_ after a case instance is started, but it is _activated_ (in CMMN 1.1 specification terminology: it moves from the _available_ state to the _active_ state) when both human task A and B are completed. Note that sentries can have complex expression in their _if part_, which are not visualized, allowing for much more complex functionality. Also note that there can be multiple sentries, although only one needs to be satisfied to trigger a state transition. Plan items and the plan model can also have sentries with _exit criteria_, which specify conditions that trigger an _exit_ from that particular plan item. In the figure above, the whole plan model is exited (as are all the child elements that are active at that moment), when human task C completes. CMMN 1.1 defines a standard XML format in an XSD that is part of the specification. For information, the example in the figure above is represented in XML as shown below. Some observations: * The four plan items above are in the XML and they reference their definition with a _definitionRef_. The actual definitions are at the bottom of the _casePlanModel_ element * The plan items have criteria (entry or exit) that reference a _sentry_ (not the other way around) * The XML also contains information on how the diagram is visualized (x and y coordinates, widths and heights, and so on), which are omitted below. These elements are important when exchanging case models with other CMMN 1.1 modeling tools to preserve the correct visual representation [source,xml,linenums] ---- complete complete complete ... ---- === Programmatic example In this section we're going to build a simple case model and execute it programmatically through the Java API's of the Flowable CMMN engine in a simple command line example. The case model we'll build is a (simplified) _employee onboarding_ case with two stages: a phase before and phase after the potential employee has started. In the first stage, someone from the HR department will complete the tasks, while in the second stage it is the employee completing them. Also, at any point in time, the potential employee can reject the job and stop the whole case instance. Note that only stages and human tasks are used. In a real case model, there will most likely other plan item types too, like milestones, nested stages, automated tasks, etc. image::images/cmmn.programmatic.example.png[align=""center""] The XML for this case models is the following: [source,xml,linenums] ---- complete complete complete complete complete ---- First of all, create a new project and add the _flowable-cmmn-engine_ dependency (here shown for Maven). The H2 dependency is also added, as H2 will be used as embedded database later on. [source,xml,linenums] ---- org.flowable flowable-cmmn-engine ${flowable.version} com.h2database h2 ${h2.version} ---- The Flowable CMMN API is designed to be consistent with the other Flowable API's and concepts. As such, people that know the BPMN or DMN API's will have no problem finding their way around. As with the other engines, the first line of code is creating a CmmnEngine. Here, the default in-memory configuration is used, which uses H2 as database: [source,java,linenums] ---- public class Main { public static void main(String[] args) { CmmnEngine cmmnEngine = new StandaloneInMemCmmnEngineConfiguration().buildCmmnEngine(); } } ---- Note that the _CmmnEngineConfiguration_ exposes many configuration options for tweaking various settings of the CMMN engine. Put the XML from above in a file, for example _my-case.cmmn_ (or .cmmn.xml). For Maven, it should be placed in the _src/main/resources_ folder. To make the engine aware of the case model, it needs to be _deployed_ first. This is done through the _CmmnRepositoryService_: [source,java,linenums] ---- CmmnRepositoryService cmmnRepositoryService = cmmnEngine.getCmmnRepositoryService(); CmmnDeployment cmmnDeployment = cmmnRepositoryService.createDeployment() .addClasspathResource(""my-case.cmmn"") .deploy(); ---- Deploying the XML will return a *CmmnDeployment*. A deployment can contain many case models and artifacts. The specific case model definition of above is stored as a *CaseDefinition*. This can be verified by doing a _CaseDefinitionQuery_: [source,java,linenums] ---- List caseDefinitions = cmmnRepositoryService.createCaseDefinitionQuery().list(); System.out.println(""Found "" + caseDefinitions.size() + "" case definitions""); ---- Having a *CaseDefinition* in the engine, it's now possible to start a *CaseInstance* for this case model definition. Either the result from the query is used and passed into the following snippet of code, or the _key_ of the case definition is used directly (as done below). Note that we're also passing data, an identifier to the _potentialEmployee_ as a variable when starting the *CaseInstance*. This variable will later be used in the human tasks to assign the task to the correct person (see the _assignee=""${potentialEmployee}""_ attribute on _human tasks_). [source,java,linenums] ---- CmmnRuntimeService cmmnRuntimeService = cmmnEngine.getCmmnRuntimeService(); CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder() .caseDefinitionKey(""employeeOnboarding"") .variable(""potentialEmployee"", ""johnDoe"") .start(); ---- After the *CaseInstance* is started, the engine will determine which of the plan items of the model should be activated: * The first stage has no entry criteria, so it's activated * The child human tasks of the first stage have no entry criteria, so three of them are expected to be active The plan items are represented at runtime by *PlanItemInstances* and can be queried through the _CmmnRuntimeService_: [source,java,linenums] ---- List planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery() .caseInstanceId(caseInstance.getId()) .orderByName().asc() .list(); for (PlanItemInstance planItemInstance : planItemInstances) { System.out.println(planItemInstance.getName()); } ---- which prints out ---- After starting Agree start date Allocate office Create email address Prior to starting Reject job Send joining letter to candidate ---- Some things might be unexpected here: * The stages are _also_ plan items and thus have a representation as *PlanItemInstance*. Note that that child plan item instances will have the stage as parent when calling _.getStageInstanceId()_. * The _Send joining letter to candidate_ is returned in the result. The reason for that is that, in accordance with the CMMN 1.1 specification, this plan item instance is in the _available_ state, but not yet in the _active_ state. Indeed, when the code above is changed to [source,java,linenums] ---- for (PlanItemInstance planItemInstance : planItemInstances) { System.out.println(planItemInstance.getName() + "", state="" + planItemInstance.getState() + "", parent stage="" + planItemInstance.getStageInstanceId()); } ---- The output now becomes: ---- After starting, state=available, parent stage=null Agree start date, state=active, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 Allocate office, state=active, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 Create email address, state=active, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 Prior to starting, state=active, parent stage=null Reject job, state=active, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 Send joining letter to candidate, state=available, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 ---- To only show the active plan item instances, the query can be adapted by adding _planItemInstanceStateActive()_: [source,java,linenums] ---- List planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery() .caseInstanceId(caseInstance.getId()) .planItemInstanceStateActive() .orderByName().asc() .list(); ---- The output is now ---- Agree start date Allocate office Create email address Prior to starting Reject job ---- Of course, the *PlanItemInstance* is the low level representation, but each plan item also has a _plan item definition_ that defines what type it is. In this case, we only have _human tasks_. It is possible to interact with the _CaseInstance_ via its _plan item instances_, for example by triggering them programmatically (e.g. _CmmnRuntimeService.triggerPlanItemInstance(String planItemInstanceId)_). However, most likely the interaction will happen through the results of the actual plan item definition, here the human tasks. Querying for tasks is done in the exact same way as for the BPMN engine (in fact, the task service is a shared component and tasks created in BPMN or CMMN can be queried through both engines): [source,java,linenums] ---- CmmnTaskService cmmnTaskService = cmmnEngine.getCmmnTaskService(); List hrTasks = cmmnTaskService.createTaskQuery() .taskCandidateGroup(""hr"") .caseInstanceId(caseInstance.getId()) .orderByTaskName().asc() .list(); for (Task task : hrTasks) { System.out.println(""Task for HR : "" + task.getName()); } List employeeTasks = cmmnTaskService.createTaskQuery() .taskAssignee(""johndoe"") .orderByTaskName().asc() .list(); for (Task task : employeeTasks) { System.out.println(""Task for employee: "" + task); } ---- Which outputs: ---- Task for HR : Agree start date Task for HR : Allocate office Task for HR : Create email address Task for employee: Reject job ---- When the three tasks of HR are completed, the 'Send joining letter to candidate' task should be available: [source,java,linenums] ---- for (Task task : hrTasks) { cmmnTaskService.complete(task.getId()); } hrTasks = cmmnTaskService.createTaskQuery() .taskCandidateGroup(""hr"") .caseInstanceId(caseInstance.getId()) .orderByTaskName().asc() .list(); for (Task task : hrTasks) { System.out.println(""Task for HR : "" + task.getName()); } ---- And indeed, the expected task is now created: ---- Task for HR : Send joining letter to candidate ---- Completing this task will now move the case instance into the second stage, as the sentry for the first stage is satisfied. The 'Reject job' tasks is automatically completed by the system and the two tasks for the employee are now created: [source,java,linenums] ---- Task for employee: Fill in paperwork Task for employee: New starter training Task for employee: Reject job ---- Completing all the tasks will now end the case instance: ---- List tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).listPage(0, 1); while (!tasks.isEmpty()) { cmmnTaskService.complete(tasks.get(0).getId()); tasks = cmmnTaskService.createTaskQuery() .caseInstanceId(caseInstance.getId()) .listPage(0, 1); } ---- While executing case instances, the engine also stores historic information, that can be queried via a query API: [source,java,linenums] ---- CmmnHistoryService cmmnHistoryService = cmmnEngine.getCmmnHistoryService(); HistoricCaseInstance historicCaseInstance = cmmnHistoryService.createHistoricCaseInstanceQuery() .caseInstanceId(caseInstance.getId()) .singleResult(); System.out.println(""Case instance execution took "" + (historicCaseInstance.getEndTime().getTime() - historicCaseInstance.getStartTime().getTime()) + "" ms""); List historicTaskInstances = cmmnHistoryService.createHistoricTaskInstanceQuery() .caseInstanceId(caseInstance.getId()) .orderByTaskCreateTime().asc() .list(); for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) { System.out.println(""Task completed: "" + historicTaskInstance.getName()); } ---- Which outputs: ---- Case instance execution took 149 ms Task completed: Reject job Task completed: Agree start date Task completed: Allocate office Task completed: Create email address Task completed: Send joining letter to candidate Task completed: New starter training Task completed: Fill in paperwork ---- Of course, this is but a small part of the available API's and constructs available in the Flowable CMMN Engine. Please check the other sections for more detailed information === CMMN 1.1 Constructs This chapter covers the CMMN 1.1 constructs supported by Flowable, as well as extensions to the CMMN 1.1 standard. ==== Stage A stage is used to group plan items together. It is typically used to define ""phases"" in a case instance. A stage is a plan item itself, and thus can have entry and exit criteria. Plan items contained within a stage are only available when the parent stage moves to the _active_ state. Stages can be nested in other stages. A stage is visualized as a rectangle with angled corners: image::images/cmmn.stage.png[align=""center""] ==== Task A ""manual"" task, meaning the task will happen external to the engine. Properties: * *name*: expression that will be resolved at runtime as the name of the human task * *blocking*: a boolean value determining whether the task blocks * *blockingExpression*: an expression that evaluates to a boolean indicating whether the tasks blocks If a task is non-blocking, the engine will simply complete it automatically when executing it. If a task is blocking, a _PlanItemInstance_ for this task will remain in the _active_ state until it is programmatically triggered by the _CmmnRuntimeService.triggerPlanItemInstance(String planItemInstanceId)_ method. A task is visualized as a rounded rectangle: image::images/cmmn.task.png[align=""center""] ==== Human task A human task is used to model work that needs to be done by a human, typically through a form. When the engine arrives at such a human task, a new entry is created in the task list of any users or groups assigned to that task. A human task is a plan item, which means that beyond a human task entry also a _PlanItemInstance_ is created and it can be queried via the _PlanItemInstanceQuery_. Human tasks can be queried through the _org.flowable.task.api.TaskQuery_ API. Historic task data can be queried through the _org.flowable.task.api.history.HistoricTaskInstanceQuery_. Properties: * *name*: expression that will be resolved at runtime as the name of the human task. * *blocking*: a boolean value determining whether the task blocks. * *blockingExpression*: an expression that evaluates to a boolean indicating whether the tasks blocks. * *assignee* : an expression (can be a static text value) that is used to determine to who the human task is assigned. * *owner* : an expression (can be a static text value) that is used to determine who is the owner of the human task. * *candidateUsers* : an expression (can be a static text value) that resolves to a comma-separated list of Strings that is used to determine which users are candidate for this human task. * *candidateGroups* : an expression (can be a static text value) that resolves to a comma-separated list of Strings that is used to determine to which groups the task is assigned. * *form key*: an expression that determines a key when using forms. Can be retrieved via the API afterwards. * *Due date* an expression that resolves to java.util.Date or a ISO-8601 date string. * *Priority*: an expression that resolves to an integer. Can be used in the TaskQuery API to filter tasks. A human task is visualized as a rounded rectangle with a user icon in the top left corner: image::images/cmmn.humantask.png[align=""center""] ==== Java Service task A service task is used to execute custom logic. Custom logic is placed in a class that implements the _org.flowable.cmmn.api.delegate.PlanItemJavaDelegate_ interface. [source,java,linenums] ---- public class MyJavaDelegate implements PlanItemJavaDelegate { public void execute(DelegatePlanItemInstance planItemInstance) { String value = (String) planItemInstance.getVariable(""someVariable""); ... } } ---- For lower-level implementations that cannot be covered by using the _PlanItemJavaDelegate_ approach, the _CmmnActivityBehavior_ can be used (similar to _JavaDelegate_ vs _ActivityBehavior_ in the BPMN engine). Properties: * *name*: name of the service task. * *class*: the Java class implementing the custom logic. * *class fields*: allows to add parameters when calling the custom logic. * *Delegate expression*: an expression that resolves to a class implementing the _PlanItemJavaDelegate_ interface. A service task is visualized as a rounded rectangle with a cog icon in the top left corner: image::images/cmmn.servicetask.png[align=""center""] ==== Decision task A _Decision task_ allows to call out to a DMN decision table and store the resulting variable in the case instance. Properties: * *Decision table reference*: the referenced DMN decision table that needs to be invoked. It is also possible to throw an error when no rule is hit during the evaluation of the DMN decision table, by setting the '_Throw error if no rules were hit_' property. A decision task is visualized as a _task_ with a table icon in the top left corner: image::images/cmmn.decisiontask.png[align=""center""] ==== Http Task The Http task is an out-of-the-box implementation of a _service task_. It is used when a REST service needs to be called over HTTP. The Http task has various options to customize the request and response. See the BPMN http task documentation for details on all the configuration options. A http task is visualized as a _task_ with a rocket icon in the top left corner: image::images/cmmn.httptask.png[align=""center""] ==== Script Task A task of type ""script"", similar to its homologue in BPMN, the Script Task executes a script when the plan item instance become active. Properties: * *name*: task attribute to indicate the name of the task. * *type*: task attribute whose value must be ""script"" to indicate the type of task. * *scriptFormat*: extended attribute that indicate the language of the script (i.e. javascript, groovy). * *script*: the script to execute, defined as a string in a extension field element named ""script"". * *autoStoreVariables*: optional task attribute flag (default: false) tha indicates whether or not variables defined in the script will be stored in the Plan Item Instance context (see note below). * *resultVariableName*: optional task attribute that when present will store a variable with the specified name in the Plan Item instance context with the script evaluation result (see note below). A script task is visualized as a _task_ with a script icon in the top left corner: image::images/cmmn.scripttask.png[align=""center""] [source,xml,linenums] ---- Optional documentation sum = 0; for ( i in inputArray ) { sum += i; } ---- *Note*: The value of the *scriptFormat* attribute must be a name that is compatible with the link:$$http://jcp.org/en/jsr/detail?id=223$$[JSR-223] (scripting for the Java platform). By default, JavaScript is included in every JDK and as such doesn't need any additional JAR files. If you want to use another (JSR-223 compatible) scripting engine, it is sufficient to add the corresponding JAR to the classpath and use the appropriate name. For example, the Flowable unit tests often use Groovy because the syntax is similar to that of Java. Do note that the Groovy scripting engine is bundled with the groovy-all jar. Before Groovy version 2.0, the scripting engine was part of the regular Groovy JAR. As such, one must now add following dependency: [source,xml,linenums] ---- org.codehaus.groovy groovy-all 2.x.x ---- All case variables that are accessible through the PlanItem instance that arrives in the script task can be used within the script. In the example, the script variable _'inputArray'_ is in fact a case variable (an array of integers). [source,xml,linenums] ---- sum = 0 for ( i in inputArray ) { sum += i } ---- *Note*: It's also possible to set process variables in a script, simply by calling _planItemInstance.setVariable(""variableName"", variableValue)_. By default, no variables are stored automatically. It's possible to automatically store any variable defined in the script (for example, __sum__ in the example above) by setting the property ++autoStoreVariables++ on the ++scriptTask++ to ++true++. However, *the best practice is not to do this and use an explicit execution.setVariable() call*, as with some recent versions of the JDK, auto storing of variables does not work for some scripting languages. See link:$$http://www.jorambarrez.be/blog/2013/03/25/bug-on-jdk-1-7-0_17-when-using-scripttask-in-activiti/$$[this link] for more details. [source,xml,linenums] ---- ---- The default for this parameter is +false+, meaning that if the parameter is omitted from the script task definition, all the declared variables will only exist during the duration of the script. Here's an example of how to set a variable in a script: [source,xml,linenums] ---- def scriptVar = ""test123"" planItemInstance.setVariable(""myVar"", scriptVar) ---- The following names are reserved and *cannot be used* as variable names: *out, out:print, lang:import, context, elcontext*. *Note* The return value of a script task can be assigned to an already existing, or to a new process variable, by specifying the process variable name as a literal value for the _'flowable:resultVariable'_ attribute of a script task definition. Any existing value for a specific process variable will be overwritten by the result value of the script execution. When a result variable name is not specified, the script result value gets ignored. [source,xml,linenums] ---- #{echo} ---- In the above example, the result of the script execution (the value of the resolved expression __'#{echo}'__) is set to the process variable named __'myVar'__ after the script completes. ==== Milestone A milestone is used to mark arriving at a certain point in the case instance. At runtime, they are represented as *MilestoneInstances* and they can be queried through the *MilestoneInstanceQuery* via the _CmmnRuntimeService_. There is also a historical counterpart via the _CmmnHistoryService_. A milestone is a plan item, which means that beyond a milestone entry aso a _PlanItemInstance_ is created and it can be queried via the _PlanItemInstanceQuery_. Properties: * *name*: an expression or static text that determines the name of the mile stone. A milestone is visualized as a rounded rectangle with, slightly more rounded than a task: image::images/cmmn.milestone.png[align=""center""] ==== Case task A case task is used to start a child case within the context of another case. The _CaseInstanceQuery_ has _parent_ options to find these cases. When the case task is blocking, the _PlanItemInstance_ will be _active_ until the child case has completely finished. If the case task is non-blocking, the child case is started and the plan item instance automatically completes. When the child case instance is ended, there is no impact on the parent case. Properties: * *name*: an expression or static text that determines the name * *blocking*: a boolean value determining whether the task blocks * *blockingExpression*: an expression that evaluates to a boolean indicating whether the tasks blocks * *Case reference*: the key of the case definition that is used to start the child case instance. Can be an expression. A case task is visualized as a rounded rectangle with a case icon in the top left corner: image::images/cmmn.casetask.png[align=""center""] ==== Process task A process task is used to start a process instance within the context of a case. When the process task is blocking, the _PlanItemInstance_ will be _active_ until the process instance has completely finished. If the process task is non-blocking, the process instance is started and the plan item instance automatically completes. When the process instance is ended, there is no impact on the parent case. Properties: * *name*: an expression or static text that determines the name * *blocking*: a boolean value determining whether the task blocks * *blockingExpression*: an expression that evaluates to a boolean indicating whether the tasks blocks * *Process reference*: the key of the process definition that is used to start the process instance. Can be an expression. A process task is visualized as a rounded rectangle with an arrow icon in the top left corner: image::images/cmmn.processtask.png[align=""center""] ==== Criteria ===== Entry criterion Entry criteria form a sentry for a given plan item instance. They consist of two parts: * One or more parts depending on other plan items: these define dependencies on state transitions of other plan items. For example, one human task can depend on the state transition 'complete' of three other human tasks to become active itself. * One optional _if part_ or _condition_: this is an expression that allows to define a complex condition. A sentry is satisfied when all of its criteria are resolved to true. When a certain criteria evaluates to true, this is stored and remembered for future evaluations. Note that entry criteria evaluations of all plan item instances in the _available_ state are executed whenever something changes in the case instance. Multiple sentries are possible on a plan item. However, when one is satisfied, the plan item moves from state _available_ to _active_. An entry criteria is visualized as a diamond shape (white color inside) on the border of a plan item: image::images/cmmn.entrycriteria.png[align=""center""] ===== Exit criterion Exit criteria form a sentry for a given plan item instance. They consist of two parts: * One or more parts depending on other plan items: these define dependencies on state transitions of other plan items. For example, one human task can depend on reaching a certain milestone to be automatically terminated. * One optional _if part_ or _condition_: this is an expression that allows to define a complex condition. A sentry is satisfied when all of its criteria are resolved to true. When a certain criteria evaluates to true, this is stored and remembered for future evaluations. Note that exit criteria evaluations of all plan item instances in the _active_ state are executed whenever something changes in the case instance. Multiple sentries are possible on a plan item. However, when one is satisfied, the plan item moves from state _active_ to _exit_. An exit criteria is visualized as a diamond shape (white color inside) on the border of a plan item: image::images/cmmn.exitcriteria.png[align=""center""] ==== Event Listeners ===== Timer Event Listener A timer event listener is used when the passing of time needs to be captured in a case model. A timer event listener is not a task and has a simpler plan item lifecycle compared to a _task_: the timer will simply move from _available_ to _completed_ when the event (in this case, the time passing) occurs. Properties: * *Timer expression*: an expression that defines when the timer should occur. Following options are possible: ** An expression resolving to a java.util.Date or org.joda.time.DateTime instance (for example _${someBean.calculateNextDate(someCaseInstanceVariable)}) ** An ISO8601 date ** An ISO8601 duration String (for example _PT5H_, indicating the timer should fire in 5 hours from instantiation) ** AN ISO8601 repetition String (for example R5/PT2H, indicating the timer should fire 5 times, each time waiting 2 hours) ** A String containing a cron expression * *Start trigger plan item/event*: allows to reference a plan item in the case model that triggers the start of the timer event listener. Note that setting a _start trigger_ for the timer event listener does not have a visual indication in the case model, as entry/exit criteria on sentries do have. A timer event listener is visualized as circle with a clock icon inside: image::images/cmmn.timereventlistener.png[align=""center""] ===== User Event Listener A user event listener can be used when neededing to capture a user interaction that influences the proceeding of a case directly, instead of indirectly via impacting variables or information in the case. When the event is captured an Occur transition is triggered on the event listener. Like timer event listeners, it has a much simpler lifecycle that a _task_. image::images/cmmn.usereventlistener.png[align=""center""] User event listeners can be queried using the _org.flowable.cmmn.api.runtime.UserEventListenerInstanceQuery_. Such a query can be created by calling the _cmmnRuntimeService.createUserEventListenerInstanceQuery()_ method. Note that a user event listener is a plan item instance under the hood, which means it can also be queried through the _org.flowable.cmmn.api.runtime.PlanItemInstanceQuery_ API. A user event listener can be completed by calling the _cmmnRuntimeService.completeUserEventListenerInstance(id)_ method. ==== Item control: Repetition Rule Plan items on the case model can have a _repetition rule_, an expression that can be used to indicate a certain plan item needs to be repeated. When no expression is set, but the repetition is enabled (e.g. the checkbox is checked in the Flowable Modeler) or the expression is empty, a _true_ value is assumed by default. An optional _repetition counter variable_ can be set, that holds the index (one-based) of the instance. If not set, the default variable name is _repeitionCounter_. If the plan item does not have any entry criteria, the repetition rule expression is evaluated when the plan item is completed or terminated. If the expression resolved to _true_, a new instance is created. For example, a human task with a repetition rule expression _${repetitionCounter < 3}_, will create three sequential human tasks. If the plan item does have entry criteria, the behavior is different. The repetition rule is not evaluated on completion or termination, but when a sentry of the plan item is satisfied. If both the sentry is satisfied and the repetition rule evaluates to true, a new instance is created. Take for example the following timer event listener followed by a human task. The sentry has one entry criteria for the _occur_ event of the timer event listener. Note that enabling and setting the repetition rule on the task has a visual indication at the bottom of the rectangle. image::images/cmmn.repeatingtimereventlistener.png[align=""center""] If the timer event listener is repeating (for example _R/PT1H_), the _occur_ event will be fired every hour. When the repetition rule expression of the human task evaluates to true, a new human task instance will be created each hour. ==== Item control: Manual Activation Rule Plan items on the case model can have a _manual activation rule_, an expression that can be used to indicate a certain plan item needs to be _manually activated by an end-user_. When no expression is set, but the manual activation is enabled (e.g. the checkbox is checked in the Flowable Modeler) or the expression is empty, a _true_ value is assumed by default. Stages and all task types can be marked for manual activation. Visually, the task or stage will get a 'play' icon (small triangle pointing to the right) to indicate an end-user will have to manually activate it: image::images/cmmn.manual-activation.png[align=""center""] Normally, when a sentry for a plan item is satisfied (or the plan item doesn't have any sentries) the plan item instance is automatically moved to the _ACTIVE_ state. When a manual activation is set though, and it evaluates to true, the plan item instance now becomes _ENABLED_ instead of _ACTIVE_. As the name implies, the idea behind this is that end-users manually have to activate the plan item instance. A typical use case is for example showing a list of buttons of potential plan item instances that can currently be started by the end user. To start an enabled plan item instance, the _startPlanItemInstance_ method of the _CmmnRuntimeService_ can be used: [source,java,linenums] ---- List enabledPlanItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery() .caseInstanceId(caseInstance.getId()) .planItemInstanceStateEnabled() .list(); // ... cmmnRuntimeService.startPlanItemInstance(planItemInstance.getId()); ---- Note that the behaviour of a task only is executed when the plan item instance moves into the _ACTIVE_ state. For example, for a human task, the user task will only be created after calling the _startPlanItemInstance_ method. Plan item instances that are enabled, can be moved into the _DISABLED_ state: [source,java,linenums] ---- cmmnRuntimeService.disablePlanItemInstance(planItemInstance.getId()); ---- Disabled plan item instances can be enabled again: [source,java,linenums] ---- cmmnRuntimeService.enablePlanItemInstance(planItemInstance.getId()); ---- Note that with regards to determining stage or case instance termination, the _DISABLED_ state is seen as a 'terminal' state. This means that the case instance will terminate when only disabled plan item instances would remain. ==== Item control: Required Rule Plan items on the case model can have a _required rule_, an expression that can be used to indicate a certain plan item is _required by the enclosing stage (or plan model)_. This can be used to indicate which plan items of the case model are required to be executed and which are optional. When no expression is set, but the required rule is enabled (e.g. the checkbox is checked in the Flowable Modeler) or the expression is empty, a _true_ value is assumed by default. The _required rule_ works in conjunction with the _autoComplete_ attribute on the parent stage: * If _autoComplete_ resolves to _false_ for the stage, which is also the default when nothing is set, *all* child plan item instances must be in an end state (completed, terminated, etc.) for the stage plan item instance to completed by the engine. * If _autoComplete_ resolves to _true_ for the stage, all child plan item instances for *which the required rule evaluates to true* need to be in an end state. If there are also no other active child plan item instances, the stage completes automatically. A _stage plan item instance_ has a *completeable* property that can be used to see whether or not the conditions for completion are satisfied. Take for example the following simple stage and assume that the sentry for the _required task_ evaluates to true and the other one to false. This means that the left plan item instance will be active while the right one will be in the _available_ state. image::images/cmmn.completeable-stage.png[align=""center""] Calling _cmmnRuntimeService.completeStagePlanItemInstance(String stagePlanItemInstanceId)_ will not be possible for the stage (an exception will be thrown) as it has one active child plan item instance. When this user task on the left is completed, the _completeStagePlanItemInstance_ can now be called, as no child plan item instances are currently active. However, by itself the stage will not automatically complete as the right user task is in the available state. If the previous stage is changed to be *autoCompleteable* (this is visualised by a black rectangle at the bottom of the stage) and the plan item on the left is changed to be required (this is visualised using an exclamation mark), the behavior will be different: image::images/cmmn.completeable-stage02.png[align=""center""] * If the left plan item instance is active (sentry is true) and the right is not (sentry is false). In this case, when the left user task is completed, the stage instance will auto complete as it has no active child plan item instances and all required plan item instances are in an end state * If both the left and right user tasks are active (sentries are true). ** When the left user task is completed, the stage will not autocomplete as there is still a child plan item instance active. ** When the right user task is completed, the stage will not autocomplete as the required left child plan item instance is not in an end state. * If the left plan item instance is not active and the right is active. In this case, when the right user task is completed the stage will not autocomplete, as the required left user task is not in an end state. It will need to become active and be completed to complete the stage. Note that the manual activation rule works independently from the required rule. For example, given the following stage: image::images/cmmn.completeable-stage03.png[align=""center""] Here, user task D is required, and user task B is manually activated. * If D is completed, the stage will automatically complete, as B is not required and it is not active. * If B would be required too, it would need to be manually started (using _cmmnRuntimeService.startPlanItemInstance(String planItemInstanceId)_) before the stage would automatically complete, even if D would be completed before the manual start of B. ==== Item control: Completion Neutral Rule _Completion Neutral Rule_ is not a CMMN 1.1 Standard. The completion neutral rule impacts the interpretation of the *AVAILABLE* state of plan items that have it, when evaluating whether or not a Stage containing such plan items can complete. Following the specification, a stage with a plan item in state *AVAILABLE* does not complete unless its _autoComplete_ attribute is set _true_. But an _autoCompletable_ stage would _ignore_, for the purposes of completing, *all* plan items in _ENABLE_ and _AVAILABLE_ state that are _not required_ (*requiredRule* not present or evaluates to _false_). _Completion Neutral_ offers the flexibility to mark only some containing plan items without setting the containing parent stage as _autoComplete_. _Required Rule_ takes precedence when plan items that having both rules, both evaluate to _true_. As a summary: * a plan item configured to be _""completion neutral""_ will not prevent a stage from completing if its in *AVAILABLE* state (i.e. waiting for a entry criteria sentry), meaning that such a plan item is neutral with respect to its parent stage completion evaluation. * a stage will remain *ACTIVE* on any of these conditions: 1. It has at least one plan item in *ACTIVE* state 2. It has at least one plan item with _requiredRule_ in *AVAILABLE* or *ENABLE* state 3. If it isn't _autoComplete_ and has at least one plan item on *ENABLED* state (irrespectively on its _requiredRule_) 4. If it isn't _autoComplete_ and has at least one plan item on *AVAILABLE* state that is *not* _completionNeutral_ * a stage will *COMPLETE* if: 1. It contains *no* plan items or all child plan items are in a _Terminal_ or _Semi-terminal_ state (CLOSED, COMPLETED, DISABLED, FAILED) 2. If it isn't _autoComplete_, all remaining plan items (not _Terminal_ or _Semi-terminal_ state) are in *AVAILABLE* state and are _completionNeutral_ and not _required_ 3. If is is _autoComplete_, all remaining plan items (not _Terminal_ or _Semi-terminal) are _not required_ in *ENABLED* or *AVAILABLE* state (regardless of its completion neutrality)",12260,False,1834.1208867386092,median "// Use these for links to issue and pulls. Note issues and pulls redirect one to // each other on Github, so don't worry too much on using the right prefix. :issue: https://github.com/elastic/beats/issues/ :pull: https://github.com/elastic/beats/pull/ === Beats version HEAD https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD diff] ==== Breaking changes *Affecting all Beats* - Update to Golang 1.12.1. {pull}11330[11330] - Update to Golang 1.12.4. {pull}11782[11782] - Update to ECS 1.0.1. {pull}12284[12284] {pull}12317[12317] - Default of output.kafka.metadata.full is set to false by now. This reduced the amount of metadata to be queried from a kafka cluster. {pull}12738[12738] - Fixed a crash under Windows when fetching processes information. {pull}12833[12833] - Update to Golang 1.12.7. {pull}12931[12931] - Remove `in_cluster` configuration parameter for Kuberentes, now in-cluster configuration is used only if no other kubeconfig is specified {pull}13051[13051] - Disable Alibaba Cloud and Tencent Cloud metadata providers by default. {pull}13812[12812] - Libbeat HTTP's Server can listen to a unix socket using the `unix:///tmp/hello.sock` syntax. {pull}13655[13655] - Libbeat HTTP's Server can listen to a Windows named pipe using the `npipe:///hello` syntax. {pull}13655[13655] *Auditbeat* - Auditd module: Normalized value of `event.category` field from `user-login` to `authentication`. {pull}11432[11432] - Auditd module: Unset `auditd.session` and `user.audit.id` fields are removed from audit events. {issue}11431[11431] {pull}11815[11815] - Socket dataset: Exclude localhost by default {pull}11993[11993] - Socket dataset: New implementation using Kprobes for finer-grained monitoring and UDP support. {pull}13058[13058] *Filebeat* - Add read_buffer configuration option. {pull}11739[11739] - `convert_timezone` option is removed and locale is always added to the event so timezone is used when parsing the timestamp, this behaviour can be overriden with processors. {pull}12410[12410] - Fix a race condition in the TCP input when close the client socket. {pull}13038[13038] - cisco/asa fileset: Renamed log.original to event.original and cisco.asa.list_id to cisco.asa.rule_name. {pull}13286[13286] - cisco/asa fileset: Fix parsing of 302021 message code. {pull}13476[13476] - Add support for gzipped files in S3 input {pull}13980[13980] *Heartbeat* - Removed the `add_host_metadata` and `add_cloud_metadata` processors from the default config. These don't fit well with ECS for Heartbeat and were rarely used. *Journalbeat* *Metricbeat* - Add new dashboards for Azure vms, vm guest metrics, vm scale sets {pull}14000[14000] - Add new Dashboard for PostgreSQL database stats {pull}13187[13187] - Add new dashboard for CouchDB database {pull}13198[13198] - Add new dashboard for Ceph cluster stats {pull}13216[13216] - Add new dashboard for Aerospike database stats {pull}13217[13217] - Add new dashboard for Couchbase cluster stats {pull}13212[13212] - Add new dashboard for Prometheus server stats {pull}13126[13126] - Add new option `OpMultiplyBuckets` to scale histogram buckets to avoid decimal points in final events {pull}10994[10994] - system/raid metricset now uses /sys/block instead of /proc/mdstat for data. {pull}11613[11613] - kubernetes.container.cpu.limit.cores and kubernetes.container.cpu.requests.cores are now floats. {issue}11975[11975] - Add statistic option into cloudwatch metricset. If there is no statistic method specified, default is to collect Average, Sum, Maximum, Minimum and SampleCount. {issue}12370[12370] {pull}12840[12840] *Packetbeat* - Add support for mongodb opcode 2013 (OP_MSG). {issue}6191[6191] {pull}8594[8594] - NFSv4: Always use opname `ILLEGAL` when failed to match request to a valid nfs operation. {pull}11503[11503] *Winlogbeat* *Functionbeat* - Separate management and functions in Functionbeat. {pull}12939[12939] ==== Bugfixes *Affecting all Beats* - Fix typo in TLS renegotiation configuration and setting the option correctly {issue}10871[10871], {pull}12354[12354] - Ensure all beat commands respect configured settings. {pull}10721[10721] - Add missing fields and test cases for libbeat add_kubernetes_metadata processor. {issue}11133[11133], {pull}11134[11134] - decode_json_field: process objects and arrays only {pull}11312[11312] - decode_json_field: do not process arrays when flag not set. {pull}11318[11318] - Report faulting file when config reload fails. {pull}11304[11304] - Fix a typo in libbeat/outputs/transport/client.go by updating `c.conn.LocalAddr()` to `c.conn.RemoteAddr()`. {pull}11242[11242] - Management configuration backup file will now have a timestamps in their name. {pull}11034[11034] - [CM] Parse enrollment_token response correctly {pull}11648[11648] - Not hiding error in case of http failure using elastic fetcher {pull}11604[11604] - Escape BOM on JsonReader before trying to decode line {pull}11661[11661] - Fix matching of string arrays in contains condition. {pull}11691[11691] - Replace wmi queries with win32 api calls as they were consuming CPU resources {issue}3249[3249] and {issue}11840[11840] - Fix a race condition with the Kafka pipeline client, it is possible that `Close()` get called before `Connect()` . {issue}11945[11945] - Fix queue.spool.write.flush.events config type. {pull}12080[12080] - Fixed a memory leak when using the add_process_metadata processor under Windows. {pull}12100[12100] - Fix of docker json parser for missing ""log"" jsonkey in docker container's log {issue}11464[11464] - Fixed Beat ID being reported by GET / API. {pull}12180[12180] - Fixed setting bulk max size in kafka output. {pull}12254[12254] - Add host.os.codename to fields.yml. {pull}12261[12261] - Fix `@timestamp` being duplicated in events if `@timestamp` is set in a processor (or by any code utilizing `PutValue()` on a `beat.Event`). - Fix leak in script processor when using Javascript functions in a processor chain. {pull}12600[12600] - Add additional nil pointer checks to Docker client code to deal with vSphere Integrated Containers {pull}12628[12628] - Fixed `json.add_error_key` property setting for delivering error messages from beat events {pull}11298[11298] - Fix Central Management enroll under Windows {issue}12797[12797] {pull}12799[12799] - ILM: Use GET instead of HEAD when checking for alias to expose detailed error message. {pull}12886[12886] - Fix seccomp policy preventing some features to function properly on 32bit Linux systems. {issue}12990[12990] {pull}13008[13008] - Fix unexpected stops on docker autodiscover when a container is restarted before `cleanup_timeout`. {issue}12962[12962] {pull}13127[13127] - Fix install-service.ps1's ability to set Windows service's delay start configuration. {pull}13173[13173] - Fix some incorrect types and formats in field.yml files. {pull}13188[13188] - Load DLLs only from Windows system directory. {pull}13234[13234] {pull}13384[13384] - Fix mapping for kubernetes.labels and kubernetes.annotations in add_kubernetes_metadata. {issue}12638[12638] {pull}13226[13226] - Fix case insensitive regular expressions not working correctly. {pull}13250[13250] - Disable `add_kubernetes_metadata` if no matchers found. {pull}13709[13709] - Better wording for xpack beats when the _xpack endpoint is not reachable. {pull}13771[13771] - Recover from panics in the javascript process and log details about the failure to aid in future debugging. {pull}13690[13690] - Make the script processor concurrency-safe. {issue}13690[13690] {pull}13857[13857] - Kubernetes watcher at `add_kubernetes_metadata` fails with StatefulSets {pull}13905[13905] *Auditbeat* - Process dataset: Fixed a memory leak under Windows. {pull}12100[12100] - Login dataset: Fix re-read of utmp files. {pull}12028[12028] - Package dataset: Fixed a crash inside librpm after Auditbeat has been running for a while. {issue}12147[12147] {pull}12168[12168] - Fix formatting of config files on macOS and Windows. {pull}12148[12148] - Fix direction of incoming IPv6 sockets. {pull}12248[12248] - Package dataset: Close librpm handle. {pull}12215[12215] - Package dataset: Auto-detect package directories. {pull}12289[12289] - Package dataset: Improve dpkg parsing. {pull}12325[12325] - System module: Start system module without host ID. {pull}12373[12373] - Host dataset: Fix reboot detection logic. {pull}12591[12591] - Add syscalls used by librpm for the system/package dataset to the default Auditbeat seccomp policy. {issue}12578[12578] {pull}12617[12617] - Process dataset: Do not show non-root warning on Windows. {pull}12740[12740] - Host dataset: Export Host fields to gob encoder. {pull}12940[12940] - Socket dataset: Fix start errors when IPv6 is disabled on the kernel. {issue}13953[13953] {pull}13966[13966] *Filebeat* - Add support for Cisco syslog format used by their switch. {pull}10760[10760] - Cover empty request data, url and version in Apache2 module{pull}10730[10730] - Fix registry entries not being cleaned due to race conditions. {pull}10747[10747] - Improve detection of file deletion on Windows. {pull}10747[10747] - Add missing Kubernetes metadata fields to Filebeat CoreDNS module, and fix a documentation error. {pull}11591[11591] - Reduce memory usage if long lines are truncated to fit `max_bytes` limit. The line buffer is copied into a smaller buffer now. This allows the runtime to release unused memory earlier. {pull}11524[11524] - Fix memory leak in Filebeat pipeline acker. {pull}12063[12063] - Fix goroutine leak caused on initialization failures of log input. {pull}12125[12125] - Fix goroutine leak on non-explicit finalization of log input. {pull}12164[12164] - Skipping unparsable log entries from docker json reader {pull}12268[12268] - Parse timezone in PostgreSQL logs as part of the timestamp {pull}12338[12338] - Load correct pipelines when system module is configured in modules.d. {pull}12340[12340] - Fix timezone offset parsing in system/syslog. {pull}12529[12529] - When TLS is configured for the TCP input and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584] - Apply `max_message_size` to incoming message buffer. {pull}11966[11966] - Syslog input will now omit the `process` object from events if it is empty. {pull}12700[12700] - Fix multiline pattern in Postgres which was too permissive {issue}12078[12078] {pull}13069[13069] - Allow path variables to be used in files loaded from modules.d. {issue}13184[13184] - Fix filebeat autodiscover fileset hint for container input. {pull}13296[13296] - Fix incorrect references to index patterns in AWS and CoreDNS dashboards. {pull}13303[13303] - Fix timezone parsing of system module ingest pipelines. {pull}13308[13308] - Fix timezone parsing of elasticsearch module ingest pipelines. {pull}13367[13367] - Change iis url path grok pattern from URIPATH to NOTSPACE. {issue}12710[12710] {pull}13225[13225] {issue}7951[7951] {pull}13378[13378] - Fix timezone parsing of nginx module ingest pipelines. {pull}13369[13369] - Fix incorrect field references in envoyproxy dashboard {issue}13420[13420] {pull}13421[13421] - Fixed early expiration of templates (Netflow v9 and IPFIX). {pull}13821[13821] - Fixed bad handling of sequence numbers when multiple observation domains were exported by a single device (Netflow V9 and IPFIX). {pull}13821[13821] - Fix timezone parsing of rabbitmq module ingest pipelines. {pull}13879[13879] - Fix conditions and error checking of date processors in ingest pipelines that use `event.timezone` to parse dates. {pull}13883[13883] - Fix timezone parsing of Cisco module ingest pipelines. {pull}13893[13893] - Fix timezone parsing of logstash module ingest pipelines. {pull}13890[13890] - cisco asa and ftd filesets: Fix parsing of message 106001. {issue}13891[13891] {pull}13903[13903] - Fix timezone parsing of iptables, mssql and panw module ingest pipelines. {pull}13926[13926] - Fix merging of fields specified in global scope with fields specified under an input's scope. {issue}3628[3628] {pull}13909[13909] - Fix delay in enforcing close_renamed and close_removed options. {issue}13488[13488] {pull}13907[13907] - Fix missing netflow fields in index template. {issue}13768[13768] {pull}13914[13914] - Fix cisco module's asa and ftd filesets parsing of domain names where an IP address is expected. {issue}14034[14034] - Fixed increased memory usage with large files when multiline pattern does not match. {issue}14068[14068] - panw module: Use geo.name instead of geo.country_iso_code for free-form location. {issue}13272[13272] *Heartbeat* - Fix NPEs / resource leaks when executing config checks. {pull}11165[11165] - Fix duplicated IPs on `mode: all` monitors. {pull}12458[12458] - Fix integer comparison on JSON responses. {pull}13348[13348] *Journalbeat* - Use backoff when no new events are found. {pull}11861[11861] - Iterate over journal correctly, so no duplicate entries are sent. {pull}12716[12716] - Preserve host name when reading from remote journal. {pull}12714[12714] *Metricbeat* - Change diskio metrics retrieval method (only for Windows) from wmi query to DeviceIOControl function using the IOCTL_DISK_PERFORMANCE control code {pull}11635[11635] - Call GetMetricData api per region instead of per instance. {issue}11820[11820] {pull}11882[11882] - Update documentation with cloudwatch:ListMetrics permission. {pull}11987[11987] - Check permissions in system socket metricset based on capabilities. {pull}12039[12039] - Get process information from sockets owned by current user when system socket metricset is run without privileges. {pull}12039[12039] - Avoid generating hints-based configuration with empty hosts when no exposed port is suitable for the hosts hint. {issue}8264[8264] {pull}12086[12086] - Fixed a socket leak in the postgresql module under Windows when SSL is disabled on the server. {pull}11393[11393] - Change some field type from scaled_float to long in aws module. {pull}11982[11982] - Fixed RabbitMQ `queue` metricset gathering when `consumer_utilisation` is set empty at the metrics source {pull}12089[12089] - Fix direction of incoming IPv6 sockets. {pull}12248[12248] - Refactored Windows perfmon metricset: replaced method to retrieve counter paths with PdhExpandWildCardPathW, separated code by responsibility, removed unused functions {pull}12212[12212] - Validate that kibana/status metricset cannot be used when xpack is enabled. {pull}12264[12264] - Ignore prometheus metrics when their values are NaN or Inf. {pull}12084[12084] {issue}10849[10849] - In the kibana/stats metricset, only log error (don't also index it) if xpack is enabled. {pull}12265[12265] - Fix an issue listing all processes when run under Windows as a non-privileged user. {issue}12301[12301] {pull}12475[12475] - The `elasticsearch/index_summary` metricset gracefully handles an empty Elasticsearch cluster when `xpack.enabled: true` is set. {pull}12489[12489] {issue}12487[12487] - When TLS is configured for the http metricset and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584] - Reuse connections in PostgreSQL metricsets. {issue}12504[12504] {pull}12603[12603] - PdhExpandWildCardPathW will not expand counter paths in 32 bit windows systems, workaround will use a different function. {issue}12590[12590] {pull}12622[12622] - In the elasticsearch/node_stats metricset, if xpack is enabled, make parsing of ES node load average optional as ES on Windows doesn't report load average. {pull}12866[12866] - Ramdisk is not filtered out when collecting disk performance counters in diskio metricset {issue}12814[12814] {pull}12829[12829] - Fix incoherent behaviour in redis key metricset when keyspace is specified both in host URL and key pattern {pull}12913[12913] - Fix connections leak in redis module {pull}12914[12914] {pull}12950[12950] - Fix wrong uptime reporting by system/uptime metricset under Windows. {pull}12915[12915] - Print errors that were being omitted in vSphere metricsets. {pull}12816[12816] - Fix redis key metricset dashboard references to index pattern. {pull}13303[13303] - Check if fields in DBInstance is nil in rds metricset. {pull}13294[13294] {issue}13037[13037] - Fix silent failures in kafka and prometheus module. {pull}13353[13353] {issue}13252[13252] - Fix issue with aws cloudwatch module where dimensions and/or namespaces that contain space are not being parsed correctly {pull}13389[13389] - Fix panic in Redis Key metricset when collecting information from a removed key. {pull}13426[13426] - Fix module-level fields in Kubernetes metricsets. {pull}13433[13433] {pull}13544[13544] - Fix reporting empty events in cloudwatch metricset. {pull}13458[13458] - Fix `docker.cpu.system.pct` calculation by using the reported number online cpus instead of the number of metrics per cpu. {pull}13691[13691] - Fix rds metricset dashboard. {pull}13721[13721] - Ignore prometheus untyped metrics with NaN value. {issue}13750[13750] {pull}13790[13790] - Change kubernetes.event.message to text {pull}13964[13964] - Fix performance counter values for windows/perfmon metricset.{issue}14036[14036] {pull}14039[14039] *Packetbeat* - Prevent duplicate packet loss error messages in HTTP events. {pull}10709[10709] - Fixed a memory leak when using process monitoring under Windows. {pull}12100[12100] - Improved debug logging efficiency in PGQSL module. {issue}12150[12150] - Limit memory usage of Redis replication sessions. {issue}12657[12657] - Fix parsing the extended RCODE in the DNS parser. {pull}12805[12805] *Winlogbeat* - Fix data race affecting config validation at startup. {issue}13005[13005] *Functionbeat* - Fix function name reference for Kinesis streams in CloudFormation templates {pull}11646[11646] - Fix Cloudwatch logs timestamp to use timestamp of the log record instead of when the record was processed {pull}13291[13291] - Look for the keystore under the correct path. {pull}13332[13332] ==== Added *Affecting all Beats* - Decouple Debug logging from fail_on_error logic for rename, copy, truncate processors {pull}12451[12451] - Add an option to append to existing logs rather than always rotate on start. {pull}11953[11953] - Add `network` condition to processors for matching IP addresses against CIDRs. {pull}10743[10743] - Add if/then/else support to processors. {pull}10744[10744] - Add `community_id` processor for computing network flow hashes. {pull}10745[10745] - Add output test to kafka output {pull}10834[10834] - Gracefully shut down on SIGHUP {pull}10704[10704] - New processor: `copy_fields`. {pull}11303[11303] - Add `error.message` to events when `fail_on_error` is set in `rename` and `copy_fields` processors. {pull}11303[11303] - New processor: `truncate_fields`. {pull}11297[11297] - Allow a beat to ship monitoring data directly to an Elasticsearch monitoring cluster. {pull}9260[9260] - Updated go-seccomp-bpf library to v1.1.0 which updates syscall lists for Linux v5.0. {pull}11394[11394] - Add `add_observer_metadata` processor. {pull}11394[11394] - Add `decode_csv_fields` processor. {pull}11753[11753] - Add `convert` processor for converting data types of fields. {issue}8124[8124] {pull}11686[11686] - New `extract_array` processor. {pull}11761[11761] - Add number of goroutines to reported metrics. {pull}12135[12135] - Add `proxy_disable` output flag to explicitly ignore proxy environment variables. {issue}11713[11713] {pull}12243[12243] - Processor `add_cloud_metadata` adds fields `cloud.account.id` and `cloud.image.id` for AWS EC2. {pull}12307[12307] - Add configurable bulk_flush_frequency in kafka output. {pull}12254[12254] - Add `decode_base64_field` processor for decoding base64 field. {pull}11914[11914] - Add support for reading the `network.iana_number` field by default to the community_id processor. {pull}12701[12701] - Add aws overview dashboard. {issue}11007[11007] {pull}12175[12175] - Add `decompress_gzip_field` processor. {pull}12733[12733] - Add `timestamp` processor for parsing time fields. {pull}12699[12699] - Fail with error when autodiscover providers have no defined configs. {pull}13078[13078] - Add a check so alias creation explicitely fails if there is an index with the same name. {pull}13070[13070] - Update kubernetes watcher to use official client-go libraries. {pull}13051[13051] - Add support for unix epoch time values in the `timestamp` processor. {pull}13319[13319] - add_host_metadata is now GA. {pull}13148[13148] - Add an `ignore_missing` configuration option the `drop_fields` processor. {pull}13318[13318] - add_host_metadata is no GA. {pull}13148[13148] - Add `registered_domain` processor for deriving the registered domain from a given FQDN. {pull}13326[13326] - Add support for RFC3339 time zone offsets in JSON output. {pull}13227[13227] - Add autodetection mode for add_docker_metadata and enable it by default in included configuration files{pull}13374[13374] - Added `monitoring.cluster_uuid` setting to associate Beat data with specified ES cluster in Stack Monitoring UI. {pull}13182[13182] - Add autodetection mode for add_kubernetes_metadata and enable it by default in included configuration files. {pull}13473[13473] - Add `providers` setting to `add_cloud_metadata` processor. {pull}13812[13812] - Use less restrictive API to check if template exists. {pull}13847[13847] - Do not check for alias when setup.ilm.check_exists is false. {pull}13848[13848] - Add support for numeric time zone offsets in timestamp processor. {pull}13902[13902] - Add condition to the config file template for add_kubernetes_metadata {pull}14056[14056] - Marking Central Management deprecated. {pull}14018[14018] - Add `keep_null` setting to allow Beats to publish null values in events. {issue}5522[5522] {pull}13928[13928] *Auditbeat* - Auditd module: Add `event.outcome` and `event.type` for ECS. {pull}11432[11432] - Process: Add file hash of process executable. {pull}11722[11722] - Socket: Add network.transport and network.community_id. {pull}12231[12231] - Host: Fill top-level host fields. {pull}12259[12259] - Socket: Add DNS enrichment. {pull}14004[14004] *Filebeat* - Add more info to message logged when a duplicated symlink file is found {pull}10845[10845] - Add option to configure docker input with paths {pull}10687[10687] - Add Netflow module to enrich flow events with geoip data. {pull}10877[10877] - Set `event.category: network_traffic` for Suricata. {pull}10882[10882] - Allow custom default settings with autodiscover (for example, use of CRI paths for logs). {pull}12193[12193] - Allow to disable hints based autodiscover default behavior (fetching all logs). {pull}12193[12193] - Change Suricata module pipeline to handle `destination.domain` being set if a reverse DNS processor is used. {issue}10510[10510] - Add the `network.community_id` flow identifier to field to the IPTables, Suricata, and Zeek modules. {pull}11005[11005] - New Filebeat coredns module to ingest coredns logs. It supports both native coredns deployment and coredns deployment in kubernetes. {pull}11200[11200] - New module for Cisco ASA logs. {issue}9200[9200] {pull}11171[11171] - Added support for Cisco ASA fields to the netflow input. {pull}11201[11201] - Configurable line terminator. {pull}11015[11015] - Add Filebeat envoyproxy module. {pull}11700[11700] - Add apache2(httpd) log path (`/var/log/httpd`) to make apache2 module work out of the box on Redhat-family OSes. {issue}11887[11887] {pull}11888[11888] - Add support to new MongoDB additional diagnostic information {pull}11952[11952] - New module `panw` for Palo Alto Networks PAN-OS logs. {pull}11999[11999] - Add RabbitMQ module. {pull}12032[12032] - Add new `container` input. {pull}12162[12162] - Add timeouts on communication with docker daemon. {pull}12310[12310] - `container` and `docker` inputs now support reading of labels and env vars written by docker JSON file logging driver. {issue}8358[8358] - Add specific date processor to convert timezones so same pipeline can be used when convert_timezone is enabled or disabled. {pull}12253[12253] - Add MSSQL module {pull}12079[12079] - Add ISO8601 date parsing support for system module. {pull}12568[12568] {pull}12578[12579] - Update Kubernetes deployment manifest to use `container` input. {pull}12632[12632] - Use correct OS path separator in `add_kubernetes_metadata` to support Windows nodes. {pull}9205[9205] - Add support for virtual host in Apache access logs {pull}12778[12778] - Add support for client addresses with port in Apache error logs {pull}12695[12695] - Add `google-pubsub` input type for consuming messages from a Google Cloud Pub/Sub topic subscription. {pull}12746[12746] - Add module for ingesting Cisco IOS logs over syslog. {pull}12748[12748] - Add module for ingesting Google Cloud VPC flow logs. {pull}12747[12747] - Report host metadata for Filebeat logs in Kubernetes. {pull}12790[12790] - Add netflow dashboards based on Logstash netflow. {pull}12857[12857] - Parse more fields from Elasticsearch slowlogs. {pull}11939[11939] - Update module pipelines to enrich events with autonomous system fields. {pull}13036[13036] - Add module for ingesting IBM MQ logs. {pull}8782[8782] - Add S3 input to retrieve logs from AWS S3 buckets. {pull}12640[12640] {issue}12582[12582] - Add aws module s3access metricset. {pull}13170[13170] {issue}12880[12880] - Update Suricata module to populate ECS DNS fields and handle EVE DNS version 2. {issue}13320[13320] {pull}13329[13329] - Update PAN-OS fileset to use the ECS NAT fields. {issue}13320[13320] {pull}13330[13330] - Add fields to the Zeek DNS fileset for ECS DNS. {issue}13320[13320] {pull}13324[13324] - Add container image in Kubernetes metadata {pull}13356[13356] {issue}12688[12688] - Add timezone information to apache error fileset. {issue}12772[12772] {pull}13304[13304] - Add module for ingesting Cisco FTD logs over syslog. {pull}13286[13286] - Update CoreDNS module to populate ECS DNS fields. {issue}13320[13320] {pull}13505[13505] - Parse query steps in PostgreSQL slowlogs. {issue}13496[13496] {pull}13701[13701] - Add filebeat azure module with activitylogs, auditlogs, signinlogs filesets. {pull}13776[13776] {pull}14033[14033] - Add support to set the document id in the json reader. {pull}5844[5844] - Add input httpjson. {issue}13545[13545] {pull}13546[13546] - Filebeat Netflow input: Remove beta label. {pull}13858[13858] - Remove `event.timezone` from events that don't need it in some modules that support log formats with and without timezones. {pull}13918[13918] - Add ExpandEventListFromField config option in the kafka input. {pull}13965[13965] - Add ELB fileset to AWS module. {pull}14020[14020] - Add module for MISP (Malware Information Sharing Platform). {pull}13805[13805] *Heartbeat* - Add non-privileged icmp on linux and darwin(mac). {pull}13795[13795] {issue}11498[11498] - Enable `add_observer_metadata` processor in default config. {pull}11394[11394] - Record HTTP body metadata and optionally contents in `http.response.body.*` fields. {pull}13022[13022] - Allow `hosts` to be used to configure http monitors {pull}13703[13703] *Journalbeat* *Metricbeat* - Add AWS SQS metricset. {pull}10684[10684] {issue}10053[10053] - Add AWS s3_request metricset. {pull}10949[10949] {issue}10055[10055] - Add s3_daily_storage metricset. {pull}10940[10940] {issue}10055[10055] - Add `coredns` metricbeat module. {pull}10585[10585] - Add SSL support for Metricbeat HTTP server. {pull}11482[11482] {issue}11457[11457] - The `elasticsearch.index` metricset (with `xpack.enabled: true`) now collects `refresh.external_total_time_in_millis` fields from Elasticsearch. {pull}11616[11616] - Allow module configurations to have variants {pull}9118[9118] - Add `timeseries.instance` field calculation. {pull}10293[10293] - Added new disk states and raid level to the system/raid metricset. {pull}11613[11613] - Added `path_name` and `start_name` to service metricset on windows module {issue}8364[8364] {pull}11877[11877] - Add check on object name in the counter path if the instance name is missing {issue}6528[6528] {pull}11878[11878] - Add AWS cloudwatch metricset. {pull}11798[11798] {issue}11734[11734] - Add `regions` in aws module config to specify target regions for querying cloudwatch metrics. {issue}11932[11932] {pull}11956[11956] - Keep `etcd` followers members from reporting `leader` metricset events {pull}12004[12004] - Add overview dashboard to Consul module {pull}10665[10665] - New fields were added in the mysql/status metricset. {pull}12227[12227] - Add Kubernetes metricset `proxy`. {pull}12312[12312] - Add Kubernetes proxy dashboard to Kubernetes module {pull}12734[12734] - Always report Pod UID in the `pod` metricset. {pull}12345[12345] - Add Vsphere Virtual Machine operating system to `os` field in Vsphere virtualmachine module. {pull}12391[12391] - Add validation for elasticsearch and kibana modules' metricsets when xpack.enabled is set to true. {pull}12386[12386] - Add CockroachDB module. {pull}12467[12467] - Add support for metricbeat modules based on existing modules (a.k.a. light modules) {issue}12270[12270] {pull}12465[12465] - Add a system/entropy metricset {pull}12450[12450] - Add kubernetes metricset `controllermanager` {pull}12409[12409] - Add Kubernetes controller manager dashboard to Kubernetes module {pull}12744[12744] - Allow redis URL format in redis hosts config. {pull}12408[12408] - Add tags into ec2 metricset. {issue}[12263]12263 {pull}12372[12372] - Add metrics to kubernetes apiserver metricset. {pull}12922[12922] - Add kubernetes metricset `scheduler` {pull}12521[12521] - Add Kubernetes scheduler dashboard to Kubernetes module {pull}12749[12749] - Add `beat` module. {pull}12181[12181] {pull}12615[12615] - Collect tags for cloudwatch metricset in aws module. {issue}[12263]12263 {pull}12480[12480] - Add AWS RDS metricset. {pull}11620[11620] {issue}10054[10054] - Add Oracle Module {pull}11890[11890] - Add Oracle Tablespaces Dashboard {pull}12736[12736] - Collect client provided name for rabbitmq connection. {issue}12851[12851] {pull}12852[12852] - Add support to load default aws config file to get credentials. {pull}12727[12727] {issue}12708[12708] - Add statistic option into cloudwatch metricset. {issue}12370[12370] {pull}12840[12840] - Add support for kubernetes cronjobs {pull}13001[13001] - Add cgroup memory stats to docker/memory metricset {pull}12916[12916] - Add AWS elb metricset. {pull}12952[12952] {issue}11701[11701] - Add AWS ebs metricset. {pull}13167[13167] {issue}11699[11699] - Add `metricset.period` field with the configured fetching period. {pull}13242[13242] {issue}12616[12616] - Add rate metrics for ec2 metricset. {pull}13203[13203] - Add refresh list of perf counters at every fetch {issue}13091[13091] - Add Performance metricset to Oracle module {pull}12547[12547] - Add proc/vmstat data to the system/memory metricset on linux {pull}13322[13322] - Use DefaultMetaGeneratorConfig in MetadataEnrichers to initialize configurations {pull}13414[13414] - Add module for statsd. {pull}13109[13109] - Add support for NATS version 2. {pull}13601[13601] - Add `docker.cpu.*.norm.pct` metrics for `cpu` metricset of Docker Metricbeat module. {pull}13695[13695] - Add `instance` label by default when using Prometheus collector. {pull}13737[13737] - Add azure module. {pull}13196[13196] {pull}13859[13859] {pull}13988[13988] - Add Apache Tomcat module {pull}13491[13491] - Add ECS `container.id` and `container.runtime` to kubernetes `state_container` metricset. {pull}13884[13884] - Add `job` label by default when using Prometheus collector. {pull}13878[13878] - Add `state_resourcequota` metricset for Kubernetes module. {pull}13693[13693] - Add tags filter in ec2 metricset. {pull}13872[13872] {issue}13145[13145] - Add cloud.account.id and cloud.account.name into events from aws module. {issue}13551[13551] {pull}13558[13558] - Add `metrics_path` as known hint for autodiscovery {pull}13996[13996] - Leverage KUBECONFIG when creating k8s client. {pull}13916[13916] - Add ability to filter by tags for cloudwatch metricset. {pull}13758[13758] {issue}13145[13145] *Packetbeat* - Update DNS protocol plugin to produce events with ECS fields for DNS. {issue}13320[13320] {pull}13354[13354] *Functionbeat* - New options to configure roles and VPC. {pull}11779[11779] - Export automation templates used to create functions. {pull}11923[11923] - Configurable Amazon endpoint. {pull}12369[12369] - Add timeout option to reference configuration. {pull}13351[13351] - Configurable tags for Lambda functions. {pull}13352[13352] - Add input for Cloudwatch logs through Kinesis. {pull}13317[13317] - Enable Logstash output. {pull}13345[13345] - Make `bulk_max_size` configurable in outputs. {pull}13493[13493] *Winlogbeat* - Add support for reading from .evtx files. {issue}4450[4450] - Add support for event ID 4634 and 4647 to the Security module. {pull}12906[12906] - Add `network.community_id` to Sysmon network events (event ID 3). {pull}13034[13034] - Add `event.module` to Winlogbeat modules. {pull}13047[13047] - Add `event.category: process` and `event.type: process_start/process_end` to Sysmon process events (event ID 1 and 5). {pull}13047[13047] - Add support for event ID 4672 to the Security module. {pull}12975[12975] - Add support for event ID 22 (DNS query) to the Sysmon module. {pull}12960[12960] - Add certain winlog.event_data.* fields to the index template. {issue}13700[13700] {pull}13704[13704] - Fill `event.provider`. {pull}13937[13937] - Add support for user management events to the Security module. {pull}13530[13530] ==== Deprecated *Affecting all Beats* *Filebeat* - `docker` input is deprecated in favour `container`. {pull}12162[12162] - `postgresql.log.timestamp` field is deprecated in favour of `@timestamp`. {pull}12338[12338] *Heartbeat* *Journalbeat* *Metricbeat* - `kubernetes.container.id` field for `state_container` is deprecated in favour of ECS `container.id` and `container.runtime`. {pull}13884[13884] *Packetbeat* *Winlogbeat* *Functionbeat* ==== Known Issue *Journalbeat* ",12282,True,2836.6791414337026,median "#include /** * Unit tests for DynamixelBus class. * */ #include #include DynamixelBus dynamixel(Serial1); /* * CAUTION! * These tests will run using the first servo found using the discovery method. * The servo limits, position, speed and torque limit values are modified * in many of the tests. The tests may be safely run using a freestanding * servo, but care must be taken when running the tests if the servo is attached * brackets or assemblies that restrict the movement of the servo. * The following macros may be used to establish limits for the test suite. * However, test failures may leave the servo configured in a state different from that * proir to executing the tests. You can try re-running the test suite to restore * the defaults given below if the test failures occurred as a result of * communication errors or alarm conditions. */ #define DEFAULT_MIN_ANGLE (512 - 64) #define DEFAULT_MAX_ANGLE (512 + 64) #define DEFAULT_TORQUE_LIMIT 256 #define DEFAULT_GOAL_POSITION 512 #define DEFAULT_GOAL_SPEED 256 #define DEFAULT_PUNCH 32 #define DEFAULT_MIN_VOLTAGE 6000 #define DEFAULT_MAX_VOLTAGE 14000 /* * Set these macros to TRUE or FALSE to control whether a test is included. * Each test reduces the amount of memory for program execution, * so you will generally need to disable most tests to successfully * compile the sketch while also leaving enough RAM to run the tests. */ #define TRUE 1 #define FALSE 0 #define TEST_PING FALSE #define TEST_MODELNUMBER_AX12 FALSE #define TEST_FIRMWAREVERSION_AX12 FALSE #define TEST_DISCOVER FALSE #define TEST_BAUD_RATE FALSE #define TEST_RETURN_DELAY_TIME FALSE #define TEST_ANGLE_LIMITS FAKSE #define TEST_TEMPERATURE_LIMIT FALSE #define TEST_VOLTAGE_LIMITS FALSE #define TEST_INITIAL_TORQUE_LIMIT FALSE #define TEST_STATUS_RETURN_LEVEL FALSE #define TEST_ALARM_LED FALSE #define TEST_ALARM_SHUTDOWN FALSE #define TEST_TORQUE_ENABLE FALSE #define TEST_LED FALSE #define TEST_COMPLIANCE_MARGINS FALSE #define TEST_COMPLIANCE_SLOPES FALSE #define TEST_GOAL_POSITION FALSE #define TEST_GOAL_SPEED FALSE #define TEST_TORQUE_LIMIT FALSE #define TEST_PRESENT_STATE FALSE #define TEST_REGISTERED_INSTRUCTION FALSE #define TEST_MOVING FALSE #define TEST_LOCK FALSE #define TEST_PUNCH FALSE // Global state variable required in multiple tests uint8_t servoId = 0; uint16_t servoMinAngle = DEFAULT_MIN_ANGLE; // +90 uint16_t servoMaxAngle = DEFAULT_MAX_ANGLE; // -90 void setup() { delay(1000); Serial.begin(115200); while(Serial.read() == -1); Serial.println(""DynamixelBus Unit Tests\\n""); dynamixel.begin(DynamixelBus::k1000000); // Must call this method to update internal state even // if the initial baud rate is incorrect as the DynamixelBus // initially assumes a state of kRespondToNone. dynamixel.setStatusReturnLevel(0xFE,DynamixelBus::kRespondToAll); Serial.println(""Starting servo discovery...\\n""); dynamixel.setMaxRetriesOnError(4); size_t count = dynamixel.discover(&servoId,1,3); if (count == 0 || servoId == 0) { Serial.println(""### No tests can be run because no servos were found!""); return; } Serial.println(""Servo discovery complete.\\n""); // Bump up the retries to account for occasional bouts // communication errors that arise for some, as yet, unkown reason. dynamixel.setMaxRetriesOnError(8); // The discovery operation will have saved the servo's baud rate DynamixelBus::BaudRate baud; dynamixel.getBaudRate(servoId,baud); Serial.print(F(""Servo #"")); Serial.print(servoId); Serial.print(F("" baud="")); Serial.println(baud); // Switch to the servo's baud rate dynamixel.begin(baud); // Uncomment the following two statements to change the servo baud rate // dynamixel.setBaudRate(servoId,DynamixelBus::k115200); // dynamixel.begin(DynamixelBus::k115200); // Instruct the servo to respond to all instructions for testing purposes dynamixel.setStatusReturnLevel(servoId,DynamixelBus::kRespondToAll); dynamixel.setLed(servoId,false); // Enable torque so the servo can move as required in some tests dynamixel.setTorqueLimit(servoId,DEFAULT_TORQUE_LIMIT); dynamixel.setAngleLimits(servoId,DEFAULT_MIN_ANGLE,DEFAULT_MAX_ANGLE); dynamixel.setGoalPosition(servoId,DEFAULT_GOAL_POSITION); dynamixel.setGoalSpeed(servoId,DEFAULT_GOAL_SPEED); dynamixel.setTorqueEnable(servoId,true); // Uncomment the following to reset triggers to desired values // dynamixel.setAlarmLedTriggers(servoId,DynamixelBus::kOverloadError | DynamixelBus::kTemperatureLimitError); // dynamixel.setAlarmShutdownTriggers(servoId,DynamixelBus::kOverloadError | DynamixelBus::kTemperatureLimitError); // Now capture the current state of the servo.. // (No guarantee every one of these calls will succeed!) uint16_t servoModelNumber = 12; uint8_t servoFirmwareVersion = 0; uint16_t servoReturnDelayTime = 0; uint8_t servoTemperatureLimit = 0; uint16_t servoLowVoltageLimit = 0; uint16_t servoHighVoltageLimit = 0; uint16_t servoInitialTorqueLimit = 0; uint8_t servoAlarmLedTriggers = 0; uint8_t servoAlarmShutdownTriggers = 0; bool servoTorqueEnable = false; uint8_t servoCWComplianceMargin = 0; uint8_t servoCCWComplianceMargin = 0; uint8_t servoCWComplianceSlope = 0; uint8_t servoCCWComplianceSlope = 0; uint16_t servoGoalPosition = 0; uint16_t servoGoalSpeed = 0; uint16_t servoTorqueLimit = 0; uint16_t servoPresentPosition = 0; uint16_t servoPresentSpeed = 0; uint16_t servoPresentLoad = 0; uint8_t servoPresentLoadDirection = 0; uint16_t servoPresentVoltage = 0; uint8_t servoPresentTemperature = 0; bool servoLock = false; uint16_t servoPunch = 0; dynamixel.getModelNumber(servoId,servoModelNumber); dynamixel.getFirmwareVersion(servoId,servoFirmwareVersion); dynamixel.getReturnDelayTime(servoId,servoReturnDelayTime); dynamixel.getAngleLimits(servoId,servoMinAngle,servoMaxAngle); dynamixel.getTemperatureLimit(servoId,servoTemperatureLimit); dynamixel.getVoltageLimits(servoId,servoLowVoltageLimit,servoHighVoltageLimit); dynamixel.getInitialTorqueLimit(servoId,servoInitialTorqueLimit); dynamixel.getAlarmLedTriggers(servoId,servoAlarmLedTriggers); dynamixel.getAlarmShutdownTriggers(servoId,servoAlarmShutdownTriggers); dynamixel.getTorqueEnable(servoId,servoTorqueEnable); dynamixel.getComplianceMargins(servoId,servoCWComplianceMargin,servoCCWComplianceMargin); dynamixel.getComplianceSlopes(servoId,servoCWComplianceSlope,servoCCWComplianceSlope); dynamixel.getGoalPosition(servoId,servoGoalPosition); dynamixel.getGoalSpeed(servoId,servoGoalSpeed); dynamixel.getTorqueLimit(servoId,servoTorqueLimit); dynamixel.getLock(servoId,servoLock); dynamixel.getPunch(servoId,servoPunch); dynamixel.getPresentPosition(servoId,servoPresentPosition); dynamixel.getPresentSpeed(servoId,servoPresentSpeed); dynamixel.getPresentLoad(servoId,servoPresentLoadDirection,servoPresentLoad); dynamixel.getPresentVoltage(servoId,servoPresentVoltage); dynamixel.getPresentTemperature(servoId,servoPresentTemperature); Serial.println(F(""Executing tests using following servo:\\n"")); Serial.print(F(""Servo ID = "")); Serial.println(servoId); Serial.print(F("": Baud Rate index = "")); Serial.println(baud); Serial.print(F("": Model Number = "")); Serial.println(servoModelNumber); Serial.print(F("": Firmware Version = "")); Serial.println(servoFirmwareVersion); Serial.print(F("": Return Delay Time (usec) = "")); Serial.println(servoReturnDelayTime); Serial.print(F("": Angle Limits: cw = "")); Serial.print(servoMinAngle); Serial.print(F(""/1023 ("")); Serial.print((servoMinAngle * 300L / 1023)); Serial.print(F(""°) ccw = "")); Serial.print(servoMaxAngle); Serial.print(F(""/1023 ("")); Serial.print((servoMaxAngle * 300L / 1023)); Serial.println(""°)""); Serial.print(F("": Temperature Limit (C) = "")); Serial.println(servoTemperatureLimit); Serial.print(F("": Voltage Limits (V): low = "")); Serial.print(servoLowVoltageLimit/1000.0); Serial.print(F("" high = "")); Serial.println(servoHighVoltageLimit/1000.0); Serial.print(F("": Initial Torque Limit (EEPROM) = "")); Serial.print(servoInitialTorqueLimit); Serial.println(F(""/1023"")); Serial.print(F("": Alarm LED Errors: "")); if (servoAlarmLedTriggers & DynamixelBus::kInstructionError) Serial.print(F(""instruction, "")); if (servoAlarmLedTriggers & DynamixelBus::kOverloadError) Serial.print(F(""overload, "")); if (servoAlarmLedTriggers & DynamixelBus::kChecksumError) Serial.print(F(""checksum, "")); if (servoAlarmLedTriggers & DynamixelBus::kRangeError) Serial.print(F(""range, "")); if (servoAlarmLedTriggers & DynamixelBus::kTemperatureLimitError) Serial.print(F(""temperature, "")); if (servoAlarmLedTriggers & DynamixelBus::kAngleLimitError) Serial.print(F(""angle, "")); if (servoAlarmLedTriggers & DynamixelBus::kVoltageLimitError) Serial.print(F(""voltage"")); Serial.println(); Serial.print(F("": Alarm Shutdown Errors: "")); if (servoAlarmShutdownTriggers & DynamixelBus::kInstructionError) Serial.print(F(""instruction, "")); if (servoAlarmShutdownTriggers & DynamixelBus::kOverloadError) Serial.print(F(""overload, "")); if (servoAlarmShutdownTriggers & DynamixelBus::kChecksumError) Serial.print(F(""checksum, "")); if (servoAlarmShutdownTriggers & DynamixelBus::kRangeError) Serial.print(F(""range, "")); if (servoAlarmShutdownTriggers & DynamixelBus::kTemperatureLimitError) Serial.print(F(""temperature, "")); if (servoAlarmShutdownTriggers & DynamixelBus::kAngleLimitError) Serial.print(F(""angle, "")); if (servoAlarmShutdownTriggers & DynamixelBus::kVoltageLimitError) Serial.print(F(""voltage"")); Serial.println(); Serial.print(F("": Torque Enable = "")); Serial.println(servoTorqueEnable ? F(""true"") : F(""false"")); Serial.print(F("": Compliance Margins: cw = "")); Serial.print(servoCWComplianceMargin); Serial.print(F("" ccw = "")); Serial.println(servoCCWComplianceMargin); Serial.print(F("": Compliance Slopes: cw = "")); Serial.print(servoCWComplianceSlope); Serial.print(F("" ccw = "")); Serial.println(servoCCWComplianceSlope); Serial.print(F("": Goal Position = "")); Serial.print(servoGoalPosition); Serial.println(F(""/1023"")); Serial.print(F("": Goal Speed = "")); Serial.print(servoGoalSpeed); Serial.println(F(""/1023"")); Serial.print(F("": Torque Limit (RAM) = "")); Serial.print(servoTorqueLimit); Serial.println(F(""/1023"")); Serial.print(F("": Present Position = "")); Serial.println(servoPresentPosition); Serial.print(F("": Present Speed = "")); Serial.println(servoPresentSpeed); Serial.print(F("": Present Load = "")); Serial.print(servoPresentLoad); Serial.print(F("" direction = "")); Serial.println(servoPresentLoadDirection); Serial.print(F("": Present Voltage (Mv) = "")); Serial.println(servoPresentVoltage); Serial.print(F("": Present Temperature (C) = "")); Serial.println(servoPresentTemperature); Serial.print(F("": Lock = "")); Serial.println(servoLock ? F(""true"") : F(""false"")); Serial.print(F("": Punch = "")); Serial.print(servoPunch); Serial.println(F(""/1023"")); Serial.println(); // Select tests (that are included by the preprocessor) Test::exclude(""ModelNumber_*""); switch (servoModelNumber) { #if TEST_MODELNUMBER_AX12 == TRUE case 12: Test::include(""ModelNumber_AX12""); break; #endif } } #if TEST_PING == TRUE test(Ping) { assertTrue(dynamixel.ping(servoId)); assertFalse(dynamixel.ping(253)); } #endif #if TEST_MODELNUMBER_AX12 == TRUE test(ModelNumberAX12) { uint16_t getModelNumber = 0; assertEqual(dynamixel.getModelNumber(servoId,getModelNumber),DynamixelBus::kOk); assertEqual(getModelNumber,12); } #endif #if TEST_FIRMWAREVERSION_AX12 == TRUE test(FirmwareVersion_AX12) { uint8_t getVersion = 0; assertEqual(dynamixel.getFirmwareVersion(servoId,getVersion),DynamixelBus::kOk); assertMore(getVersion,0); } #endif #if TEST_DISCOVER == TRUE test(Discover) { uint8_t id; size_t count = dynamixel.discover(&id,1,servoId+1); assertTrue(count > 0); assertEqual(servoId,id); } #endif #if TEST_BAUD_RATE == TRUE test(BaudRate) { DynamixelBus::BaudRate currentBaud = DynamixelBus::kUnknown; dynamixel.getBaudRate(servoId,currentBaud); DynamixelBus::BaudRate putBaud = DynamixelBus::k115200; if (currentBaud == putBaud) putBaud = DynamixelBus::k57600; assertEqual(dynamixel.setBaudRate(servoId,putBaud),DynamixelBus::kOk); DynamixelBus::BaudRate getBaud = DynamixelBus::kUnknown; uint8_t error = dynamixel.getBaudRate(servoId,getBaud); if (error) { dynamixel.setBaudRate(servoId,currentBaud); fail(); } assertTrue(putBaud == getBaud); dynamixel.setBaudRate(servoId,currentBaud); } #endif #if TEST_RETURN_DELAY_TIME == TRUE test(ReturnDelayTime) { uint16_t currentReturnDelayTime = 0; assertEqual(dynamixel.getReturnDelayTime(servoId,currentReturnDelayTime),DynamixelBus::kOk); //Serial.print(""current return delay time: ""); //Serial.println(currentReturnDelayTime); uint16_t putReturnDelayTime = (currentReturnDelayTime + 256) / 2; assertEqual(dynamixel.setReturnDelayTime(servoId,putReturnDelayTime),DynamixelBus::kOk); //Serial.print(""put return delay time: ""); //Serial.println(putReturnDelayTime); uint16_t getReturnDelayTime = -1; assertEqual(dynamixel.getReturnDelayTime(servoId,getReturnDelayTime),DynamixelBus::kOk); //Serial.print(""get return delay time: ""); //Serial.println(getReturnDelayTime); assertTrue(putReturnDelayTime == getReturnDelayTime); assertEqual(dynamixel.setReturnDelayTime(servoId,currentReturnDelayTime),DynamixelBus::kOk); } #endif #if TEST_ANGLE_LIMITS == TRUE test(AngleLimits) { uint16_t currentMinAngleLimit = 0; uint16_t currentMaxAngleLimit = 0; assertEqual(dynamixel.getAngleLimits(servoId,currentMinAngleLimit,currentMaxAngleLimit),DynamixelBus::kOk); uint16_t offset = (currentMaxAngleLimit - currentMinAngleLimit) / 3; uint16_t putMinAngleLimit = currentMinAngleLimit + offset; uint16_t putMaxAngleLimit = currentMaxAngleLimit - offset; assertEqual(dynamixel.setAngleLimits(servoId,putMinAngleLimit,putMaxAngleLimit),DynamixelBus::kOk); uint16_t getMinAngleLimit = 0; uint16_t getMaxAngleLimit = 0; delay(18); assertEqual(dynamixel.getAngleLimits(servoId,getMinAngleLimit,getMaxAngleLimit),DynamixelBus::kOk); assertTrue(getMinAngleLimit == putMinAngleLimit); assertTrue(getMaxAngleLimit == putMaxAngleLimit); assertEqual(dynamixel.setAngleLimits(servoId,currentMinAngleLimit,currentMaxAngleLimit),DynamixelBus::kOk); } #endif #if TEST_TEMPERATURE_LIMIT == TRUE test(TemperatureLimit) { uint8_t currentTemperatureLimit = 0; assertEqual(dynamixel.getTemperatureLimit(servoId,currentTemperatureLimit),DynamixelBus::kOk); // This value will probaby trigger the temperature limit alarms if enabled uint8_t putTemperatureLimit = currentTemperatureLimit / 2; assertEqual(dynamixel.setTemperatureLimit(servoId,putTemperatureLimit),DynamixelBus::kOk); uint8_t getTemperatureLimit = 0; assertEqual(dynamixel.getTemperatureLimit(servoId,getTemperatureLimit),DynamixelBus::kOk); assertEqual(putTemperatureLimit,getTemperatureLimit); assertEqual(dynamixel.setTemperatureLimit(servoId,currentTemperatureLimit),DynamixelBus::kOk); } #endif #if TEST_VOLTAGE_LIMITS == TRUE test(VoltageLimits) { uint16_t currentMinVoltageLimit = 0; uint16_t currentMaxVoltageLimit = 0; assertEqual(dynamixel.getVoltageLimits(servoId,currentMinVoltageLimit,currentMaxVoltageLimit),DynamixelBus::kOk); uint16_t offset = (currentMaxVoltageLimit - currentMinVoltageLimit) / 3; uint16_t putMinVoltageLimit = ((currentMinVoltageLimit + offset) / 100) * 100; uint16_t putMaxVoltageLimit = ((currentMaxVoltageLimit - offset) / 100) * 100; assertEqual(dynamixel.setVoltageLimits(servoId,putMinVoltageLimit,putMaxVoltageLimit),DynamixelBus::kOk); uint16_t getMinVoltageLimit = 0; uint16_t getMaxVoltageLimit = 0; assertEqual(dynamixel.getVoltageLimits(servoId,getMinVoltageLimit,getMaxVoltageLimit),DynamixelBus::kOk); assertEqual(putMinVoltageLimit,getMinVoltageLimit); assertEqual(putMaxVoltageLimit,getMaxVoltageLimit); assertEqual(dynamixel.setVoltageLimits(servoId,DEFAULT_MIN_VOLTAGE,DEFAULT_MAX_VOLTAGE),DynamixelBus::kOk); } #endif #if TEST_INITIAL_TORQUE_LIMIT == TRUE test(InitialTorqueLimit) { uint16_t currentInitialTorqueLimit = 0; assertEqual(dynamixel.getInitialTorqueLimit(servoId,currentInitialTorqueLimit),DynamixelBus::kOk); uint16_t putInitialTorquLimit = currentInitialTorqueLimit / 2; assertEqual(dynamixel.setInitialTorqueLimit(servoId,putInitialTorquLimit),DynamixelBus::kOk); uint16_t getInitialTorquLimit = 0; assertEqual(dynamixel.getInitialTorqueLimit(servoId,getInitialTorquLimit),DynamixelBus::kOk); assertEqual(putInitialTorquLimit,getInitialTorquLimit); assertEqual(dynamixel.setInitialTorqueLimit(servoId,currentInitialTorqueLimit),DynamixelBus::kOk); } #endif #if TEST_STATUS_RETURN_LEVEL == TRUE test(StatusReturnLevel) { uint8_t error = 0; uint8_t currentStatusReturnLevel = DynamixelBus::kRespondToNone; uint8_t putStatusReturnLevel = DynamixelBus::kRespondToRead; uint8_t getStatusReturnLevel = DynamixelBus::kRespondToNone; assertEqual(dynamixel.getStatusReturnLevel(servoId,currentStatusReturnLevel),DynamixelBus::kOk); assertEqual(dynamixel.setStatusReturnLevel(servoId,putStatusReturnLevel),DynamixelBus::kOk); assertEqual(dynamixel.getStatusReturnLevel(servoId,getStatusReturnLevel),DynamixelBus::kOk); assertEqual(putStatusReturnLevel,getStatusReturnLevel); putStatusReturnLevel = DynamixelBus::kRespondToAll; getStatusReturnLevel = DynamixelBus::kRespondToNone; assertEqual(dynamixel.setStatusReturnLevel(servoId,currentStatusReturnLevel),DynamixelBus::kOk); assertEqual(dynamixel.getStatusReturnLevel(servoId,getStatusReturnLevel),DynamixelBus::kOk); assertEqual(getStatusReturnLevel,currentStatusReturnLevel); } #endif #if TEST_ALARM_LED == TRUE test(AlarmLed) { uint8_t currentAlarmLed = 0; uint8_t putAlarmLed = 0x7F; assertEqual(dynamixel.getAlarmLedTriggers(servoId,currentAlarmLed),DynamixelBus::kOk); assertEqual(dynamixel.setAlarmLedTriggers(servoId,putAlarmLed),DynamixelBus::kOk); uint8_t getAlarmLed = 0; assertEqual(dynamixel.getAlarmLedTriggers(servoId,getAlarmLed),DynamixelBus::kOk); assertEqual(putAlarmLed,getAlarmLed); assertEqual(dynamixel.setAlarmLedTriggers(servoId,currentAlarmLed),DynamixelBus::kOk); } #endif #if TEST_ALARM_SHUTDOWN == TRUE test(AlarmShutdown) { uint8_t currentAlarmShutdown = 0; uint8_t putAlarmShutdown = 0x7F; assertEqual(dynamixel.getAlarmShutdownTriggers(servoId,currentAlarmShutdown),DynamixelBus::kOk); assertEqual(dynamixel.setAlarmShutdownTriggers(servoId,putAlarmAlarmShutdown),DynamixelBus::kOk); uint8_t getAlarmShutdown = 0; assertEqual(dynamixel.getAlarmShutdownTriggers(servoId,getAlarmShutdown),DynamixelBus::kOk); assertEqual(putAlarmShutdown,getAlarmShutdown); assertEqual(dynamixel.setAlarmShutdownTriggers(servoId,currentAlarmShutdown),DynamixelBus::kOk); } #endif #if TEST_TORQUE_ENABLE == TRUE test(TorqueEnable) { assertEqual(dynamixel.setTorqueEnable(servoId,false),DynamixelBus::kOk); bool getTorqueEnable = true; assertEqual(dynamixel.getTorqueEnable(servoId,getTorqueEnable),DynamixelBus::kOk); assertTrue(getTorqueEnable); assertEqual(dynamixel.setTorqueEnable(servoId,true),DynamixelBus::kOk); } #endif #if TEST_LED == TRUE test(Led) { bool currentLed = false; assertEqual(dynamixel.getLed(servoId,currentLed), DynamixelBus::kOk); for (size_t i=0; i < 10; i++) { assertEqual(dynamixel.setLed(servoId,i & 0x1), DynamixelBus::kOk); delay(100); } assertEqual(dynamixel.setLed(servoId,!currentLed), DynamixelBus::kOk); bool getLed = false; assertEqual(dynamixel.getLed(servoId,getLed), DynamixelBus::kOk); assertTrue(currentLed != getLed); assertEqual(dynamixel.setLed(servoId,currentLed), DynamixelBus::kOk); } #endif #if TEST_COMPLIANCE_MARGINS == TRUE test(ComplianceMargins) { uint8_t currentCWComplianceMargin = 0; uint8_t currentCCWComplianceMargin = 0; assertEqual(dynamixel.getComplianceMargins(servoId,currentCWComplianceMargin,currentCCWComplianceMargin),DynamixelBus::kOk); uint8_t putCWComplianceMargin = 24; uint8_t putCCWComplianceMargin = 12; assertEqual(dynamixel.setComplianceMargins(servoId,putCWComplianceMargin,putCCWComplianceMargin),DynamixelBus::kOk); assertEqual(dynamixel.setTorqueLimit(servoId,0x3FF),DynamixelBus::kOk); assertEqual(dynamixel.setGoalSpeed(servoId,0x3FF),DynamixelBus::kOk); assertEqual(dynamixel.setPunch(servoId,0xFF),DynamixelBus::kOk); assertEqual(dynamixel.setGoalPosition(servoId,DEFAULT_GOAL_POSITION),DynamixelBus::kOk); delay(100); bool isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } uint16_t targetPosition = servoMinAngle; // + putCWComplianceMargin; assertEqual(dynamixel.setGoalPosition(servoId,targetPosition),DynamixelBus::kOk); delay(100); isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } uint16_t actualPosition = 0; assertEqual(dynamixel.getPresentPosition(servoId,actualPosition),DynamixelBus::kOk); int offset = actualPosition - targetPosition; offset = abs(offset); assertLessOrEqual(offset,putCWComplianceMargin); targetPosition = servoMaxAngle;// - putCCWComplianceMargin; assertEqual(dynamixel.setGoalPosition(servoId,targetPosition),DynamixelBus::kOk); delay(100); isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } assertEqual(dynamixel.getPresentPosition(servoId,actualPosition),DynamixelBus::kOk); offset = actualPosition - targetPosition; offset = abs(offset); assertLessOrEqual(offset,putCCWComplianceMargin); assertEqual(dynamixel.setTorqueLimit(servoId,DEFAULT_TORQUE_LIMIT),DynamixelBus::kOk); assertEqual(dynamixel.setGoalSpeed(servoId,DEFAULT_GOAL_SPEED),DynamixelBus::kOk); assertEqual(dynamixel.setGoalPosition(servoId,DEFAULT_GOAL_POSITION),DynamixelBus::kOk); assertEqual(dynamixel.setPunch(servoId,DEFAULT_PUNCH),DynamixelBus::kOk); delay(100); isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } assertEqual(dynamixel.setComplianceMargins(servoId,currentCWComplianceMargin,currentCCWComplianceMargin),DynamixelBus::kOk); } #endif #if TEST_COMPLIANCE_SLOPES == TRUE test(ComplianceSlopes) { uint8_t currentCWComplianceSlope = 0; uint8_t currentCCWComplianceSlope = 0; assertEqual(dynamixel.getComplianceSlopes(servoId,currentCWComplianceSlope,currentCCWComplianceSlope),DynamixelBus::kOk); uint8_t putCWComplianceSlope = 0xFE; uint8_t putCCWComplianceSlope = 0xFE; assertEqual(dynamixel.setComplianceSlopes(servoId,putCWComplianceSlope,putCCWComplianceSlope),DynamixelBus::kOk); uint8_t getCWComplianceSlope = 0x0; uint8_t getCCWComplianceSlope = 0x0; assertEqual(dynamixel.getComplianceSlopes(servoId,getCWComplianceSlope,getCCWComplianceSlope),DynamixelBus::kOk); assertEqual(putCWComplianceSlope,getCWComplianceSlope); assertEqual(putCCWComplianceSlope,getCCWComplianceSlope); assertEqual(dynamixel.setTorqueLimit(servoId,0x3FF),DynamixelBus::kOk); assertEqual(dynamixel.setGoalSpeed(servoId,0x3FF),DynamixelBus::kOk); assertEqual(dynamixel.setGoalPosition(servoId,DEFAULT_GOAL_POSITION),DynamixelBus::kOk); delay(100); bool isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } uint16_t targetPosition = servoMinAngle; assertEqual(dynamixel.setGoalPosition(servoId,targetPosition),DynamixelBus::kOk); delay(100); isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } targetPosition = servoMaxAngle; assertEqual(dynamixel.setGoalPosition(servoId,servoMaxAngle),DynamixelBus::kOk); delay(100); isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } assertEqual(dynamixel.setTorqueLimit(servoId,DEFAULT_TORQUE_LIMIT),DynamixelBus::kOk); assertEqual(dynamixel.setGoalSpeed(servoId,DEFAULT_GOAL_SPEED),DynamixelBus::kOk); assertEqual(dynamixel.setGoalPosition(servoId,DEFAULT_GOAL_POSITION),DynamixelBus::kOk); delay(100); isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } assertEqual(dynamixel.setComplianceSlopes(servoId,currentCWComplianceSlope,currentCCWComplianceSlope),DynamixelBus::kOk); } #endif #if TEST_GOAL_POSITION == TRUE test(GoalPosition) { uint16_t putPosition = servoMinAngle; uint16_t getPosition = 0; if (putPosition < servoMinAngle) putPosition = servoMinAngle; else if (putPosition > servoMaxAngle) putPosition = servoMaxAngle; assertEqual(dynamixel.setGoalPosition(servoId,putPosition),DynamixelBus::kOk); delay(100); bool isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } assertEqual(dynamixel.getGoalPosition(servoId,getPosition),DynamixelBus::kOk); assertEqual(putPosition,getPosition); assertEqual(dynamixel.setGoalPosition(servoId,512),DynamixelBus::kOk); delay(100); isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } } #endif #if TEST_GOAL_SPEED == TRUE test(GoalSpeed) { uint16_t putSpeed = millis() & 0x3FF; uint16_t getSpeed = 0; assertEqual(dynamixel.setGoalSpeed(servoId,putSpeed),DynamixelBus::kOk); assertEqual(dynamixel.getGoalSpeed(servoId,getSpeed),DynamixelBus::kOk); assertEqual(putSpeed,getSpeed); } #endif #if TEST_TORQUE_LIMIT == TRUE test(TorqueLimit) { uint16_t currentTorqueLimit = 0; assertEqual(dynamixel.getTorqueLimit(servoId,currentTorqueLimit),DynamixelBus::kOk); uint16_t putTorquLimit = currentTorqueLimit / 2; assertEqual(dynamixel.setTorqueLimit(servoId,putTorquLimit),DynamixelBus::kOk); uint16_t getTorquLimit = 0; assertEqual(dynamixel.getTorqueLimit(servoId,getTorquLimit),DynamixelBus::kOk); assertEqual(putTorquLimit,getTorquLimit); assertEqual(dynamixel.setTorqueLimit(servoId,currentTorqueLimit),DynamixelBus::kOk); } #endif #if TEST_PRESENT_STATE == TRUE test(PresentState) { uint16_t servoPresentPosition = 0; uint16_t servoPresentSpeed = 0; uint16_t servoPresentLoad = 0; uint8_t servoPresentLoadDirection = 0; uint16_t servoPresentVoltage = 0; uint8_t servoPresentTemperature = 0; assertEqual(dynamixel.getPresentPosition(servoId,servoPresentPosition),DynamixelBus::kOk); assertEqual(dynamixel.getPresentSpeed(servoId,servoPresentSpeed),DynamixelBus::kOk); assertEqual(dynamixel.getPresentLoad(servoId,servoPresentLoadDirection,servoPresentLoad),DynamixelBus::kOk); assertEqual(dynamixel.getPresentVoltage(servoId,servoPresentVoltage),DynamixelBus::kOk); assertEqual(dynamixel.getPresentTemperature(servoId,servoPresentTemperature),DynamixelBus::kOk); } #endif #if TEST_REGISTERED_INSTRUCTION == TRUE test(RegisteredInstruction) { fail(); } #endif #if TEST_MOVING == TRUE test(Moving) { bool isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } assertEqual(dynamixel.setGoalPosition(servoId,DEFAULT_MIN_ANGLE),DynamixelBus::kOk); delay(10); assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); assertTrue(isMoving); delay(100); while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } assertEqual(dynamixel.setGoalPosition(servoId,DEFAULT_GOAL_POSITION),DynamixelBus::kOk); isMoving = true; while(isMoving) { assertEqual(dynamixel.getMoving(servoId,isMoving),DynamixelBus::kOk); delay(100); } } #endif #if TEST_LOCK == TRUE test(Lock) { } #endif #if TEST_PUNCH == TRUE test(Punch) { uint16_t currentPunch = 0; assertEqual(dynamixel.getPunch(servoId,currentPunch),DynamixelBus::kOk); uint16_t putPunch = DEFAULT_PUNCH / 2; assertEqual(dynamixel.setPunch(servoId,putPunch),DynamixelBus::kOk); uint16_t getPunch = 0; assertEqual(dynamixel.getPunch(servoId,getPunch),DynamixelBus::kOk); assertEqual(putPunch,getPunch); assertEqual(dynamixel.setPunch(servoId,DEFAULT_PUNCH),DynamixelBus::kOk); } #endif void loop() { if (servoId != 0) Test::run(); } ",8284,False,1802.1388738441176,median "// Copyright (c) 2013 The Chromium 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 ""base/bind.h"" #include ""base/files/file_path.h"" #include ""base/files/file_util.h"" #include ""base/files/scoped_temp_dir.h"" #include ""base/json/json_reader.h"" #include ""base/message_loop/message_loop.h"" #include ""base/run_loop.h"" #include ""base/strings/string_number_conversions.h"" #include ""base/values.h"" #include ""google_apis/drive/drive_api_parser.h"" #include ""google_apis/drive/drive_api_requests.h"" #include ""google_apis/drive/drive_api_url_generator.h"" #include ""google_apis/drive/dummy_auth_service.h"" #include ""google_apis/drive/request_sender.h"" #include ""google_apis/drive/test_util.h"" #include ""net/test/embedded_test_server/embedded_test_server.h"" #include ""net/test/embedded_test_server/http_request.h"" #include ""net/test/embedded_test_server/http_response.h"" #include ""net/url_request/url_request_test_util.h"" #include ""testing/gtest/include/gtest/gtest.h"" namespace google_apis { namespace { const char kTestETag[] = ""test_etag""; const char kTestUserAgent[] = ""test-user-agent""; const char kTestChildrenResponse[] = ""{\\n"" ""\\""kind\\"": \\""drive#childReference\\"",\\n"" ""\\""id\\"": \\""resource_id\\"",\\n"" ""\\""selfLink\\"": \\""self_link\\"",\\n"" ""\\""childLink\\"": \\""child_link\\"",\\n"" ""}\\n""; const char kTestPermissionResponse[] = ""{\\n"" ""\\""kind\\"": \\""drive#permission\\"",\\n"" ""\\""id\\"": \\""resource_id\\"",\\n"" ""\\""selfLink\\"": \\""self_link\\"",\\n"" ""}\\n""; const char kTestUploadExistingFilePath[] = ""/upload/existingfile/path""; const char kTestUploadNewFilePath[] = ""/upload/newfile/path""; const char kTestDownloadPathPrefix[] = ""/download/""; // Used as a GetContentCallback. void AppendContent(std::string* out, GDataErrorCode error, scoped_ptr content) { EXPECT_EQ(HTTP_SUCCESS, error); out->append(*content); } } // namespace class DriveApiRequestsTest : public testing::Test { public: DriveApiRequestsTest() { } virtual void SetUp() OVERRIDE { request_context_getter_ = new net::TestURLRequestContextGetter( message_loop_.message_loop_proxy()); request_sender_.reset(new RequestSender(new DummyAuthService, request_context_getter_.get(), message_loop_.message_loop_proxy(), kTestUserAgent)); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(test_server_.InitializeAndWaitUntilReady()); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleChildrenDeleteRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleDataFileRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleDeleteRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandlePreconditionFailedRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleResumeUploadRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleInitiateUploadRequest, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleContentResponse, base::Unretained(this))); test_server_.RegisterRequestHandler( base::Bind(&DriveApiRequestsTest::HandleDownloadRequest, base::Unretained(this))); GURL test_base_url = test_util::GetBaseUrlForTesting(test_server_.port()); url_generator_.reset(new DriveApiUrlGenerator( test_base_url, test_base_url.Resolve(kTestDownloadPathPrefix))); // Reset the server's expected behavior just in case. ResetExpectedResponse(); received_bytes_ = 0; content_length_ = 0; } base::MessageLoopForIO message_loop_; // Test server needs IO thread. net::test_server::EmbeddedTestServer test_server_; scoped_ptr request_sender_; scoped_ptr url_generator_; scoped_refptr request_context_getter_; base::ScopedTempDir temp_dir_; // This is a path to the file which contains expected response from // the server. See also HandleDataFileRequest below. base::FilePath expected_data_file_path_; // This is a path string in the expected response header from the server // for initiating file uploading. std::string expected_upload_path_; // This is a path to the file which contains expected response for // PRECONDITION_FAILED response. base::FilePath expected_precondition_failed_file_path_; // These are content and its type in the expected response from the server. // See also HandleContentResponse below. std::string expected_content_type_; std::string expected_content_; // The incoming HTTP request is saved so tests can verify the request // parameters like HTTP method (ex. some requests should use DELETE // instead of GET). net::test_server::HttpRequest http_request_; private: void ResetExpectedResponse() { expected_data_file_path_.clear(); expected_upload_path_.clear(); expected_content_type_.clear(); expected_content_.clear(); } // For ""Children: delete"" request, the server will return ""204 No Content"" // response meaning ""success"". scoped_ptr HandleChildrenDeleteRequest( const net::test_server::HttpRequest& request) { if (request.method != net::test_server::METHOD_DELETE || request.relative_url.find(""/children/"") == string::npos) { // The request is not the ""Children: delete"" request. Delegate the // processing to the next handler. return scoped_ptr(); } http_request_ = request; // Return the response with just ""204 No Content"" status code. scoped_ptr http_response( new net::test_server::BasicHttpResponse); http_response->set_code(net::HTTP_NO_CONTENT); return http_response.PassAs(); } // Reads the data file of |expected_data_file_path_| and returns its content // for the request. // To use this method, it is necessary to set |expected_data_file_path_| // to the appropriate file path before sending the request to the server. scoped_ptr HandleDataFileRequest( const net::test_server::HttpRequest& request) { if (expected_data_file_path_.empty()) { // The file is not specified. Delegate the processing to the next // handler. return scoped_ptr(); } http_request_ = request; // Return the response from the data file. return test_util::CreateHttpResponseFromFile( expected_data_file_path_).PassAs(); } // Deletes the resource and returns no content with HTTP_NO_CONTENT status // code. scoped_ptr HandleDeleteRequest( const net::test_server::HttpRequest& request) { if (request.method != net::test_server::METHOD_DELETE || request.relative_url.find(""/files/"") == string::npos) { // The file is not file deletion request. Delegate the processing to the // next handler. return scoped_ptr(); } http_request_ = request; scoped_ptr response( new net::test_server::BasicHttpResponse); response->set_code(net::HTTP_NO_CONTENT); return response.PassAs(); } // Returns PRECONDITION_FAILED response for ETag mismatching with error JSON // content specified by |expected_precondition_failed_file_path_|. // To use this method, it is necessary to set the variable to the appropriate // file path before sending the request to the server. scoped_ptr HandlePreconditionFailedRequest( const net::test_server::HttpRequest& request) { if (expected_precondition_failed_file_path_.empty()) { // The file is not specified. Delegate the process to the next handler. return scoped_ptr(); } http_request_ = request; scoped_ptr response( new net::test_server::BasicHttpResponse); response->set_code(net::HTTP_PRECONDITION_FAILED); std::string content; if (base::ReadFileToString(expected_precondition_failed_file_path_, &content)) { response->set_content(content); response->set_content_type(""application/json""); } return response.PassAs(); } // Returns the response based on set expected upload url. // The response contains the url in its ""Location: "" header. Also, it doesn't // have any content. // To use this method, it is necessary to set |expected_upload_path_| // to the string representation of the url to be returned. scoped_ptr HandleInitiateUploadRequest( const net::test_server::HttpRequest& request) { if (request.relative_url == expected_upload_path_ || expected_upload_path_.empty()) { // The request is for resume uploading or the expected upload url is not // set. Delegate the processing to the next handler. return scoped_ptr(); } http_request_ = request; scoped_ptr response( new net::test_server::BasicHttpResponse); // Check if the X-Upload-Content-Length is present. If yes, store the // length of the file. std::map::const_iterator found = request.headers.find(""X-Upload-Content-Length""); if (found == request.headers.end() || !base::StringToInt64(found->second, &content_length_)) { return scoped_ptr(); } received_bytes_ = 0; response->set_code(net::HTTP_OK); response->AddCustomHeader( ""Location"", test_server_.base_url().Resolve(expected_upload_path_).spec()); return response.PassAs(); } scoped_ptr HandleResumeUploadRequest( const net::test_server::HttpRequest& request) { if (request.relative_url != expected_upload_path_) { // The request path is different from the expected path for uploading. // Delegate the processing to the next handler. return scoped_ptr(); } http_request_ = request; if (!request.content.empty()) { std::map::const_iterator iter = request.headers.find(""Content-Range""); if (iter == request.headers.end()) { // The range must be set. return scoped_ptr(); } int64 length = 0; int64 start_position = 0; int64 end_position = 0; if (!test_util::ParseContentRangeHeader( iter->second, &start_position, &end_position, &length)) { // Invalid ""Content-Range"" value. return scoped_ptr(); } EXPECT_EQ(start_position, received_bytes_); EXPECT_EQ(length, content_length_); // end_position is inclusive, but so +1 to change the range to byte size. received_bytes_ = end_position + 1; } if (received_bytes_ < content_length_) { scoped_ptr response( new net::test_server::BasicHttpResponse); // Set RESUME INCOMPLETE (308) status code. response->set_code(static_cast(308)); // Add Range header to the response, based on the values of // Content-Range header in the request. // The header is annotated only when at least one byte is received. if (received_bytes_ > 0) { response->AddCustomHeader( ""Range"", ""bytes=0-"" + base::Int64ToString(received_bytes_ - 1)); } return response.PassAs(); } // All bytes are received. Return the ""success"" response with the file's // (dummy) metadata. scoped_ptr response = test_util::CreateHttpResponseFromFile( test_util::GetTestFilePath(""drive/file_entry.json"")); // The response code is CREATED if it is new file uploading. if (http_request_.relative_url == kTestUploadNewFilePath) { response->set_code(net::HTTP_CREATED); } return response.PassAs(); } // Returns the response based on set expected content and its type. // To use this method, both |expected_content_type_| and |expected_content_| // must be set in advance. scoped_ptr HandleContentResponse( const net::test_server::HttpRequest& request) { if (expected_content_type_.empty() || expected_content_.empty()) { // Expected content is not set. Delegate the processing to the next // handler. return scoped_ptr(); } http_request_ = request; scoped_ptr response( new net::test_server::BasicHttpResponse); response->set_code(net::HTTP_OK); response->set_content_type(expected_content_type_); response->set_content(expected_content_); return response.PassAs(); } // Handles a request for downloading a file. scoped_ptr HandleDownloadRequest( const net::test_server::HttpRequest& request) { http_request_ = request; const GURL absolute_url = test_server_.GetURL(request.relative_url); std::string id; if (!test_util::RemovePrefix(absolute_url.path(), kTestDownloadPathPrefix, &id)) { return scoped_ptr(); } // For testing, returns a text with |id| repeated 3 times. scoped_ptr response( new net::test_server::BasicHttpResponse); response->set_code(net::HTTP_OK); response->set_content(id + id + id); response->set_content_type(""text/plain""); return response.PassAs(); } // These are for the current upload file status. int64 received_bytes_; int64 content_length_; }; TEST_F(DriveApiRequestsTest, DriveApiDataRequest_Fields) { // Make sure that ""fields"" query param is supported by using its subclass, // AboutGetRequest. // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/about.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr about_resource; { base::RunLoop run_loop; drive::AboutGetRequest* request = new drive::AboutGetRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &about_resource))); request->set_fields( ""kind,quotaBytesTotal,quotaBytesUsed,largestChangeId,rootFolderId""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/about?"" ""fields=kind%2CquotaBytesTotal%2CquotaBytesUsed%2C"" ""largestChangeId%2CrootFolderId"", http_request_.relative_url); scoped_ptr expected( AboutResource::CreateFrom( *test_util::LoadJSONFile(""drive/about.json""))); ASSERT_TRUE(about_resource.get()); EXPECT_EQ(expected->largest_change_id(), about_resource->largest_change_id()); EXPECT_EQ(expected->quota_bytes_total(), about_resource->quota_bytes_total()); EXPECT_EQ(expected->quota_bytes_used(), about_resource->quota_bytes_used()); EXPECT_EQ(expected->root_folder_id(), about_resource->root_folder_id()); } TEST_F(DriveApiRequestsTest, FilesInsertRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; const base::Time::Exploded kLastViewedByMeDate = {2013, 7, 0, 19, 15, 59, 13, 123}; // Set an expected data file containing the directory's entry data. expected_data_file_path_ = test_util::GetTestFilePath(""drive/directory_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; // Create ""new directory"" in the root directory. { base::RunLoop run_loop; drive::FilesInsertRequest* request = new drive::FilesInsertRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_last_viewed_by_me_date( base::Time::FromUTCExploded(kLastViewedByMeDate)); request->set_mime_type(""application/vnd.google-apps.folder""); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->add_parent(""root""); request->set_title(""new directory""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""lastViewedByMeDate\\"":\\""2013-07-19T15:59:13.123Z\\"","" ""\\""mimeType\\"":\\""application/vnd.google-apps.folder\\"","" ""\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""root\\""}],"" ""\\""title\\"":\\""new directory\\""}"", http_request_.content); scoped_ptr expected( FileResource::CreateFrom( *test_util::LoadJSONFile(""drive/directory_entry.json""))); // Sanity check. ASSERT_TRUE(file_resource.get()); EXPECT_EQ(expected->file_id(), file_resource->file_id()); EXPECT_EQ(expected->title(), file_resource->title()); EXPECT_EQ(expected->mime_type(), file_resource->mime_type()); EXPECT_EQ(expected->parents().size(), file_resource->parents().size()); } TEST_F(DriveApiRequestsTest, FilesPatchRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; const base::Time::Exploded kLastViewedByMeDate = {2013, 7, 0, 19, 15, 59, 13, 123}; // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath(""drive/file_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; { base::RunLoop run_loop; drive::FilesPatchRequest* request = new drive::FilesPatchRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_file_id(""resource_id""); request->set_set_modified_date(true); request->set_update_viewed_date(false); request->set_title(""new title""); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->set_last_viewed_by_me_date( base::Time::FromUTCExploded(kLastViewedByMeDate)); request->add_parent(""parent_resource_id""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_PATCH, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id"" ""?setModifiedDate=true&updateViewedDate=false"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""lastViewedByMeDate\\"":\\""2013-07-19T15:59:13.123Z\\"","" ""\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""parent_resource_id\\""}],"" ""\\""title\\"":\\""new title\\""}"", http_request_.content); EXPECT_TRUE(file_resource); } TEST_F(DriveApiRequestsTest, AboutGetRequest_ValidJson) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/about.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr about_resource; { base::RunLoop run_loop; drive::AboutGetRequest* request = new drive::AboutGetRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &about_resource))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/about"", http_request_.relative_url); scoped_ptr expected( AboutResource::CreateFrom( *test_util::LoadJSONFile(""drive/about.json""))); ASSERT_TRUE(about_resource.get()); EXPECT_EQ(expected->largest_change_id(), about_resource->largest_change_id()); EXPECT_EQ(expected->quota_bytes_total(), about_resource->quota_bytes_total()); EXPECT_EQ(expected->quota_bytes_used(), about_resource->quota_bytes_used()); EXPECT_EQ(expected->root_folder_id(), about_resource->root_folder_id()); } TEST_F(DriveApiRequestsTest, AboutGetRequest_InvalidJson) { // Set an expected data file containing invalid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/testfile.txt""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr about_resource; { base::RunLoop run_loop; drive::AboutGetRequest* request = new drive::AboutGetRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &about_resource))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } // ""parse error"" should be returned, and the about resource should be NULL. EXPECT_EQ(GDATA_PARSE_ERROR, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/about"", http_request_.relative_url); EXPECT_FALSE(about_resource); } TEST_F(DriveApiRequestsTest, AppsListRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/applist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr app_list; { base::RunLoop run_loop; drive::AppsListRequest* request = new drive::AppsListRequest( request_sender_.get(), *url_generator_, false, // use_internal_endpoint test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &app_list))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/apps"", http_request_.relative_url); EXPECT_TRUE(app_list); } TEST_F(DriveApiRequestsTest, ChangesListRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/changelist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr result; { base::RunLoop run_loop; drive::ChangesListRequest* request = new drive::ChangesListRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &result))); request->set_include_deleted(true); request->set_start_change_id(100); request->set_max_results(500); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/changes?maxResults=500&startChangeId=100"", http_request_.relative_url); EXPECT_TRUE(result); } TEST_F(DriveApiRequestsTest, ChangesListNextPageRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/changelist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr result; { base::RunLoop run_loop; drive::ChangesListNextPageRequest* request = new drive::ChangesListNextPageRequest( request_sender_.get(), test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &result))); request->set_next_link(test_server_.GetURL(""/continue/get/change/list"")); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/continue/get/change/list"", http_request_.relative_url); EXPECT_TRUE(result); } TEST_F(DriveApiRequestsTest, FilesCopyRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; // Set an expected data file containing the dummy file entry data. // It'd be returned if we copy a file. expected_data_file_path_ = test_util::GetTestFilePath(""drive/file_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; // Copy the file to a new file named ""new title"". { base::RunLoop run_loop; drive::FilesCopyRequest* request = new drive::FilesCopyRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_file_id(""resource_id""); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->add_parent(""parent_resource_id""); request->set_title(""new title""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id/copy"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ( ""{\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""parent_resource_id\\""}],\\""title\\"":\\""new title\\""}"", http_request_.content); EXPECT_TRUE(file_resource); } TEST_F(DriveApiRequestsTest, FilesCopyRequest_EmptyParentResourceId) { // Set an expected data file containing the dummy file entry data. // It'd be returned if we copy a file. expected_data_file_path_ = test_util::GetTestFilePath(""drive/file_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; // Copy the file to a new file named ""new title"". { base::RunLoop run_loop; drive::FilesCopyRequest* request = new drive::FilesCopyRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_file_id(""resource_id""); request->set_title(""new title""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id/copy"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""title\\"":\\""new title\\""}"", http_request_.content); EXPECT_TRUE(file_resource); } TEST_F(DriveApiRequestsTest, FilesListRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/filelist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr result; { base::RunLoop run_loop; drive::FilesListRequest* request = new drive::FilesListRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &result))); request->set_max_results(50); request->set_q(""\\""abcde\\"" in parents""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/drive/v2/files?maxResults=50&q=%22abcde%22+in+parents"", http_request_.relative_url); EXPECT_TRUE(result); } TEST_F(DriveApiRequestsTest, FilesListNextPageRequest) { // Set an expected data file containing valid result. expected_data_file_path_ = test_util::GetTestFilePath( ""drive/filelist.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr result; { base::RunLoop run_loop; drive::FilesListNextPageRequest* request = new drive::FilesListNextPageRequest( request_sender_.get(), test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &result))); request->set_next_link(test_server_.GetURL(""/continue/get/file/list"")); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(""/continue/get/file/list"", http_request_.relative_url); EXPECT_TRUE(result); } TEST_F(DriveApiRequestsTest, FilesDeleteRequest) { GDataErrorCode error = GDATA_OTHER_ERROR; // Delete a resource with the given resource id. { base::RunLoop run_loop; drive::FilesDeleteRequest* request = new drive::FilesDeleteRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_file_id(""resource_id""); request->set_etag(kTestETag); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_NO_CONTENT, error); EXPECT_EQ(net::test_server::METHOD_DELETE, http_request_.method); EXPECT_EQ(kTestETag, http_request_.headers[""If-Match""]); EXPECT_EQ(""/drive/v2/files/resource_id"", http_request_.relative_url); EXPECT_FALSE(http_request_.has_content); } TEST_F(DriveApiRequestsTest, FilesTrashRequest) { // Set data for the expected result. Directory entry should be returned // if the trashing entry is a directory, so using it here should be fine. expected_data_file_path_ = test_util::GetTestFilePath(""drive/directory_entry.json""); GDataErrorCode error = GDATA_OTHER_ERROR; scoped_ptr file_resource; // Trash a resource with the given resource id. { base::RunLoop run_loop; drive::FilesTrashRequest* request = new drive::FilesTrashRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &file_resource))); request->set_file_id(""resource_id""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id/trash"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); } TEST_F(DriveApiRequestsTest, ChildrenInsertRequest) { // Set an expected data file containing the children entry. expected_content_type_ = ""application/json""; expected_content_ = kTestChildrenResponse; GDataErrorCode error = GDATA_OTHER_ERROR; // Add a resource with ""resource_id"" to a directory with // ""parent_resource_id"". { base::RunLoop run_loop; drive::ChildrenInsertRequest* request = new drive::ChildrenInsertRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_folder_id(""parent_resource_id""); request->set_id(""resource_id""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/parent_resource_id/children"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""id\\"":\\""resource_id\\""}"", http_request_.content); } TEST_F(DriveApiRequestsTest, ChildrenDeleteRequest) { GDataErrorCode error = GDATA_OTHER_ERROR; // Remove a resource with ""resource_id"" from a directory with // ""parent_resource_id"". { base::RunLoop run_loop; drive::ChildrenDeleteRequest* request = new drive::ChildrenDeleteRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_child_id(""resource_id""); request->set_folder_id(""parent_resource_id""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_NO_CONTENT, error); EXPECT_EQ(net::test_server::METHOD_DELETE, http_request_.method); EXPECT_EQ(""/drive/v2/files/parent_resource_id/children/resource_id"", http_request_.relative_url); EXPECT_FALSE(http_request_.has_content); } TEST_F(DriveApiRequestsTest, UploadNewFileRequest) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadNewFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with // ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadNewFileRequest* request = new drive::InitiateUploadNewFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""parent_resource_id"", // The resource id of the parent directory. ""new file title"", // The title of the file being uploaded. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadNewFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files?uploadType=resumable"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""parents\\"":[{"" ""\\""id\\"":\\""parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\"""" ""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position kTestContent.size(), // end_position (exclusive) kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes 0-"" + base::Int64ToString(kTestContent.size() - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_CREATED, response.code); // Because it's a new file // The start and end positions should be set to -1, if an upload is complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); } TEST_F(DriveApiRequestsTest, UploadNewEmptyFileRequest) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadNewFilePath; const char kTestContentType[] = ""text/plain""; const char kTestContent[] = """"; const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""empty_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadNewFileRequest* request = new drive::InitiateUploadNewFileRequest( request_sender_.get(), *url_generator_, kTestContentType, 0, ""parent_resource_id"", // The resource id of the parent directory. ""new file title"", // The title of the file being uploaded. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadNewFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(""0"", http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files?uploadType=resumable"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""parents\\"":[{"" ""\\""id\\"":\\""parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\"""" ""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position 0, // end_position (exclusive) 0, // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should NOT be added. EXPECT_EQ(0U, http_request_.headers.count(""Content-Range"")); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_CREATED, response.code); // Because it's a new file // The start and end positions should be set to -1, if an upload is complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); } TEST_F(DriveApiRequestsTest, UploadNewLargeFileRequest) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadNewFilePath; const char kTestContentType[] = ""text/plain""; const size_t kNumChunkBytes = 10; // Num bytes in a chunk. const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadNewFileRequest* request = new drive::InitiateUploadNewFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""parent_resource_id"", // The resource id of the parent directory. ""new file title"", // The title of the file being uploaded. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadNewFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files?uploadType=resumable"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""parents\\"":[{"" ""\\""id\\"":\\""parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\"""" ""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); // Before sending any data, check the current status. // This is an edge case test for GetUploadStatusRequest. { UploadRangeResponse response; scoped_ptr new_entry; // Check the response by GetUploadStatusRequest. { base::RunLoop run_loop; drive::GetUploadStatusRequest* get_upload_status_request = new drive::GetUploadStatusRequest( request_sender_.get(), upload_url, kTestContent.size(), test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry))); request_sender_->StartRequestWithRetry(get_upload_status_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes */"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Check the response. EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code); EXPECT_EQ(0, response.start_position_received); EXPECT_EQ(0, response.end_position_received); } // Upload the content to the upload URL. for (size_t start_position = 0; start_position < kTestContent.size(); start_position += kNumChunkBytes) { const std::string payload = kTestContent.substr( start_position, std::min(kNumChunkBytes, kTestContent.size() - start_position)); const size_t end_position = start_position + payload.size(); UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, start_position, end_position, kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes "" + base::Int64ToString(start_position) + ""-"" + base::Int64ToString(end_position - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(payload, http_request_.content); if (end_position == kTestContent.size()) { // Check the response. EXPECT_EQ(HTTP_CREATED, response.code); // Because it's a new file // The start and end positions should be set to -1, if an upload is // complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); break; } // Check the response. EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code); EXPECT_EQ(0, response.start_position_received); EXPECT_EQ(static_cast(end_position), response.end_position_received); // Check the response by GetUploadStatusRequest. { base::RunLoop run_loop; drive::GetUploadStatusRequest* get_upload_status_request = new drive::GetUploadStatusRequest( request_sender_.get(), upload_url, kTestContent.size(), test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry))); request_sender_->StartRequestWithRetry(get_upload_status_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes */"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Check the response. EXPECT_EQ(HTTP_RESUME_INCOMPLETE, response.code); EXPECT_EQ(0, response.start_position_received); EXPECT_EQ(static_cast(end_position), response.end_position_received); } } TEST_F(DriveApiRequestsTest, UploadNewFileWithMetadataRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; const base::Time::Exploded kLastViewedByMeDate = {2013, 7, 0, 19, 15, 59, 13, 123}; // Set an expected url for uploading. expected_upload_path_ = kTestUploadNewFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadNewFileRequest* request = new drive::InitiateUploadNewFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""parent_resource_id"", // The resource id of the parent directory. ""new file title"", // The title of the file being uploaded. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->set_last_viewed_by_me_date( base::Time::FromUTCExploded(kLastViewedByMeDate)); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadNewFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files?uploadType=resumable&setModifiedDate=true"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""lastViewedByMeDate\\"":\\""2013-07-19T15:59:13.123Z\\"","" ""\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); } TEST_F(DriveApiRequestsTest, UploadExistingFileRequest) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. std::string(), // No etag. test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(""*"", http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?uploadType=resumable"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position kTestContent.size(), // end_position (exclusive) kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes 0-"" + base::Int64ToString(kTestContent.size() - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_SUCCESS, response.code); // Because it's an existing file // The start and end positions should be set to -1, if an upload is complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); } TEST_F(DriveApiRequestsTest, UploadExistingFileRequestWithETag) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. kTestETag, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(kTestETag, http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?uploadType=resumable"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position kTestContent.size(), // end_position (exclusive) kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes 0-"" + base::Int64ToString(kTestContent.size() - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_SUCCESS, response.code); // Because it's an existing file // The start and end positions should be set to -1, if an upload is complete. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); } TEST_F(DriveApiRequestsTest, UploadExistingFileRequestWithETagConflicting) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; // If it turned out that the etag is conflicting, PRECONDITION_FAILED should // be returned. expected_precondition_failed_file_path_ = test_util::GetTestFilePath(""drive/error.json""); const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. ""Conflicting-etag"", test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_PRECONDITION, error); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(""Conflicting-etag"", http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?uploadType=resumable"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); } TEST_F(DriveApiRequestsTest, UploadExistingFileRequestWithETagConflictOnResumeUpload) { // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); const base::FilePath kTestFilePath = temp_dir_.path().AppendASCII(""upload_file.txt""); ASSERT_TRUE(test_util::WriteStringToFile(kTestFilePath, kTestContent)); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. kTestETag, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(kTestETag, http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?uploadType=resumable"", http_request_.relative_url); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(http_request_.content.empty()); // Set PRECONDITION_FAILED to the server. This is the emulation of the // confliction during uploading. expected_precondition_failed_file_path_ = test_util::GetTestFilePath(""drive/error.json""); // Upload the content to the upload URL. UploadRangeResponse response; scoped_ptr new_entry; { base::RunLoop run_loop; drive::ResumeUploadRequest* resume_request = new drive::ResumeUploadRequest( request_sender_.get(), upload_url, 0, // start_position kTestContent.size(), // end_position (exclusive) kTestContent.size(), // content_length, kTestContentType, kTestFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&response, &new_entry)), ProgressCallback()); request_sender_->StartRequestWithRetry(resume_request); run_loop.Run(); } // METHOD_PUT should be used to upload data. EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); // Request should go to the upload URL. EXPECT_EQ(upload_url.path(), http_request_.relative_url); // Content-Range header should be added. EXPECT_EQ(""bytes 0-"" + base::Int64ToString(kTestContent.size() - 1) + ""/"" + base::Int64ToString(kTestContent.size()), http_request_.headers[""Content-Range""]); // The upload content should be set in the HTTP request. EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(kTestContent, http_request_.content); // Check the response. EXPECT_EQ(HTTP_PRECONDITION, response.code); // The start and end positions should be set to -1 for error. EXPECT_EQ(-1, response.start_position_received); EXPECT_EQ(-1, response.end_position_received); // New entry should be NULL. EXPECT_FALSE(new_entry.get()); } TEST_F(DriveApiRequestsTest, UploadExistingFileWithMetadataRequest) { const base::Time::Exploded kModifiedDate = {2012, 7, 0, 19, 15, 59, 13, 123}; const base::Time::Exploded kLastViewedByMeDate = {2013, 7, 0, 19, 15, 59, 13, 123}; // Set an expected url for uploading. expected_upload_path_ = kTestUploadExistingFilePath; const char kTestContentType[] = ""text/plain""; const std::string kTestContent(100, 'a'); GDataErrorCode error = GDATA_OTHER_ERROR; GURL upload_url; // Initiate uploading a new file to the directory with ""parent_resource_id"". { base::RunLoop run_loop; drive::InitiateUploadExistingFileRequest* request = new drive::InitiateUploadExistingFileRequest( request_sender_.get(), *url_generator_, kTestContentType, kTestContent.size(), ""resource_id"", // The resource id of the file to be overwritten. kTestETag, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error, &upload_url))); request->set_parent_resource_id(""new_parent_resource_id""); request->set_title(""new file title""); request->set_modified_date(base::Time::FromUTCExploded(kModifiedDate)); request->set_last_viewed_by_me_date( base::Time::FromUTCExploded(kLastViewedByMeDate)); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(kTestUploadExistingFilePath, upload_url.path()); EXPECT_EQ(kTestContentType, http_request_.headers[""X-Upload-Content-Type""]); EXPECT_EQ(base::Int64ToString(kTestContent.size()), http_request_.headers[""X-Upload-Content-Length""]); EXPECT_EQ(kTestETag, http_request_.headers[""If-Match""]); EXPECT_EQ(net::test_server::METHOD_PUT, http_request_.method); EXPECT_EQ(""/upload/drive/v2/files/resource_id?"" ""uploadType=resumable&setModifiedDate=true"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); EXPECT_TRUE(http_request_.has_content); EXPECT_EQ(""{\\""lastViewedByMeDate\\"":\\""2013-07-19T15:59:13.123Z\\"","" ""\\""modifiedDate\\"":\\""2012-07-19T15:59:13.123Z\\"","" ""\\""parents\\"":[{\\""id\\"":\\""new_parent_resource_id\\"","" ""\\""kind\\"":\\""drive#fileLink\\""}],"" ""\\""title\\"":\\""new file title\\""}"", http_request_.content); } TEST_F(DriveApiRequestsTest, DownloadFileRequest) { const base::FilePath kDownloadedFilePath = temp_dir_.path().AppendASCII(""cache_file""); const std::string kTestId(""dummyId""); GDataErrorCode result_code = GDATA_OTHER_ERROR; base::FilePath temp_file; { base::RunLoop run_loop; drive::DownloadFileRequest* request = new drive::DownloadFileRequest( request_sender_.get(), *url_generator_, kTestId, kDownloadedFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&result_code, &temp_file)), GetContentCallback(), ProgressCallback()); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } std::string contents; base::ReadFileToString(temp_file, &contents); base::DeleteFile(temp_file, false); EXPECT_EQ(HTTP_SUCCESS, result_code); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(kTestDownloadPathPrefix + kTestId, http_request_.relative_url); EXPECT_EQ(kDownloadedFilePath, temp_file); const std::string expected_contents = kTestId + kTestId + kTestId; EXPECT_EQ(expected_contents, contents); } TEST_F(DriveApiRequestsTest, DownloadFileRequest_GetContentCallback) { const base::FilePath kDownloadedFilePath = temp_dir_.path().AppendASCII(""cache_file""); const std::string kTestId(""dummyId""); GDataErrorCode result_code = GDATA_OTHER_ERROR; base::FilePath temp_file; std::string contents; { base::RunLoop run_loop; drive::DownloadFileRequest* request = new drive::DownloadFileRequest( request_sender_.get(), *url_generator_, kTestId, kDownloadedFilePath, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&result_code, &temp_file)), base::Bind(&AppendContent, &contents), ProgressCallback()); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } base::DeleteFile(temp_file, false); EXPECT_EQ(HTTP_SUCCESS, result_code); EXPECT_EQ(net::test_server::METHOD_GET, http_request_.method); EXPECT_EQ(kTestDownloadPathPrefix + kTestId, http_request_.relative_url); EXPECT_EQ(kDownloadedFilePath, temp_file); const std::string expected_contents = kTestId + kTestId + kTestId; EXPECT_EQ(expected_contents, contents); } TEST_F(DriveApiRequestsTest, PermissionsInsertRequest) { expected_content_type_ = ""application/json""; expected_content_ = kTestPermissionResponse; GDataErrorCode error = GDATA_OTHER_ERROR; // Add comment permission to the user ""user@example.com"". { base::RunLoop run_loop; drive::PermissionsInsertRequest* request = new drive::PermissionsInsertRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_id(""resource_id""); request->set_role(drive::PERMISSION_ROLE_COMMENTER); request->set_type(drive::PERMISSION_TYPE_USER); request->set_value(""user@example.com""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id/permissions"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); scoped_ptr expected(base::JSONReader::Read( ""{\\""additionalRoles\\"":[\\""commenter\\""], \\""role\\"":\\""reader\\"", "" ""\\""type\\"":\\""user\\"",\\""value\\"":\\""user@example.com\\""}"")); ASSERT_TRUE(expected); scoped_ptr result(base::JSONReader::Read(http_request_.content)); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(base::Value::Equals(expected.get(), result.get())); // Add ""can edit"" permission to users in ""example.com"". error = GDATA_OTHER_ERROR; { base::RunLoop run_loop; drive::PermissionsInsertRequest* request = new drive::PermissionsInsertRequest( request_sender_.get(), *url_generator_, test_util::CreateQuitCallback( &run_loop, test_util::CreateCopyResultCallback(&error))); request->set_id(""resource_id2""); request->set_role(drive::PERMISSION_ROLE_WRITER); request->set_type(drive::PERMISSION_TYPE_DOMAIN); request->set_value(""example.com""); request_sender_->StartRequestWithRetry(request); run_loop.Run(); } EXPECT_EQ(HTTP_SUCCESS, error); EXPECT_EQ(net::test_server::METHOD_POST, http_request_.method); EXPECT_EQ(""/drive/v2/files/resource_id2/permissions"", http_request_.relative_url); EXPECT_EQ(""application/json"", http_request_.headers[""Content-Type""]); expected.reset(base::JSONReader::Read( ""{\\""role\\"":\\""writer\\"", \\""type\\"":\\""domain\\"",\\""value\\"":\\""example.com\\""}"")); ASSERT_TRUE(expected); result.reset(base::JSONReader::Read(http_request_.content)); EXPECT_TRUE(http_request_.has_content); EXPECT_TRUE(base::Value::Equals(expected.get(), result.get())); } } // namespace google_apis ",16284,True,3522.7934190428828,median "= DataGrid ++++

++++ `DataGrid`, similarly to the xref:vcl/components/table.adoc[Table] component, is designed to display and sort tabular data and provides means to manipulate rows and columns with greater performance due to the lazy loading of data while scrolling. In addition to this, `DataGrid` has the following features: * <>; * <>; * Advanced configuration of <>; * <>. However, there is no `GroupDataGrid` implementation (but `Table` xref:vcl/components/group-table.adoc[has]). Component’s XML-name: `dataGrid`. [[basics]] == Basics A typical `dataGrid` is shown below: image::vcl/components/data-grid-anatomy.png[align=""center""] . Buttons panel . Sort button . Pagination . Column control button . Rows . Header row An example of `dataGrid` declaration in the XML screen descriptor is shown below: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=data-start;collection-customers;data-end;layout-start;data-grid-simple;layout-end;] ---- In the example, there is a xref:data/collection-container.adoc[collection container] for the `Customer` entity. The `DataGrid` component is bound to the container using the `dataContainer` attribute, while its `columns` element defines which entity attributes are shown in the data grid columns. [[data-binding]] == Data Binding [[declarative-binding]] === Declarative Binding Usually, you bind `dataGrid` to data declaratively in the screen XML descriptor using the `dataContainer` attribute. It should refer to a xref:data/collection-container.adoc[collection container]. [[using-key-value-containers]] === Using Key-Value Containers You can bind the data grid to a xref:data/key-value-containers.adoc[key-value container] to display the results of a query that returns scalar values and/or aggregates. For example: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=data-start;key-value-collection-sales;data-end;layout-start;key-value-grid;layout-end;] ---- [[meta-class]] === Programmatic Binding If you need to define a data container programmatically in the screen controller, set the xref:vcl/xml.adoc#meta-class[metaClass] attribute instead of xref:vcl/xml.adoc#data-container[dataContainer] in XML descriptor: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=meta-class-data-grid] ---- In the screen controller, use `ContainerDataGridItems` class to bind the data grid to a data container: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-customersDataGrid;inject-customersDc;init-start;programmatic-binding;init-end] ---- [[columns]] == Columns The set of columns for a data grid is defined in the `columns` element. If it is not specified, columns will be automatically determined by the xref:data-access:fetching.adoc#fetch-plan[fetch plan] defined in `dataContainer`. The `columns` element can have the following attributes: [[include-all]] * `includeAll` includes all the attributes from `fetchPlan` that is defined in `dataContainer`. + In the example below, we will show all the attributes from the fetch plan used in `customersDc`: + [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=columns-include-all] ---- + If the entity fetch plan contains a reference attribute, this attribute will be displayed according to its xref:data-model:entities.adoc#instance-name[instance name]. If you want to show a specific nested attribute, defined it in the fetch plan as well as in the `column` element: + [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=data-start;collection-customers-with-country;data-end;layout-start;columns-include-all-reference;layout-end] ---- [[exclude]] * `exclude` contains a comma-separated list of attributes that should not be loaded to the data grid. + In the example below, we will show all the attributes excluding `id`, `maritalStatus`, and `email`: + [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=columns-exclude] ---- [[column]] === Column Each column is described in a nested `column` element. [[column-id]] `id` - an optional attribute with the column identifier. If not set, the string with the `property` value will be used as the column identifier. In this case, setting the `property` value is mandatory; otherwise, the `GuiDevelopmentException` exception will be thrown. The `id` attribute is still mandatory for the columns created in the screen controller. [[column-property]] `property` specifies the name of an entity attribute displayed in the column. It can be either an attribute of the entity from the data container or a linked entity (use dot notation to traverse the object graph). For example: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-column] ---- [[column-caption-options]] === Column Caption [[column-caption]] `caption` - an optional attribute containing the column caption. If not specified, a xref:localization:message-bundles.adoc#localizing-data-model[localized name] of the entity attribute is used. This caption is also used as the hiding toggle caption unless explicitly set via the <> attribute. [[column-collapsing]] === Column Collapsing [[column-collapsed]] `collapsed` - an optional attribute; hides the column by default when set to `true`. Users can control the column’s visibility using the menu available via the image:vcl/components/table-column-control-button.png[] button in the top right part of the data grid when the <> attribute is `true`. By default, `collapsed` is `false`. [[column-collapsible]] The `collapsible` attribute defines whether a user can hide or show columns using the column control button. The default value is `true`. [[collapsing-toggle-caption]] The `collapsingToggleCaption` attribute sets the column’s caption in the column control menu. By default, its value is `null`; in this case, the caption remains the same as the column’s <>. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-collapsed] ---- image::vcl/components/data-grid-collapse.gif[align=""center""] As you can see, the `age` column is collapsed by default, but users can expand it from the image:vcl/components/table-column-control-button.png[] button's drop-down menu. At the same time, the `firstName` and `lastName` columns cannot be made collapsed using user actions. The custom caption for the `hobby` column is shown in the drop-down menu of the column control button. [[column-width]] === Column Width `width` - an optional attribute controlling the default column width. It may contain only numeric values in pixels. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-width] ---- image::vcl/components/data-grid-column-width.png[align=""center""] [[column-expand-ratio]] `expandRatio` - an optional attribute that specifies the expand ratio for each column. The ratio must be greater than or equal to 0. If some value is set for at least one column, all implicit values are ignored, and only explicitly assigned values are considered. By default, all columns expand equally (treated as if all of them had the expand ratio of `1`). If you set `width` and `expandRatio` attributes simultaneously, the `expandRatio` attribute will be ignored. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-expandRatio-column] ---- image::vcl/components/data-grid-ratio.png[align=""center""] In the example above, the `DataGrid` component has three columns, with expand ratios `0`, `1`, and `2`, respectively. The column with a ratio of `0` is exactly as wide as its contents require. The column with a ratio of `1` is as wide as it needs, plus a third of any excess space, because we have three parts total, and this column reserves only one of those. The column with a ratio of `2` is as wide as it needs to be, plus two thirds of the excess width. To clear the expand value, set a negative number to an `expandRatio` attribute. [[column-minimum-width]] The `minimumWidth` attribute defines the minimum guaranteed pixel width of the column when it is set to expand. The default value of minimum column width is specified in the xref:app-properties.adoc#jmix-ui-data-grid-default-column-min-width[jmix.ui.DataGrid.defaultColumnMinWidth] property. [[column-maximum-width]] The `maximumWidth` attribute defines the maximum allowed pixel width of the column when it is set to expand. The default value of maximum column width is specified in the xref:app-properties.adoc#jmix-ui-data-grid-default-column-max-width[jmix.ui.DataGrid.defaultColumnMaxWidth] property. [[column-resizable]] === Column Resizing Users can resize data grid columns: image::vcl/components/data-grid-resize.gif[align=""center""] The `resizable` attribute defines whether users can resize this column. By default, all columns are resizable. [[column-resize-mode]] Use the `columnResizeMode` attribute to specify the resize mode. Two modes are supported: * In the `ANIMATED` mode, the grid redraws its columns continuously when users resize columns. * In the `SIMPLE` mode, the grid redraws columns only when the user releases the mouse button. The column size changes can be tracked with <>. [[reordering-allowed]] === Column Reordering `DataGrid` provides the drag-and-drop functionality allowing users to change the order in which columns are displayed within the data grid. // TODO: поменять тут скриншот. Этот от компонента Table. Жду решения тикета https://github.com/Haulmont/jmix-ui/issues/623 image::vcl/components/table-columns-reordering.gif[align=""center""] The column reordering functionality is enabled by default. To disable it, set the `reorderingAllowed` attribute to `false`. The column order changes can be tracked with <>. [[column-freezing]] === Column Freezing `DataGrid` allows you to anchor columns to its left side. It can help keep the essential columns always visible in a grid with a large number of columns. Frozen columns are not scrolled when you scroll the grid horizontally. The `frozenColumnCount` attribute sets the number of fixed columns. The `0` value means that no columns will be fixed except the predefined column with checkboxes for multiple-choice if the <> is used. The `-1` value makes even a multi-select column not fixed. The default value is `0`. Let's consider an example with a data grid where the first two columns are frozen. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-frozen-column] ---- image::vcl/components/data-grid-frozen.gif[align=""center""] == Sizes === Grid Sizing In addition to the xref:vcl/xml.adoc#height[height] and xref:vcl/xml.adoc#width[width] attributes, `DataGrid` has the `minHeight` and `minWidth` optional attributes: [[min-height]] * `minHeight` is used to set the minimum height of the `DataGrid` component. [[min-width]] * `minWidth` is used to set the minimum width of the `DataGrid` component. === Column Sizing See the `width`, `expandRatio`, `minimumWidth` and `maximumWidth` attributes in the <> section. === Row Sizing To set the header row height, use the <> attribute. [[body-row-height]] Use the `bodyRowHeight` attribute to set the height of a body rows in pixels. If the value is `-1`, the row height is calculated based on the theme for an empty row before the `DataGrid` is displayed. To set the footer row height, use the <> attribute. In the example below, we will show the `DataGrid` component with a custom height of a header and body rows: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=sized-grid] ---- image::vcl/components/data-grid-custom-row-height.png[align=""center""] [[selection]] == Selection The `DataGrid` component allows users to select single or multiple rows. [[selection-mode]] The `selectionMode` attribute sets the rows selection mode. There are 4 predefined selection modes: * `SINGLE`; * `MULTI`; * `MULTI_CHECK`; * `NONE`. Rows selection events can be tracked by <>. [[single-selection]] === Single Selection Mode Set the `selectionMode` attribute to the `SINGLE` value to allow users to select a single row at a time. Single selection mode is enabled by default. [[multi-selection]] === Multi Selection Mode If the `selectionMode` attribute is set to `MULTI`, users can select multiple rows in the grid using a keyboard or mouse and holding *Ctrl* or *Shift* keys. [[checkbox-selection]] === Checkbox Selection Mode If the `selectionMode` attribute is set to `MULTI_CHECK`, users can select multiple rows using the embedded column with checkboxes. image::vcl/components/data-grid-checkbox-select.png[align=""center""] [[none-selection]] === Disabling Selection If the `selectionMode` attribute is set to `NONE`, the selection is disabled. [[text-selection-enabled]] === Text Selection The `textSelectionEnabled` attribute defines if text selection is enabled in grid cells. The default value is `false`. == Placeholder `DataGrid` allows you to set a placeholder message and/or link, shown when the data container is empty or not set at all. [[empty-state-message]] The placeholder message is defined using the `emptyStateMessage` attribute. It should contain information about why the grid is empty. [[empty-state-link-message]] The placeholder link is defined using the `emptyStateLinkMessage` attribute. It should describe the action that needs to be performed to fill the grid. For example: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=placeholder-grid] ---- image::vcl/components/data-grid-placeholder.png[align=""center""] Both `emptyStateMessage` and `emptyStateLinkMessage` can load messages from the xref:localization:message-bundles.adoc#using-messages-in-ui[message bundle]. To handle clicks on the link, use <>. [[column-collapsing-allowed]] == Column Control Visibility Users can select which columns are <> using the column control button image:vcl/components/table-column-control-button.png[] in the right part of the data grid header. Currently displayed columns are marked in the drop-down menu. There are additional menu items: * `Select all` - shows all data grid columns; * `Deselect all` - hides all columns that are possible. image::vcl/components/data-grid-column-collapsing-allowed.png[align=""center""] If the `columnsCollapsingAllowed` attribute is set to `false`, users cannot collapse columns. The default value is `true`. When a column name is checked/unchecked, the value of the <> attribute of this column is updated. The column collapsing changes can be tracked with <>. [[headers-footers]] == Headers and Footers [[header-visible]] The `headerVisible` attribute defines whether the `DataGrid` header is visible. The default value is `true`. [[header-row-height]] Use the `headerRowHeight` attribute to set the height of a header row in pixels. If the value is `-1`, the row height is calculated based on the theme for an empty row before the `DataGrid` is displayed. The default value is `-1`. [[footer-visible]] The `footerVisible` attribute defines whether the `DataGrid` footer is visible. The default value is `true`. [[footer-row-height]] Use the `footerRowHeight` attribute to set the height of a footer row in pixels. If the value is `-1`, the row height is calculated based on the theme for an empty row before the `DataGrid` is displayed. The default value is `-1`. `HeaderRow` and `FooterRow` interfaces are used to represent header and footer cells respectively. These cells may be merged for multiple columns. The following methods of `DataGrid` allow to create and manage the `DataGrid` header and footer: * `appendHeaderRow()`, `appendFooterRow()` - adds a new row at the bottom of the header/footer section. * `prependHeaderRow()`, `prependFooterRow()` - adds a new row at the top of the header/footer section. * `addHeaderRowAt()`, `addFooterRowAt()` - inserts a new row at the given position to the header/footer section. Shifts the row currently at that position and any subsequent rows down incrementing their indices. * `removeHeaderRow()`, `removeFooterRow()` - removes the given row from the header/footer section. * `getHeaderRowCount()`, `getFooterRowCount()` - gets the row count for the header/footer section. * `setDefaultHeaderRow()` - sets the default row of the header. The default row is a special header row providing a user interface for sorting columns. `HeaderCell` and `FooterCell` interfaces provide means of customization of static `DataGrid` cells: * `setStyleName()` - sets a custom style name for this cell. * `getCellType()` - returns the type of content stored in this cell. There are 3 types of `DataGridStaticCellType` enumeration available: ** `TEXT` ** `HTML` ** `COMPONENT` * `getComponent()`, `getHtml()`, `getText()` - returns the content displayed in this cell depending on its type. Below is an example of `DataGrid` with the header that contains merged cells and the footer displaying calculated values. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-header-footer] ---- [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=init-footer-header-var;init-start;init-footer-header;init-end;init-footer;init-header;get-average;calculate-member-count] ---- image::vcl/components/data-grid-header-footer.png[align=""center""] [[aggregatable]] == Aggregating `DataGrid` supports the aggregation of values in rows. The following operations are supported: * `SUM` - calculate the sum; * `AVG` - calculate the average value; * `COUNT` - calculate the total number; * `MIN` - find the minimum value; * `MAX` - find the maximum value. To enable aggregation for a data grid, you should: . Set the `aggregatable` attribute to `true`. . Set the `aggregation` element for aggregated grid columns. + [[aggregation-type]] . Set the `type` attribute for the `aggregation` element, which defines the aggregation function. The aggregated values are shown in an additional row. [[aggregation-position]] The `aggregationPosition` attribute allows you to specify the location of the aggregation row: `TOP` or `BOTTOM`. `TOP` is used by default. [NOTE] ==== By default, only numeric data types are supported in aggregated columns, such as `Integer`, `Double`, `Long`, and `BigDecimal`. ==== An example of an aggregated data grid description: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=aggregation-grid] ---- image::vcl/components/data-grid-aggregation.png[align=""center""] [[aggregation-value-description]] The `valueDescription` attribute defines a hint displayed in a popup when a user hovers the mouse cursor on the aggregated value. For the operations listed above (`SUM`, `AVG`, `COUNT`, `MIN`, `MAX`), popup hints are already available by default. [[aggregation-formatter]] You can specify `Formatter` to display the aggregated value in the format other than the standard for this `Datatype`: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-aggregation-format] ---- [[aggregation-strategy-class]] The `aggregation` element can also contain the `strategyClass` attribute specifying a class implementing the `AggregationStrategy` interface. [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/CustomerHobbyAggregation.java[tags=aggregation-strategy] ---- [source,xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-aggregation-strategy] ---- [[grid-sorting]] == Sorting `DataGrid` allows users to sort column data. Sorting functionality is enabled by default. The `sortable` attribute enables sorting data in the grid. By default, it is set to `true`. If sorting is allowed, clicking a column header will show a image:vcl/components/table-sortable-down.png[]/image:vcl/components/table-sortable-up.png[] icon to the right of the column name. [[column-sortable]] You can disable sorting for a particular <> by using its `sortable` attribute. In the example below, we disable sorting by the `lastName` column: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-sorting] ---- [[column-sort]] The `sort` attribute of the `column` element allows you to set the initial sorting direction of the data grid by this `column`. Possible values: * `ASCENDING` - ascending order (0 -> 9 -> A -> Z). * `DESCENDING` - descending order (Z -> A -> 9 -> 0). For example: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-sort] ---- [CAUTION] ==== `DataGrid` can be sorted only by one column at a time. If you set the `sort` attribute for multiple columns or set `sort` and `sortable=""false""` attributes simultaneously, the screen will fail. ==== The `DataGrid` sorting events can be tracked by <>. [[paging]] == Paging The xref:vcl/components/simple-pagination.adoc[] component can be used inside `dataGrid` to provide pagination: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-paging] ---- image::vcl/components/data-grid-pagination.png[align=""center""] Alternatively, you can use the standalone xref:vcl/components/pagination.adoc[] component. [[actions]] == DataGrid Actions The `DataGrid` component implements the `ActionsHolder` interface and can contain custom actions, as well as xref:actions/standard-actions.adoc#list-actions[standard list actions]. Data grid actions are defined in the nested `actions` element. If an action has a caption, it is displayed as an item of the data grid <>. Additionally, a data grid action can be assigned to a button located anywhere on the screen. [[buttons-panel]] You can use the xref:vcl/containers/buttons-panel.adoc[ButtonsPanel] container to show action buttons above the data grid. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-actions-buttons-panel] ---- <1> Define the `create` standard action. <2> Define the `about` custom action. <3> Define a `ButtonsPanel` container inside a data grid. image::vcl/components/data-grid-actions.png[align=""center""] [[data-grid-column-generation]] == Column Generation `ColumnGeneratorEvent` allows you to add generated, or calculated, columns and define a custom representation of data in a column. The handler is invoked by the framework for each cell when rendering the data grid. `ColumnGeneratorEvent` contains information on the entity, displayed in the current `DataGrid` row, and the column identifier. You can create the `ColumnGeneratorEvent` handler for a data grid column using Studio. To do this, you should choose a generated type from the list suggested by Studio and the corresponding type of <>. As an example, let's create a generated column containing the full name of the customer. First, create a column with the `fullName` id: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=text-renderer] ---- Then create the `ColumnGeneratorEvent` handler for the `fullName` column using Studio and implement it as follows: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=column-generator] ---- The result: image::vcl/components/data-grid-generated-column.png[align=""center""] The `fullName` column is a generated column with <>. To register the column generator handler programmatically, use the `addGeneratedColumn()` method of the `DataGrid` component. [[renderers]] == Renderers The way the data is displayed in columns can be customized using parameterized declarative renderers. Some `DataGrid` renderers are set by special XML elements with parameters defined in the corresponding attributes. Renderers can be declared for not generated columns. The framework provides the following renderers: * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> [[button-renderer]] === ButtonRenderer `ButtonRenderer` displays string values as a button caption. `ButtonRenderer` cannot be declared in the XML descriptor because it is not possible to define a renderer click listener in the XML descriptor. Studio will generate the `ButtonRenderer` declaration code in the `onInit()` screen controller method, for example: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-gridButtonRenderer;inject-notifications;init-start;button-renderer;init-end] ---- image::vcl/components/data-grid-button-renderer.png[align=""center""] [[image-renderer]] === ImageRenderer `ImageRenderer` is a renderer for presenting images. The value of the corresponding property is used as the image location. Location can be a theme resource or URL. `ImageRenderer` cannot be declared in the XML descriptor because it is not possible to define a renderer click listener in the XML descriptor. Studio will generate the `ImageRenderer` declaration code in the `onInit()` screen controller method, for example: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-imageGrid;inject-notifications;init-start;image-renderer;init-end] ---- The result: image::vcl/components/data-grid-image-renderer.png[align=""center""] [[check-box-renderer]] === CheckBoxRenderer `CheckBoxRenderer` displays boolean values as a checkbox icon. The `column` element of `DataGrid` has a child `checkBoxRenderer` element: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-check-box-renderer] ---- [[number-renderer]] === NumberRenderer `NumberRenderer` displays numbers in the defined format. The `column` element of `DataGrid` has a child `numberRenderer` element with non-required `nullRepresentation` attribute and required `format` string attribute. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-number-renderer] ---- `formatString` is the format string describing the number format which will be used to create the `NumberFormat` instance. [[local-date-time-renderer]] === LocalDateTimeRenderer `LocalDateTimeRenderer` displays dates as `LocalDateTime` values. The `column` element of `DataGrid` has a child `localDateTimeRenderer` element with non-required `nullRepresentation` attribute and required `format` string attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-local-date-time-renderer] ---- [[local-date-renderer]] === LocalDateRenderer `LocalDateRenderer` displays dates as `LocalDate` values. The `column` element of `DataGrid` has a child `localDateRenderer` element with non-required `nullRepresentation` attribute and required `format` string attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-local-date-renderer] ---- The result: image::vcl/components/data-grid-local-date-renderer.png[align=""center""] [[date-renderer]] === DateRenderer `DateRenderer` displays dates in the defined format. The `column` element of `DataGrid` has a child `dateRenderer` element with non-required `nullRepresentation` attribute and required `format` string attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-date-renderer] ---- `formatString` is the format string describing the date and time format used to create the `DateFormat` instance. image::vcl/components/data-grid-date-renderer.png[align=""center""] Please note, the `startDate` field has a `DateRenderer`, and the `endDate` field does not. [[progress-bar-renderer]] === ProgressBarRenderer `ProgressBarRenderer` displays `double` values between 0 and 1 as a `ProgressBar` component. The `column` element of `DataGrid` has a child `progressBarRenderer` element: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-progress-bar-renderer] ---- The result: image::vcl/components/data-grid-progress-bar-renderer.png[align=""center""] [[html-renderer]] === HtmlRenderer `HtmlRenderer` displays HTML layout. The `column` element of `DataGrid` has a child `htmlRenderer` element with a non-required `nullRepresentation` attribute. Below is an example of rendering the `endDate` attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-html-renderer] ---- [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=html-renderer] ---- The result: image::vcl/components/data-grid-html-renderer.png[align=""center""] [[clickable-text-renderer]] === ClickableTextRenderer `ClickableTextRenderer` displays simple plain-text string values as a link with call back handler. `ClickableTextRenderer` cannot be declared in the XML descriptor because it is not possible to define a renderer click listener in the XML descriptor. Studio will generate the `ClickableTextRenderer` declaration code in the `onInit()` screen controller method, for example: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-gridClick;inject-notifications;init-start;clickable-text-renderer;init-end] ---- The result: image::vcl/components/data-grid-click-text-renderer.gif[align=""center""] [[text-renderer]] === TextRenderer `TextRenderer` is a renderer for presenting simple plain-text string values. The `column` element of `DataGrid` has a child `textRenderer` element with non-required `nullRepresentation` attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=text-renderer] ---- [[component-renderer]] === ComponentRenderer `ComponentRenderer` is a renderer for UI components. The `column` element of `DataGrid` has a child `componentRenderer` element: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-component-renderer] ---- In the example below, we will display the `age` value in the `Slider` component. [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=component-renderer] ---- The result: image::vcl/components/data-grid-component-renderer.png[align=""center""] [[icon-renderer]] === IconRenderer `IconRenderer` is a renderer that represents `JmixIcon`. The `column` element of `DataGrid` has a child `iconRenderer` element. Below is an example of rendering a generated `hasEmail` attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-icon-renderer] ---- [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=icon-renderer] ---- The result: image::vcl/components/data-grid-icon-renderer.png[align=""center""] [[item-details-generator]] == Item Details Generator Item details are expandable content areas used to display more information for a specific row. The `DetailsGenerator` interface allows you to create a custom component to display item details. You can create the `DetailsGenerator` handler for `DataGrid` using Studio (see <>) and implement it as follows: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-detailsGrid;details-generator;create-close-button;get-content] ---- To handle showing and hiding the details you should implement your own listener. For instance, in this sample, we handle opening the details in the `ItemClickAction` of the `DataGrid` component: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=item-click-event] ---- The result: image::vcl/components/data-grid-detail-generator.png[align=""center""] [[editing]] == Editing Values [[editor-enabled]] `DataGrid` provides inline editing that allows users to manipulate grid data. To enable inline editing, set the `editorEnabled` attribute to `true`. === Usage * Inline editing can be instantiated by double-clicking on the field to be edited or pressing *Enter* when an editable cell is focused. [[column-editable]] * The columns with `editable = true` attribute show components to edit the attributes of the corresponding entity. Non-editable fields will be disabled. * The component type for each editable column is selected automatically based on the type of the corresponding entity attribute. For example, for string and numeric attributes, the application will use xref:vcl/components/text-field.adoc[TextField], for `Date` - xref:vcl/components/date-field.adoc[DateField], for enumerations - xref:vcl/components/combo-box.adoc[ComboBox], for links to other entities - xref:vcl/components/entity-picker.adoc[EntityPicker]. * Once a row becomes editable, default *OK* and *Cancel* buttons will appear near the row allowing users to commit or cancel the edit. * To save the changes and exit edit mode, click the *OK* button or press *Enter*. * To discard the changes and exit edit mode, click the *Cancel* button or press *Esc*. image::vcl/components/data-grid-editing.png[align=""center""] [[editor-buffered]] === Modes Editing can be either buffered and non-buffered. * In the buffered mode, changes must be explicitly committed. * Non-buffered editing automatically commits changes when a field loses focus. The `editorBuffered` attribute sets the buffered editor mode. The default value is `true`. === Inline Editor Customizing [[editor-cancel-caption]] The `editorCancelCaption` attribute sets the caption on the cancel button in the `DataGrid` editor. [[editor-save-caption]] The `editorSaveCaption` attribute sets the caption on the save button in the `DataGrid` inline editor. [[edit-field-generator]] The editor field can be customized with the help of `EditorFieldGenerationContext` class. You should create an edit field generator that generates a component for this column in `DataGrid` editor, for example: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-citiesDc;edit-field-generator] ---- The result: image::vcl/components/data-grid-edit-field-generator.png[align=""center""] There is also a declarative way of defining what component to use for selecting an entity in generic mechanisms. It is based on the xref:app-properties.adoc#jmix-ui-component-entity-field-type[jmix.ui.component.entityFieldType] and xref:app-properties.adoc#jmix-ui-component-entity-field-actions[jmix.ui.component.entityFieldActions] properties. For example, if you add the following lines to the `application.properties` file: [source,properties] ---- jmix.ui.component.entityFieldType.uiex1_City = entityComboBox jmix.ui.component.entityFieldActions.uiex1_City = entity_lookup, entity_open, entity_clear ---- Then the `EntityComboBox` component will be generated for the `City` entity: image::vcl/components/data-grid-editable-custom-field.png[align=""center""] [[editor-cross-field-validate]] === Cross Field Validation `DataGrid` inline editor can take into account entity constraints (cross-field validation). If there are validation errors, `DataGrid` will show an error message. To enable or disable validation, use the `editorCrossFieldValidate` attribute. The default value is `true`. === Editor Events [[editor-open-event]] * `EditorOpenEvent` is an event that is fired before the `DataGrid` editor is opened. Provides access to the components used in the editor, allowing the possibility to change their values programmatically. + For example: + [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=editor-open-event] ---- [[editor-close-event]] * `EditorCloseEvent` is an event that is fired when the `DataGrid` editor is closed. Provides access to the components used in the editor, allowing the possibility to use their values programmatically. [[editor-pre-commit-event]] * `EditorPreCommitEvent` is an event that is fired before the item is updated. Provides access to the components used in the editor, allowing the possibility to use their values programmatically. [[editor-post-commit-event]] * `EditorPostCommitEvent` is an event that is fired after the item is updated. Provides access to the components used in the editor, allowing the possibility to use their values programmatically. The changes are committed to the data container only. The logic to save these changes in the database should be added separately. === Methods of Inline Editor [[method-get-edited-item]] * `getEditedItem()` returns the item that is currently being edited or `null` if no item is being edited at the moment. [[method-is-editor-active]] * `isEditorActive()` returns whether an item is currently being edited in the editor. [[method-edit]] * The `edit()` method opens the editor interface for the provided entity. Scrolls `DataGrid` to bring the entity to view if it is not already visible. [[context-menu-enabled]] == Context Menu The context menu is activated by right-clicking within the data grid. The `contextMenuEnabled` attribute enables the context menu. By default, this attribute is set to `true`. The context menu shows <> (if any). The right mouse clicks on the data grid can be tracked with <>. [[stylename]] == Styling You can set predefined styles to the `DataGrid` component using the `stylename` attribute either in the XML descriptor or in the screen controller: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-stylename] ---- [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=set-style-name] ---- Predefined styles: * `borderless` - removes the outer border of the data grid; * `no-horizontal-lines` - removes the horizontal divider lines between the data grid rows; * `no-vertical-lines` - remove the vertical divider lines between the data grid columns. * `no-stripes` - removes the alternating row colors. The appearance of the `DataGrid` component can be customized using SCSS variables with the `$jmix-datagrid-*` prefix. You can change these variables in the visual editor after creating a xref:themes/custom_theme.adoc[custom theme]. [[methods]] == Methods of DataGrid Interface [[methods-get-columns]] * `getColumns()` returns a copy of currently configured columns in their current visual order in this `DataGrid`. [[methods-get-visible-columns]] * `getVisibleColumns()` returns a copy of columns not hidden by security permissions. [[methods-sort]] * The `sort()` method <> the `DataGrid` data for the specified column in the chosen sort direction. [[methods-scroll-to]] * `scrollTo()` allows you to scroll the `DataGrid` to the specified row. It takes an entity instance identifying the row as a parameter. Besides the entity instance, an overloaded method can take a `ScrollDestination` parameter with the following possible values: ** `ANY` - scroll as little as possible to show the target element. If the element fits into view, this works as `START` or `END`, depending on the current scroll position. If the element does not fit into view, this works as `START`. ** `START` - scrolls so that the element is shown at the start of the viewport. The viewport will, however, not scroll beyond its contents. ** `MIDDLE` - scrolls so that the element is shown in the middle of the viewport. However, the viewport will not scroll beyond its contents, given more elements than what the viewport can show at once. Under no circumstances will the viewport scroll before its first element. ** `END` - scrolls so that the element is shown at the end of the viewport. The viewport will, however, not scroll before its first element. [[methods-scroll-to-start-end]] * `scrollToStart()` and `scrollToEnd()` - scroll `DataGrid` to the first data item and to last data item respectively. [[methods-get-aggregation-results]] * The `getAggregationResults()` method returns a map with <> results, where map keys are data grid column identifiers and values are aggregation values. [[handlers]] == Events and Handlers include::../events-hanlers-generation-tip.adoc[] [[column-collapsing-change-event]] === ColumnCollapsingChangeEvent `ColumnCollapsingChangeEvent` is sent when a column's <> changes. Example of subscribing to the event for the data grid defined in the screen XML with the `collapseGrid` id: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=column-collapsing-change-event] ---- To register the event handler programmatically, use the `addColumnCollapsingChangeListener()` component method. [[column-reorder-event]] === ColumnReorderEvent See xref:vcl/components/table.adoc#column-reorder-event[ColumnReorderEvent]. [[column-resize-event]] === ColumnResizeEvent `ColumnResizeEvent` is sent when a column is <>. Example of subscribing to the event for the data grid defined in the screen XML with the `resizedEventGrid` id: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=column-resize-event] ---- To register the event handler programmatically, use the `addColumnResizeListener()` component method. [[context-click-event]] === ContextClickEvent `ContextClickEvent` happens when a context-click occurs on the client-side inside `DataGrid`. `ContextClickEvent` contains information about mouse event details. Example of subscribing to the event for the data grid defined in the screen XML with the `contextGrid` id: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=context-click-event] ---- To register the event handler programmatically, use the `addContextClickListener()` component method. === EditorCloseEvent See <>. === EditorOpenEvent See <>. === EditorPostCommitEvent See <>. === EditorPreCommitEvent See <>. [[item-click-event]] === ItemClickEvent `ItemClickEvent` is sent when the user clicks on a data grid. `ItemClickEvent` contains information about: * Mouse event details; * An entity instance represented by the clicked row; * An item `id`; * `id` of the clicked `DataGrid` column. As an example, we will give the user to begin <> by single-clicking on an editable cell: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=item-click-event2] ---- To register the event handler programmatically, use the `addItemClickListener()` component method. [[selection-event]] === SelectionEvent See xref:vcl/components/table.adoc#selection-event[SelectionEvent]. [[sort-event]] === SortEvent `SortEvent` is sent when a <> order is changed. Example of subscribing to the event for the data grid defined in the screen XML with the `sortGrid` id: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=sort-event] ---- To register the event handler programmatically, use the `addSortListener()` component method. [[context-help-icon-click-handler]] === ContextHelpIconClickHandler See xref:vcl/api.adoc#context-help-icon-click-handler[ContextHelpIconClickHandler]. [[details-generator]] === DetailsGenerator See <>. [[empty-state-link-click-handler]] === EmptyStateLinkClickHandler See xref:vcl/components/table.adoc#empty-state-click-event[EmptyStateLinkClickHandler]. [[lookup-select-handler]] === LookupSelectHandler See xref:vcl/components/table.adoc#lookup-select-handler[LookupSelectHandler]. [[row-description-provider]] === RowDescriptionProvider `RowDescriptionProvider` generates optional descriptions (tooltips) when the user hovers over a `DataGrid` row. If `DescriptionProvider` for a column is also set, the row description generated by `RowDescriptionProvider` is used for cells for which the cell description provider returns `null`. In the example below, we will show a `RowDescriptionProvider` usage for the `rowDescGrid`: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=row-description-provider] ---- The result: image::vcl/components/data-grid-row-description.gif[align=""center""] To register the provider programmatically, use the `setRowDescriptionProvider()` component method. [[row-style-provider]] === RowStyleProvider `RowStyleProvider` allows style providers for the `DataGrid` rows. `DataGrid` can use several providers to obtain many style names for rows. Example of setting a style: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=row-style-provider] ---- Then you should define row styles in the application theme. Detailed information on creating a theme is available in xref:themes.adoc[Themes]. Style names returned by the provider in the screen controller should be used as CSS selectors. For example: [source,css,indent=0] ---- include::example$/ex1/src/main/themes/helium-extended/helium-extended.scss[tags=grid-rows-style] ---- The result: image::vcl/components/data-grid-row-style.png[align=""center""] [[xml]] == All XML Attributes include::../xml-studio-tip.adoc[] === DataGrid XML Attributes <> - <> - xref:vcl/xml.adoc#align[align] - <> - xref:vcl/xml.adoc#box-expand-ratio[box.expandRatio] - xref:vcl/xml.adoc#caption[caption] - xref:vcl/xml.adoc#caption-as-html[captionAsHtml] - xref:vcl/xml.adoc#colspan[colspan] - <> - <> - xref:vcl/xml.adoc#context-help-text[contextHelpText] - xref:vcl/xml.adoc#context-help-text-html-enabled[contextHelpTextHtmlEnabled] - <> - xref:vcl/xml.adoc#css[css] - xref:vcl/xml.adoc#data-container[dataContainer] - xref:vcl/xml.adoc#description[description] - xref:vcl/xml.adoc#description-as-html[descriptionAsHtml] - <> - <> - <> - <> - <> - <> - <> - xref:vcl/xml.adoc#enable[enable] - <> - <> - <> - <> - <> - xref:vcl/xml.adoc#height[height] - xref:vcl/xml.adoc#html-sanitizer-enabled[htmlSanitizerEnabled] - xref:vcl/xml.adoc#icon[icon] - xref:vcl/xml.adoc#id[id] - <> - <> - <> - <> - xref:vcl/xml.adoc#responsive[responsive] - xref:vcl/xml.adoc#rowspan[rowspan] - <> - <> - <> - xref:vcl/xml.adoc#tab-index[tabIndex] - <> - xref:vcl/xml.adoc#visible[visible] - xref:vcl/xml.adoc#width[width] [[xml-data-grid-elements]] === DataGrid XML Elements <> - <> - <> - <> === Columns XML Attributes <> - <> === Column XML Attributes xref:vcl/xml.adoc#box-expand-ratio[box.expandRatio] - <> - <> - <> - <> - xref:vcl/xml.adoc#colspan[colspan] - <> - <> - <> - <> - <> - <> - <> - xref:vcl/xml.adoc#rowspan[rowspan] - <> - <> - <> === Column XML Elements <> - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> === Aggregation XML Attributes <> - <> - <> == API <> - <> - <> - <> - <> - <> - <> - <> - <> - xref:vcl/components/table.adoc#methods-set-enter-press-action[setEnterPressAction] - xref:vcl/components/table.adoc#methods-set-item-click-action[setItemClickAction] - <>",12089,True,2501.198771847107,median "= rouziclib This is my library of code that is common to all my different projects such as https://photosounder.com[Photosounder], https://photosounder.com/spiral/[Spiral] and https://photosounder.com/splineeq/[SplineEQ], but also lesser projects such as my minimalistic https://github.com/Photosounder/rouziclib-picture-viewer[picture viewer], my https://github.com/Photosounder/screenshot-tool[screenshot tool] or my modernised version of NASA's https://github.com/Photosounder/Voyager-Image-Decoder[Voyager Image Decoder] as well as projects you don't know about such as my private project Spacewar which is where all my new code is born. It includes some of the following: * Fast lookup table-based fixed-point arithmetic approximations for sqrt, hypot, log2, exp2, pow, cos, atan2 (both noting angles in http://en.wikipedia.org/wiki/Turn_(geometry)[turns], not radians), the Gaussian function (http://www.wolframalpha.com/input/?i=e%5E-x%C2%B2[e^-x²^]) and the raised error function (https://www.wolframalpha.com/input/?i=0.5%2B0.5erf(x)[0.5+0.5erf(x)]). Some are implemented using linear interpolation, segmented quadratic polynomial approximation or simple lookup, which offers different levels of speed/precision/memory usage tradeoffs. * Fast polynomial lookup table-based floating-point approximations for cos, log2, exp2, pow and others. * Original math functions such as a short Gaussian function and its integral, the short error function which I now use for filter design. I also created an approximation of the inverse of the error function accurate to about 10^-12^. * Functions to draw lines, points, circles, roundrects and gradients, all antialiased with Gaussian filtering * Functions to convert from sRGB to linear RGB for loading images and to convert from linear RGB to sRGB with optional Gaussian dithering for displaying * Geometric functions used for computing intersections between lines, shortest the distance of a point to a line or to limit a line to a bounding box * Blending modes like additive, subtractive, multiplicative blending and alpha blending * Blitting of a buffer onto another, like for displaying a sprite * An original Hue-Saturation-Luminance colour space with a Luminance that is about perceptually correct (unlike the 1931 CIE XYZ colour space which gets the weights of each colour blatantly wrong) which is used for HSL to RGB conversion and for bringing out of gamut colours (such as colours that have components brighter than 1.0) to the most appropriate representable colour * Vector font generation, vector text rendering and a built-in minimalistic vector font that is always available. A more complete typeface is available in the link:vector_type[vector_type] directory * Vector procedural zoomable interface elements that for instance allow you to have a fully functional button just by calling a function with all the necessary information provided as parameters (without anything stored in memory) and simply getting the return value, with no need for storage for each instance of a control, no unique IDs or anything * Functions to conveniently do operations on point vectors (2D or 3D) or rectangles and triangles, such as generating rectangle coordinates based on position, size and offset vectors, or calculating the scaling and positioning needed to make a rectangle fit in a certain way inside another rectangle. This forms the basis of the aforementioned interface system. * A drawing queue-based graphical system that lets the main thread queue drawing commands and then is rendered on the GPU using OpenCL or the CPU in a threaded way * A file concatenation feature called fileball similar to tarball that I use to pack and compress many files together as one header that can be included in an executable in a portable compiler-independent way, like my vector typeface. * Convenient directory-listing and file management features * Built-in dependency-free loading of various image formats (https://github.com/nothings/stb/blob/master/stb_image.h[JPG, PNG, BMP, PSD], TIFF, https://heasarc.gsfc.nasa.gov/docs/heasarc/fits.html[NASA]'s FITS), saving of images (32-bit TIFF, https://github.com/nothings/stb/blob/master/stb_image_write.h[PNG, JPG, BMP]), loading of sounds (AIFF, WAVE, https://github.com/lieff/minimp3/blob/master/minimp3.h[MP3], https://github.com/mackron/dr_libs/blob/master/dr_flac.h[FLAC], https://github.com/nothings/stb/blob/master/stb_vorbis.c[OGG]) and saving of sounds (AIFF, WAVE). * Modified libraries such as a version of https://github.com/zywina/cfftpack[cfftpack] modified so that both single and double precision floating point FFTs can be done in the same program (not possible with the original) or a version of https://github.com/tronkko/dirent[dirent] modified to fix some path length and Unicode conversion bugs, or a cut-down version of https://github.com/nigels-com/glew[GLEW] that contains only what rouziclib needs. * Fast tiled mipmap generation, image rescaling based on https://photosounder.com/michel_rouzic/#flattop[flat-top bilinear filtering], Gaussian blurring, an original texture compression and YUV coding/decoding in C and OpenCL. * A system for loading and saving an application's preferences to one file but in a non-centralised way with just a simple value query being enough to add a new value in its proper place * A sound system so that multiple functions can play sounds at the same time by providing a callback * Functions to easily resize buffers as needed and a generic buffer system based on this with many functions that replicate how outputing to a file stream works * Binary searching of arrays * Functions to convert between UTF-8, UTF-16 and Unicode codepoints. A subset of these functions forms the basis for https://github.com/Photosounder/fopen_utf8[fopen_utf8] which I recommend you use if you need to fopen UTF-8 paths on Windows. * Various functions to parse or format strings * Various utility functions and macros * Code for working with https://www.libsdl.org/[SDL], OpenGL, https://www.khronos.org/opencl/[OpenCL], https://github.com/clMathLibraries/clFFT[clFFT], http://openil.sourceforge.net/[DevIL], http://opencv.org/[OpenCV], https://www.ffmpeg.org/[FFMPEG], https://www.libraw.org/[LibRAW] and http://www.mpfr.org/[MPFR]. All graphical functions operate on pixels in a linear colour space. Please do not use these functions directly in a gamma-compressed colour space, instead use an intermediary linear framebuffer which you can then convert to an sRGB framebuffer using the function `convert_lrgb_to_srgb`. === How to use it Unusually for a library, rouziclib's code relies on macros that are defined inside your project's code. This means that rouziclib isn't entirely independently compiled. So the way to make this work is to create two files in your project, a header file which directly includes the main header, but not before you add the macros you can optionally define, and a code file which includes the aforementioned header file you just created and then includes the library's rouziclib.c. Here's how it looks: rl.h [source,C] ---- #ifndef H_PRL #define H_PRL #ifdef __cplusplus extern ""C"" { #endif // these are examples of optional macros that rouziclib will then use for your project #define COL_FRGB // this macro makes the internal format for colour be floating-point instead of fixed-point #define RL_SDL // this includes SDL-using code as well as the necessary SDL files #define RL_OPENCL // same for OpenCL // this defines a wrapper for fprintf_rl, so your project can use a custom fprintf-type function that can for instance output to a file #define fprintf_rl fprintf_wrapper #include #include extern void fprintf_wrapper (FILE *stream, const char* format, ...); #include #ifdef __cplusplus } #endif #endif ---- rl.c [source,C] ---- #include ""rl.h"" // this creates that custom printing function that all calls to fprintf_rl in rouziclib will use void fprintf_wrapper (FILE *stream, const char* format, ...) { va_list args; va_start (args, format); vfprintf (stream, format, args); // printf to original stream fflush (stream); va_end (args); } #include ---- I realise that this is a bit unusual, but it's pretty simple and very handy. You can for instance include rouziclib in a simple command-line C program without having to worry about dependencies as none will be included, and in another project add dependencies as you need by adding the necessary macros, so without having the recompile anything separately (as you would have to were you to use two versions of a same library compiled with different dependencies) you can have in separate projects a rouziclib with no dependencies or a rouziclib that uses SDL, DevIL, OpenCV, OpenCL, clFFT, FFMPEG and LibRAW. === Example project Have a look at a minimal https://github.com/Photosounder/rouziclib-picture-viewer[picture viewer] built around rouziclib, with explanations of its features, how it works and how to expand on it or create a similar program. === Files * link:rouziclib/rouziclib.c[rouziclib.c] / link:rouziclib/rouziclib.h[rouziclib.h] / link:rouziclib/rouziclib.m[rouziclib.m] + Every piece of code in this library is ultimately included into one of those three files, so it's as if this whole library was only made of 2 (or 3 on macOS) files. Basically rouziclib is just like a two-file library broken down into over 360 files due to size. * link:rouziclib/general[general/] ** link:rouziclib/general/xyz.c[xyz.c] / link:rouziclib/general/xyz.h[xyz.h] and link:rouziclib/general/xyz_struct.h[xyz_struct.h] + Vectors (2D, 3D integer 2D and 3x3 matrices) with conversions and operations. Very widely used throughout the library. ** link:rouziclib/general/time.c[time.c] / link:rouziclib/general/time.h[time.h] + Multiplatform standard and high resolution time-measuring, sleep, date-time string parsing and Julian date conversion. ** link:rouziclib/general/estimates.c[estimates.c] / link:rouziclib/general/estimates.h[estimates.h] + Functions for estimating the program's framerate. ** link:rouziclib/general/mouse.c[mouse.c] / link:rouziclib/general/mouse.h[mouse.h] and link:rouziclib/general/mouse_struct.h[mouse_struct.h] + Mouse cursor logic and cursor drawing. ** link:rouziclib/general/keyboard.c[keyboard.c] / link:rouziclib/general/keyboard.h[keyboard.h] and link:rouziclib/general/keyboard_struct.h[keyboard_struct.h] + Processing SDL keyboard events to update arrays of flags while avoiding missing quick presses like when both the down and up event arrive at the same time. Also controls the zoom-scroll system from key combos. ** link:rouziclib/general/noop.c[noop.c] / link:rouziclib/general/noop.h[noop.h] + Functions that do nothing and say so when that's needed. ** link:rouziclib/general/hashing.c[hashing.c] / link:rouziclib/general/hashing.h[hashing.h] + Functions for hashing using https://github.com/Cyan4973/xxHash/[xxHash]. ** link:rouziclib/general/threading.c[threading.c] / link:rouziclib/general/threading.h[threading.h] + Multiplatform threading, mainly wrappers for https://github.com/mattiasgustavsson/libs/blob/main/thread.h[thread.h]. ** link:rouziclib/general/intrinsics.c[intrinsics.c] / link:rouziclib/general/intrinsics.h[intrinsics.h] + Functions for testing Intel x86 CPU features at runtime, replacements for certain intrinsics that can be missing or inefficient, macros that simplify basic operations. ** link:rouziclib/general/crash_dump.c[crash_dump.c] / link:rouziclib/general/crash_dump.h[crash_dump.h] + Windows-only functions to generate a minidump file in case the program crashes. ** link:rouziclib/general/audio.c[audio.c] / link:rouziclib/general/audio.h[audio.h] + Audio system that can call multiple callbacks, mix their outputs, register them, deregister and stop running them automatically. ** link:rouziclib/general/structs.h[structs.h] + Generic buffer structure and generic lookup table structure. ** link:rouziclib/general/globals.c[globals.c] / link:rouziclib/general/globals.h[globals.h] + Creates the globals used by the various system in rouziclib, such as the framebuffer structure (thread-local so that other threads can render to a framebuffer and therefore use the usual drawing and GUI functions, like when rendering a video), the zoom-scroll state, the mouse-keyboard state, the vector typeface, the audio system, the window manager as well as the default drawing thickness. * link:rouziclib/memory[memory/] ** link:rouziclib/memory/alloc.c[alloc.c] / link:rouziclib/memory/alloc.h[alloc.h] + Manages allocations, reallocations, deallocations, copying, 2D arrays and managing an allocation list. Contains the very essential `alloc_enough()` which I use extensively to resize buffers as needed. ** link:rouziclib/memory/fill.c[fill.c] / link:rouziclib/memory/fill.h[fill.h] + Like `memset()` but with 32 and 64-bit words instead of 8 bits. ** link:rouziclib/memory/swap.c[swap.c] / link:rouziclib/memory/swap.h[swap.h] + Functions to swap two values. ** link:rouziclib/memory/circular_buffer.c[circular_buffer.c] / link:rouziclib/memory/circular_buffer.h[circular_buffer.h] + Manages circular buffers by wrapping indices around and doing the equivalent of `memset()` and `memcpy()` on circular buffers or from linear buffers to circular buffers. ** link:rouziclib/memory/generic_buffer.c[generic_buffer.c] / link:rouziclib/memory/generic_buffer.h[generic_buffer.h] + A generic buffer is a structure that contains a buffer (usually used as a string, otherwise as a byte stream) as well as a count of how many bytes are currently used and how many are allocated. This allows for the buffer to be enlarged as needed, to avoid inefficiencies that come from running `strlen()` to know where a string ends, and to have functions that behave on strings just like on a `FILE` pointer. For instance `bufprintf()` works just like `fprintf()` except on a string (as a generic buffer), which is rather convenient, and `bufwrite()` works like `fwrite()`, which makes creating binary files in memory much easier. ** link:rouziclib/memory/comparison.c[comparison.c] / link:rouziclib/memory/comparison.h[comparison.h] + Contains often-needed comparison functions that like `strcmp()` can be used with `qsort()` or `bsearch()`. `array_find_index_by_cmp()` uses binary searching to find an index in a pre-sorted array based on a given value. * link:rouziclib/geometry[geometry/] ** link:rouziclib/geometry/rect.c[rect.c] / link:rouziclib/geometry/rect.h[rect.h] and link:rouziclib/geometry/rect_struct.h[rect_struct.h] + Vectors for rectangles, integer rectangles and triangles, and functions to create, transform or get information from such rectangles. ** link:rouziclib/geometry/intersection.c[intersection.c] / link:rouziclib/geometry/intersection.h[intersection.h] + Functions to computer intersections between lines, find the distance between a point and a line, find the segment of a line inside a rectangle, intersect rectangles, intersect a circle with a rectangle, find if a point is inside a rectangle or circle, or find the angular radius of a circle from a point. ** link:rouziclib/geometry/rotation.c[rotation.c] / link:rouziclib/geometry/rotation.h[rotation.h] + Handle 2D and 3D vector rotation. ** link:rouziclib/geometry/fit.c[fit.c] / link:rouziclib/geometry/fit.h[fit.h] + Functions to find how to best fit squares or rectangles in an area, manage a Hilbert curve grid, fit a rectangle inside a rectangular area or subdivide a rectangle. ** link:rouziclib/geometry/distance.c[distance.c] / link:rouziclib/geometry/distance.h[distance.h] + Calculate the hypothenuse in 2D and 3D and move a point away from another point using a given distance multiplier. ** link:rouziclib/geometry/bezier.c[bezier.c] / link:rouziclib/geometry/bezier.h[bezier.h] + Can turn an array of points into an array of cubic Bézier segments with automatic handles and evaluate an entire array of Bézier segments for a given value of `x`. ** link:rouziclib/geometry/misc.c[misc.c] / link:rouziclib/geometry/misc.h[misc.h] + Mainly triangle functions. * link:rouziclib/math[math/] ** link:rouziclib/math/functions.c[functions.c] / link:rouziclib/math/functions.h[functions.h] + Basic math functions, an approximation of the inverse error function, functions to find a value or interpolated value from an array of 2D points. ** link:rouziclib/math/ieee754.c[ieee754.c] / link:rouziclib/math/ieee754.h[ieee754.h] + IEEE-754 floating point manipulation, fractional part calculation and dealing with numbers at the level of https://en.wikipedia.org/wiki/Unit_in_the_last_place[units of least precision] to guarantee incrementation or make floating point comparisons that take a degree of error into account. ** link:rouziclib/math/rand.c[rand.c] / link:rouziclib/math/rand.h[rand.h] + Functions to generate uniform pseudo-random numbers in a given range, nmumbers with a normal (Gaussian) distribution and a PRNG based on MINSTD. ** link:rouziclib/math/dsp.c[dsp.c] / link:rouziclib/math/dsp.h[dsp.h] + FFT size calculation, basic array operations, root mean square computation, decibel conversion, Blackman window, short Gaussian window (an original way to make a Gaussian window finite with desirable characteristics) and its integral, polynomial step functions, ramp filter kernel computation. ** link:rouziclib/math/dct.c[dct.c] / link:rouziclib/math/dct.h[dct.h] + Discrete Cosine Transform computation for JPEG 8x8 blocks. ** link:rouziclib/math/matrix.c[matrix.c] / link:rouziclib/math/matrix.h[matrix.h] + Matrix determinant and inverse, including MPFR versions. ** link:rouziclib/math/physics.c[physics.c] / link:rouziclib/math/physics.h[physics.h] + Euler physical integration. ** link:rouziclib/math/debug.c[debug.c] / link:rouziclib/math/debug.h[debug.h] + Something used by my graphing calculator. ** link:rouziclib/math/polynomials.c[polynomials.c] / link:rouziclib/math/polynomials.h[polynomials.h] + Polynomial evaluation (1D and 2D), error calculation for approximations, coefficient operations, Chebyshev fitting by discrete cosine transform, conversion of Chebyshev coefficients to polynomial coefficients, digit reduction to make coefficients take up less digits and an attempt at optimising fits to reduce the maximum error. ** link:rouziclib/math/erf_radlim.c[erf_radlim.c] / link:rouziclib/math/erf_radlim.h[erf_radlim.h] + Part of my attempts at directly computing Gaussian-antialiased triangles. * link:rouziclib/fixedpoint[fixedpoint/] and link:rouziclib/fastfloat[fastfloat/] ** link:rouziclib/fixedpoint/fp.c[fp.c] / link:rouziclib/fixedpoint/fp.h[fp.h] + Fixed point approximations for the square root, division, log2m exp2, cosine, atan2, the Gaussian function and the error function. ** link:rouziclib/fastfloat/fastfloat.c[fastfloat.c] / link:rouziclib/fastfloat/fastfloat.h[fastfloat.h] + Floating point approximations for log2, exp2, pow, the square root (which tends to be slower than just using `sqrt()`), linear to sRGB gamma conversion and exp over a small range. ** link:rouziclib/fastfloat/fastcos.c[fastcos.c] / link:rouziclib/fastfloat/fastcos.h[fastcos.h] + Floating point approximations for the cosine at different levels of precision, in turns or radians. ** link:rouziclib/fastfloat/simd.c[simd.c] / link:rouziclib/fastfloat/simd.h[simd.h] + Intel x86 SIMD versions of Gaussian, error function and linear to sRGB conversion approximations. * link:rouziclib/graphics[graphics/] ** link:rouziclib/graphics/graphics.c[graphics.c] / link:rouziclib/graphics/graphics.h[graphics.h] and link:rouziclib/graphics/graphics_struct.h[graphics_struct.h] + Functions to manage the `raster_t` and `framebuffer_t` structures and access pixels in various formats. ** link:rouziclib/graphics/pixel_conv.c[pixel_conv.c] / link:rouziclib/graphics/pixel_conv.h[pixel_conv.h] + Conversions between different pixel formats, with Intel x86 SIMD versions. ** link:rouziclib/graphics/srgb.c[srgb.c] / link:rouziclib/graphics/srgb.h[srgb.h] + Conversions between linear valued and gamma-compressed sRGB. ** link:rouziclib/graphics/sqrgb.c[sqrgb.c] / link:rouziclib/graphics/sqrgb.h[sqrgb.h] + Conversions for the 10-bit square root pixel format. ** link:rouziclib/graphics/yuv.c[yuv.c] / link:rouziclib/graphics/yuv.h[yuv.h] + YUV conversions. ** link:rouziclib/graphics/colour.c[colour.c] / link:rouziclib/graphics/colour.h[colour.h] + Colour operations, inversion, HSL conversions, channel access, out-of-gamut desaturation and luminosity adjustment. ** link:rouziclib/graphics/blending.c[blending.c] / link:rouziclib/graphics/blending.h[blending.h] and link:rouziclib/graphics/blending_struct.h[blending_struct.h] + Pixel blending functions. ** link:rouziclib/graphics/blit.c[blit.c] / link:rouziclib/graphics/blit.h[blit.h] + Image blitting with no scaling, flat-top filtering or bilinear interpolation and rotation. ** link:rouziclib/graphics/drawline.c[drawline.c] / link:rouziclib/graphics/drawline.h[drawline.h] + Draw Gaussian-antialiased thin lines and Gaussian dots. Also contains a generic Bresenham line drawing function that takes a function pointer to edit a pixel in custom ways. ** link:rouziclib/graphics/drawrect.c[drawrect.c] / link:rouziclib/graphics/drawrect.h[drawrect.h] + Draw Gaussian-antialiased full or dark rectangles. ** link:rouziclib/graphics/drawprimitives.c[drawprimitives.c] / link:rouziclib/graphics/drawprimitives.h[drawprimitives.h] + Draw Gaussian-antialiased circles (full or hollow), hollow rectangles and chamfered (angular) rectangles, rounded rectangles, dashed lines, Gaussian gradients and dots, triangles and mouse cursors. ** link:rouziclib/graphics/drawqueue.c[drawqueue.c] / link:rouziclib/graphics/drawqueue.h[drawqueue.h] + Drawing queue rendering system. ** link:rouziclib/graphics/drawqueue[drawqueue/] *** link:rouziclib/graphics/drawqueue/drawqueue_soft.c[drawqueue_soft.c] / link:rouziclib/graphics/drawqueue/drawqueue_soft.h[drawqueue_soft.h] + Render drawing queue on the CPU with multiple threads using SIMD instructions. Used as a fallback for the OpenCL renderer. The 3 files that follow implement the functions needed by this system to draw rectangles, lines and images. *** link:rouziclib/graphics/drawqueue/drawrect.c[drawrect.c] / link:rouziclib/graphics/drawqueue/drawrect.h[drawrect.h] + *** link:rouziclib/graphics/drawqueue/drawline.c[drawline.c] / link:rouziclib/graphics/drawqueue/drawline.h[drawline.h] + *** link:rouziclib/graphics/drawqueue/blit.c[blit.c] / link:rouziclib/graphics/drawqueue/blit.h[blit.h] + *** link:rouziclib/graphics/drawqueue/opencl[opencl/] + The files below make up the OpenCL version of my drawing queue renderer. **** link:rouziclib/graphics/drawqueue/opencl/bits.cl[bits.cl] + Read bits in a binary stream. Used for decoding my compressed texture format which uses 3 bits per pixel. **** link:rouziclib/graphics/drawqueue/opencl/blending.cl[blending.cl] + Various blending modes available when closing a bracket. **** link:rouziclib/graphics/drawqueue/opencl/blit.cl[blit.cl] + Read textures in various formats and blit them with flat-top filtering or bilinear interpolation and rotation. **** link:rouziclib/graphics/drawqueue/opencl/colour.cl[colour.cl] + CIELab L, YUV and HSL conversions, colour matrix and transfer curves. **** link:rouziclib/graphics/drawqueue/opencl/drawcircle.cl[drawcircle.cl] + Draw full and hollow Gaussian-antialiased circles. **** link:rouziclib/graphics/drawqueue/opencl/drawline.cl[drawline.cl] + Draw Gaussian-antialiased thin lines and Gaussian dots. **** link:rouziclib/graphics/drawqueue/opencl/drawqueue.cl[drawqueue.cl] + Includes all the other .cl files and is compiled to link:rouziclib/graphics/drawqueue/opencl/drawqueue.cl.h[drawqueue.cl.h] for inclusion in the program, which then gets compiled by the OpenCL compiler at run time to generate the OpenCL kernels. Reads the buffers sent from the host and interprets them to execute the drawing functions. **** link:rouziclib/graphics/drawqueue/opencl/drawrect.cl[drawrect.cl] + Draw full Gaussian-antialiased rectangles, either additively or with multiplication to make dark rectangles. Can also add a plain colour to a rendering sector which is used in optimising the drawing of the insides of full rectangles and circles far from the edges. **** link:rouziclib/graphics/drawqueue/opencl/gaussian.cl[gaussian.cl] + Fast error function (`erf()`) approximation. **** link:rouziclib/graphics/drawqueue/opencl/rand.cl[rand.cl] + MINSTD-based PRNG used to generate a practically non-repeating Gaussian noise texture used for dithering. **** link:rouziclib/graphics/drawqueue/opencl/srgb.cl[srgb.cl] + sRGB conversions, out-of-gamut colour desaturation and Gaussian dithering and optional quantisation (with `max_s`) to simulate lower colour bit depths. **** link:rouziclib/graphics/drawqueue/opencl/trig.cl[trig.cl] + Arccos and arcsin approximations. ** link:rouziclib/graphics/draw_effects.c[draw_effects.c] / link:rouziclib/graphics/draw_effects.h[draw_effects.h] + Apply effects to the image using the drawqueue system. ** link:rouziclib/graphics/processing.c[processing.c] / link:rouziclib/graphics/processing.h[processing.h] + Apply Gaussian blur to an image, scale an image using flat-top filtering, interpolate a pixel with bilinear interpolation and apply operations to pixels. ** link:rouziclib/graphics/mipmap.c[mipmap.c] / link:rouziclib/graphics/mipmap.h[mipmap.h] + Turns a simple raster image into a multi-level tiled mipmap. ** link:rouziclib/graphics/cl_memory.c[cl_memory.c] / link:rouziclib/graphics/cl_memory.h[cl_memory.h] + Manage the memory buffer used to exchange data by the drawqueue system. For instance an image that must be displayed on screen will have its pixel data copied to the big buffer, then when using OpenCL the updated parts of that buffer will be copied to the GPU so that a GPU-side mirror of this buffer is maintained and the image can be displayed using the OpenCL code on the GPU. ** link:rouziclib/graphics/texture_compression.c[texture_compression.c] / link:rouziclib/graphics/texture_compression.h[texture_compression.h] + My original texture compression. It compresses each block of pixels to 3-bits and uses two colours for each block, giving 8 possible colours being interpolated between those two colours. * link:rouziclib/vector[vector/] ** link:rouziclib/vector/vector.c[vector.c] / link:rouziclib/vector/vector.h[vector.h] and link:rouziclib/vector/vector_struct.h[vector_struct.h] + How vector objects (represented as a collection of thin lines) are represented and manipulated. ** link:rouziclib/vector/polyline.c[polyline.c] / link:rouziclib/vector/polyline.h[polyline.h] + A crude tool to create vector objects by mouse. * link:rouziclib/text[text/] ** link:rouziclib/text/unicode_data.c[unicode_data.c] / link:rouziclib/text/unicode_data.h[unicode_data.h] + Gives access to Unicode data about each Unicode codepoint. ** link:rouziclib/text/unicode.c[unicode.c] / link:rouziclib/text/unicode.h[unicode.h] + Functions to deal with UTF-8 or UTF-16 strings. ** link:rouziclib/text/unicode_bidi.c[unicode_bidi.c] / link:rouziclib/text/unicode_bidi.h[unicode_bidi.h] + Used to decompose a UTF-8 string into sections depending on the directionality of its codepoints (for instance when mixing Arabic, Latin and digits). ** link:rouziclib/text/unicode_arabic.c[unicode_arabic.c] / link:rouziclib/text/unicode_arabic.h[unicode_arabic.h] + Allows the text renderer to know which form of an Arabic letter to use. ** link:rouziclib/text/parse.c[parse.c] / link:rouziclib/text/parse.h[parse.h] + Various text parsing tools to skip parts of a string, extract fields according to separators, convert my dozenal number format (for instance ""1;4"" becomes 1.333...), count lines, find lines, convert a multiline string into an array of lines, case insensitive string search, `memmem()` replacement where needed, pattern finding (like date-time or timestamps), parse files with XY vector data, parse XML fields, parse musical notes such as ""G#3+02.1"". ** link:rouziclib/text/format.c[format.c] / link:rouziclib/text/format.h[format.h] + Various string printing functions to print large numbers in a readable way, print dozenal numbers, print English ordinals (like 1st, 4th, 11th, 22nd), convert short months like ""Jan"" to long months like ""January"", transform date strings, print compilation and compiler information, indent lines, print time, print duration in a nice readable way (like ""1 day and 8.3 hours""), print timestamps, convert text to a C string literal with proper escaping and conversion of a file to a C header that contains a string representing the contents of the file. ** link:rouziclib/text/string.c[string.c] / link:rouziclib/text/string.h[string.h] + String utilities to copy strings, replace all instances of a character in a string, convert a string to lowercase, alternatives to `sprintf()` with options to allocate, reallocate and append, string line insertion or replacement. ** link:rouziclib/text/edit.c[edit.c] / link:rouziclib/text/edit.h[edit.h] and link:rouziclib/general/textedit_struct.h[textedit_struct.h] + Text editor GUI control with undo functionality. ** link:rouziclib/text/undo.c[undo.c] / link:rouziclib/text/undo.h[undo.h] + Undo functionality of text editor controls. ** link:rouziclib/text/history.c[history.c] / link:rouziclib/text/history.h[history.h] + I have no idea what this is, wtf. * link:rouziclib/vector_type[vector_type/] ** link:rouziclib/vector_type/vector_type.c[vector_type.c] / link:rouziclib/vector_type/vector_type.h[vector_type.h] and link:rouziclib/vector_type/vector_type_struct.h[vector_type_struct.h] + Mainly contains functions to retrieve glyphs from codepoints. ** link:rouziclib/vector_type/make_font.c[make_font.c] / link:rouziclib/vector_type/make_font.h[make_font.h] + Generates the vector typeface from the markup. ** link:rouziclib/vector_type/draw.c[draw.c] / link:rouziclib/vector_type/draw.h[draw.h] + Draw a string on screen using the vector typeface. ** link:rouziclib/vector_type/stats.c[stats.c] / link:rouziclib/vector_type/stats.h[stats.h] + Functions to obtain the width of glyphs, and using those find the width of words and lines, which are then used to fit strings into rectangles. ** link:rouziclib/vector_type/fit.c[fit.c] / link:rouziclib/vector_type/fit.h[fit.h] + Fit strings into rectangles with line breaks either to maximise the size of the letters or to break the lines at a given threshold. Currently only works with strings that don't already contain line breaks, except for `draw_string_bestfit_asis()` which doesn't add line breaks. ** link:rouziclib/vector_type/cjk.c[cjk.c] / link:rouziclib/vector_type/cjk.h[cjk.h] + Generates CJK glyphs by combining strokes using a list of combinations. Doesn't really produce anything readable. ** link:rouziclib/vector_type/insert_rect.c[insert_rect.c] / link:rouziclib/vector_type/insert_rect.h[insert_rect.h] + An insert rect is a space in a string to be drawn on screen, and that space has its coordinates reported so that they can be used to insert an interface element where the space is. The width of the space is specified by combining private use Unicode codepoints that each represent a different spacing, the sum of which is the width of the space, and then a variation selector character which represents an index in an array. So for example by using the character that represents a space of 36 units, followed by the character that represents 3 units, followed by the character that represents an index of 0, I can make a space 39 units wide in some text and then by querying the insert rect at index 0 get the on-screen coordinates for that space so that I can place something there. I use it mainly for inserting text edit controls to enter a value in the middle of some text, so the text input field is automatically adjusted to be the right size and position to fit in perfectly. * link:rouziclib/gui[gui/] ** link:rouziclib/gui/zoom.c[zoom.c] / link:rouziclib/gui/zoom.h[zoom.h] and link:rouziclib/gui/zoom_struct.h[zoom_struct.h] + Zoom-scroll system, with conversion between ""world coordinates"" (positions on the infinite plane) and screen coordinates and handling of the mouse to scroll around, zoom in and out, reset the view or change the zoom level and focus programatically. The GUI system relies on this system. ** link:rouziclib/gui/focus.c[focus.c] / link:rouziclib/gui/focus.h[focus.h] and link:rouziclib/gui/focus_struct.h[focus_struct.h] + Can affect the drawing thickness and brightness of drawn elements to simulate a camera being out of focus, albeit with Gaussian blur rather than a circular kernel. ** link:rouziclib/gui/positioning.c[positioning.c] / link:rouziclib/gui/positioning.h[positioning.h] + Convert local coordinates to world coordinates using an offset and scale. This is used when making interface elements fit into an area. ** link:rouziclib/gui/layout.c[layout.c] / link:rouziclib/gui/layout.h[layout.h] + Manage control grids. ** link:rouziclib/gui/drawelements.c[drawelements.c] / link:rouziclib/gui/drawelements.h[drawelements.h] + Drawing functions for various interface elements. ** link:rouziclib/gui/visualisations.c[visualisations.c] / link:rouziclib/gui/visualisations.h[visualisations.h] + Draw a bar graph. ** link:rouziclib/gui/inputprocessing.c[inputprocessing.c] / link:rouziclib/gui/inputprocessing.h[inputprocessing.h] and link:rouziclib/gui/inputprocessing_struct.h[inputprocessing_struct.h] + The core of the GUI system, this is how controls are identified when hovered or clicked and how each type of control processes mouse inputs. ** link:rouziclib/gui/knob_functions.c[knob_functions.c] / link:rouziclib/gui/knob_functions.h[knob_functions.h] + Knobs can use a few different functions so that they don't have to always be linear. ** link:rouziclib/gui/controls.c[controls.c] / link:rouziclib/gui/controls.h[controls.h] and link:rouziclib/gui/controls_struct.h[controls_struct.h] + How the basic GUI controls are created. ** link:rouziclib/gui/control_array.c[control_array.c] / link:rouziclib/gui/control_array.h[control_array.h] + Program arrays of controls. ** link:rouziclib/gui/selection.c[selection.c] / link:rouziclib/gui/selection.h[selection.h] + Generic selection logic, the kind you expect when selecting files in a folder. ** link:rouziclib/gui/make_gui.c[make_gui.c] / link:rouziclib/gui/make_gui.h[make_gui.h] + Make a GUI from layout markup, which can be generated by using the toolbar found in the next file. Contains functions to implement every element type using the data in a layout structure and various functions to modify them. ** link:rouziclib/gui/editor_toolbar.c[editor_toolbar.c] / link:rouziclib/gui/editor_toolbar.h[editor_toolbar.h] + Toolbar to create and modify GUI layouts. ** link:rouziclib/gui/floating_window.c[floating_window.c] / link:rouziclib/gui/floating_window.h[floating_window.h] + Create and handle floating windows with a draggable title bar, a resizing control, a pinning control and a closing button. * link:rouziclib/fileio[fileio/] ** link:rouziclib/fileio/bits.c[bits.c] / link:rouziclib/fileio/bits.h[bits.h] + Read, set or manipulate bits in a bit stream. ** link:rouziclib/fileio/open.c[open.c] / link:rouziclib/fileio/open.h[open.h] + `fopen()` wrapper that takes UTF-8 paths, with another version that can create any folder needed to make the file being opened writable, query a file's size, load a file into memory, optionally with conversion of DOS line endings, save a whole buffer or string or array of strings to file, count lines in a text file, check if a file or folder exists. ** link:rouziclib/fileio/endian.c[endian.c] / link:rouziclib/fileio/endian.h[endian.h] + Functions to load or write 8 to 64 bit integers in little or big endian to and from memory, file or generic buffer. By default to speed things up the platform is assumed to be little endian, this can be changed by defining `RL_DONT_ASSUME_LITTLE_ENDIAN`. ** link:rouziclib/fileio/image.c[image.c] / link:rouziclib/fileio/image.h[image.h] + Convert images between different pixel formats, load and save images and image tiles in various formats, partly using https://github.com/nothings/stb/blob/master/stb_image.h[stb_image] and https://github.com/nothings/stb/blob/master/stb_image_write.h[stb_image_write]. ** link:rouziclib/fileio/image_bmp.c[image_bmp.c] / link:rouziclib/fileio/image_bmp.h[image_bmp.h] + Save BMP images. ** link:rouziclib/fileio/image_tiff.c[image_tiff.c] / link:rouziclib/fileio/image_tiff.h[image_tiff.h] + Load TIFF files in 8, 16 and 32-bit bits per channel, with either no compression or LZW compression. Save images to 32-bit per channel TIFF files. ** link:rouziclib/fileio/image_tiff_lzw.c[image_tiff_lzw.c] / link:rouziclib/fileio/image_tiff_lzw.h[image_tiff_lzw.h] + TIFF LZW decoder. ** link:rouziclib/fileio/image_fts.c[image_fts.c] / link:rouziclib/fileio/image_fts.h[image_fts.h] + Load NASA FITS images. Only tested with SOHO mission images. ** link:rouziclib/fileio/image_screen.c[image_screen.c] / link:rouziclib/fileio/image_screen.h[image_screen.h] + Function to take screenshots of the main display on Windows. ** link:rouziclib/fileio/sound_format.c[sound_format.c] / link:rouziclib/fileio/sound_format.h[sound_format.h] + Convert between different sound sample formats and channel layouts. ** link:rouziclib/fileio/sound_aiff.c[sound_aiff.c] / link:rouziclib/fileio/sound_aiff.h[sound_aiff.h] + Load and save AIFF sound files. ** link:rouziclib/fileio/sound_wav.c[sound_wav.c] / link:rouziclib/fileio/sound_wav.h[sound_wav.h] + Load and save WAVE sound files. ** link:rouziclib/fileio/path.c[path.c] / link:rouziclib/fileio/path.h[path.h] + Transform file paths to remove, extract or append elements, make appdata paths to save configuration files, check that a path is to an image or video file or change the current working directory. ** link:rouziclib/fileio/dir.c[dir.c] / link:rouziclib/fileio/dir.h[dir.h] and link:rouziclib/fileio/dir_struct.h[dir_struct.h] + Load a directory to any depth as a tree using a modified version of link:rouziclib/libraries/dirent.c[dirent.c] / link:rouziclib/libraries/dirent.h[dirent.h] (I fixed some bugs from the original this was based on and reorganised it a bit) on Windows. Query volumes and their free space on Windows. ** link:rouziclib/fileio/file_management.c[file_management.c] / link:rouziclib/fileio/file_management.h[file_management.h] + Create symbolic links, folders (even with multiple depths), move, copy, remove files and folders, open files or URLs in whatever program they're usually opened, show files in Explorer (Windows). ** link:rouziclib/fileio/process.c[process.c] / link:rouziclib/fileio/process.h[process.h] + Launch another process (Windows). Load the program's commandline arguments `argv` at any point in the program. ** link:rouziclib/fileio/fileball.c[fileball.c] / link:rouziclib/fileio/fileball.h[fileball.h] and link:rouziclib/fileio/fileball_struct.h[fileball_struct.h] + Manage fileball archives, a simple format to pack many files into one and optionally compress them using Deflate (via https://github.com/richgel999/miniz[miniz]). This is used to pack the many files that make up the vector typeface into a C header with compression. ** link:rouziclib/fileio/prefs.c[prefs.c] / link:rouziclib/fileio/prefs.h[prefs.h] + Preference management system. This is what I use to load and save preferences in my programs. Besides being quite elegant and readable it can be used independently by different parts of a program without any awareness of what the other parts do. ** link:rouziclib/fileio/dialog.c[dialog.c] / link:rouziclib/fileio/dialog.h[dialog.h] + Open and Save file dialogs on Windows and macOS. Both platforms use the same filter format. ** link:rouziclib/fileio/ffmpeg_sound_player.c[ffmpeg_sound_player.c] / link:rouziclib/fileio/ffmpeg_sound_player.h[ffmpeg_sound_player.h] + Callback to load and play an audio stream using FFMPEG. The seeking leaves a bit to be desired, it can be quite slow compared to the video stream seeking and I don't know why. * link:rouziclib/network[network/] + TCP and HTTP socket-based code. Not very useful anymore since everything requires HTTPS. ** link:rouziclib/network/network.c[network.c] / link:rouziclib/network/network.h[network.h] + ** link:rouziclib/network/http.c[http.c] / link:rouziclib/network/http.h[http.h] + * link:rouziclib/libraries[libraries/] ** link:rouziclib/libraries/opencl.c[opencl.c] / link:rouziclib/libraries/opencl.h[opencl.h] and link:rouziclib/libraries/opencl_struct.h[opencl_struct.h] + OpenCL code for initialising a context, compiling a kernel and more. Relies on https://github.com/martijnberger/clew[CLEW]. ** link:rouziclib/libraries/sdl.c[sdl.c] / link:rouziclib/libraries/sdl.h[sdl.h] + SDL2 code to get display and driver information, handle various types of events, control the mouse cursor, initialise graphics and audio, use the clipboard, poll drag-and-drop file events. ** link:rouziclib/libraries/vulkan.c[vulkan.c] / link:rouziclib/libraries/vulkan.h[vulkan.h] and link:rouziclib/libraries/vulkan_struct.h[vulkan_struct.h] + Aborted attempt to port my OpenCL system to Vulkan. Vulkan is rather complicated. ** link:rouziclib/libraries/clfft.c[clfft.c] / link:rouziclib/libraries/clfft.h[clfft.h] + Code for dealing with https://github.com/clMathLibraries/clFFT[clFFT]. ** link:rouziclib/libraries/ffmpeg.c[ffmpeg.c] / link:rouziclib/libraries/ffmpeg.h[ffmpeg.h] + FFMPEG-based decoding. ** link:rouziclib/libraries/ffmpeg_enc.c[ffmpeg_enc.c] / link:rouziclib/libraries/ffmpeg_enc.h[ffmpeg_enc.h] + FFMPEG-based encoding (video-only, no audio). ** link:rouziclib/libraries/opencv.c[opencv.c] / link:rouziclib/libraries/opencv.h[opencv.h] + Decode videos and access webcam images using OpenCV. ** link:rouziclib/libraries/devil.c[devil.c] / link:rouziclib/libraries/devil.h[devil.h] + Load images with DevIL. I don't use this anymore. ** link:rouziclib/libraries/libsndfile.c[libsndfile.c] / link:rouziclib/libraries/libsndfile.h[libsndfile.h] + Open files for libsndfile. I also don't use this anymore. ** link:rouziclib/libraries/libraw.c[libraw.c] / link:rouziclib/libraries/libraw.h[libraw.h] + Load RAW photographs with LibRAW in different ways. ** link:rouziclib/libraries/libjpeg.c[libjpeg.c] / link:rouziclib/libraries/libjpeg.h[libjpeg.h] + Load JPEG with libJPEG and access DCT blocks. ** link:rouziclib/libraries/libstb_image.c[libstb_image.c] / link:rouziclib/libraries/libstb_image.h[libstb_image.h] + Load and save images with https://github.com/nothings/stb/blob/master/stb_image.h[stb_image]. ** link:rouziclib/libraries/libstb_vorbis.c[libstb_vorbis.c] / link:rouziclib/libraries/libstb_vorbis.h[libstb_vorbis.h] + Load OGG sound files with https://github.com/nothings/stb/blob/master/stb_vorbis.c[stb_vorbis]. ** link:rouziclib/libraries/libminimp3.c[libminimp3.c] / link:rouziclib/libraries/libminimp3.h[libminimp3.h] + Load MP3s with https://github.com/lieff/minimp3/blob/master/minimp3.h[minimp3]. ** link:rouziclib/libraries/libdr_flac.c[libdr_flac.c] / link:rouziclib/libraries/libdr_flac.h[libdr_flac.h] + Load FLAC sound files with https://github.com/mackron/dr_libs/blob/master/dr_flac.h[dr_flac]. ** link:rouziclib/libraries/zlib.c[zlib.c] / link:rouziclib/libraries/zlib.h[zlib.h] + Compress or decompress using the Deflate compression using either zlib or https://github.com/richgel999/miniz[miniz] (miniz is built in rouziclib so there's no reason to use zlib). ** link:rouziclib/libraries/mpfr.c[mpfr.c] / link:rouziclib/libraries/mpfr.h[mpfr.h] + Macros to make MPFR syntax simpler (I used to have problems typing `mpfr_` correctly so I changed it to `r_`) and some other functions I need. ** link:rouziclib/libraries/fftpack.c[fftpack.c] / link:rouziclib/libraries/fftpack.h[fftpack.h] + Older FFTPACK code, only handles real-to-real transforms with no negative frequencies. ** link:rouziclib/libraries/cfftpack.c[cfftpack.c] / link:rouziclib/libraries/cfftpack.h[cfftpack.h] + https://github.com/zywina/cfftpack[FFTPACK] code with both single and double precision available at the same time (I modified the code it's based on for this purpose). Does 1D and 2D complex-binned FFTs with negative frequencies, padding, conversion betwen real and complex bins, mixing single and double precision, padding, reallocation, and recompution or reallocation plans only as needed. ** link:rouziclib/libraries/tinyexpr.c[tinyexpr.c] / link:rouziclib/libraries/tinyexpr.h[tinyexpr.h] + https://github.com/codeplea/tinyexpr[TinyExpr] (logic branch) code which I use for many purposes, like parsing markup, knob text input evaluation, making graphing and image calculators. I added several of the functions I need and made `etof()` and `etoi()` as equivalents to `atof()` and `atoi()` but with mathematical expressions rather than simple number strings. ** link:rouziclib/libraries/libcurl.c[libcurl.c] / link:rouziclib/libraries/libcurl.h[libcurl.h] + cURL code to get files through HTTPS. I can't seem to get authentication right. ** link:rouziclib/libraries/libminiaudio.c[libminiaudio.c] / link:rouziclib/libraries/libminiaudio.h[libminiaudio.h] + Adds https://github.com/mackron/miniaudio[MiniAudio]. Excluded by default due to the code size ** link:rouziclib/libraries/openal.c[openal.c] / link:rouziclib/libraries/openal.h[openal.h] + Adds OpenAL. ** link:rouziclib/libraries/emscripten.c[emscripten.c] / link:rouziclib/libraries/emscripten.h[emscripten.h] / link:rouziclib/libraries/emscripten.js[emscripten.js] + Emscripten-specific code. ** link:rouziclib/libraries/orig[orig/] + This where I put libraries I use from third parties. Several of them have modifications which are described in the link:rouziclib/libraries/orig/update_notes.txt[update notes]. ",12094,True,2937.6494895478327,median "= v1beta1.CertificateSigningRequest {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] Describes a certificate signing request == 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:
extra:
[string]:
groups:
- [string]:
request:
uid:
usages:
- [string]:
username:
status:
certificate:
conditions:
- lastUpdateTime:
message:
reason:
type:
++++ == Operations [[Post-apis-certificates.k8s.io-v1beta1-certificatesigningrequests]] === Create a CertificateSigningRequest Create a CertificateSigningRequest ==== HTTP request ---- POST /apis/certificates.k8s.io/v1beta1/certificatesigningrequests HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""CertificateSigningRequest"", ""apiVersion"": ""certificates.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/certificates.k8s.io/v1beta1/certificatesigningrequests <<'EOF' { ""kind"": ""CertificateSigningRequest"", ""apiVersion"": ""certificates.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.CertificateSigningRequest |=== ==== 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|v1beta1.CertificateSigningRequest |201 Created|v1beta1.CertificateSigningRequest |202 Accepted|v1beta1.CertificateSigningRequest |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-certificates.k8s.io-v1beta1-certificatesigningrequests-name]] === Get a CertificateSigningRequest Read the specified CertificateSigningRequest ==== HTTP request ---- GET /apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$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/apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the CertificateSigningRequest |=== ==== 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|v1beta1.CertificateSigningRequest |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-certificates.k8s.io-v1beta1-certificatesigningrequests]] === Get all CertificateSigningRequests List or watch objects of kind CertificateSigningRequest ==== HTTP request ---- GET /apis/certificates.k8s.io/v1beta1/certificatesigningrequests 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/apis/certificates.k8s.io/v1beta1/certificatesigningrequests ---- ==== 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|v1beta1.CertificateSigningRequestList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-certificates.k8s.io-v1beta1-watch-certificatesigningrequests-name]] === Watch a CertificateSigningRequest Watch changes to an object of kind CertificateSigningRequest ==== HTTP request ---- GET /apis/certificates.k8s.io/v1beta1/watch/certificatesigningrequests/$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/apis/certificates.k8s.io/v1beta1/watch/certificatesigningrequests/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the CertificateSigningRequest |=== ==== 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-apis-certificates.k8s.io-v1beta1-watch-certificatesigningrequests]] === Watch all CertificateSigningRequests Watch individual changes to a list of CertificateSigningRequest ==== HTTP request ---- GET /apis/certificates.k8s.io/v1beta1/watch/certificatesigningrequests 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/apis/certificates.k8s.io/v1beta1/watch/certificatesigningrequests ---- ==== 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-apis-certificates.k8s.io-v1beta1-certificatesigningrequests-name]] === Update a CertificateSigningRequest Replace the specified CertificateSigningRequest ==== HTTP request ---- PUT /apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""CertificateSigningRequest"", ""apiVersion"": ""certificates.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME <<'EOF' { ""kind"": ""CertificateSigningRequest"", ""apiVersion"": ""certificates.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.CertificateSigningRequest |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the CertificateSigningRequest |=== ==== 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|v1beta1.CertificateSigningRequest |201 Created|v1beta1.CertificateSigningRequest |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-certificates.k8s.io-v1beta1-certificatesigningrequests-name]] === Patch a CertificateSigningRequest Partially update the specified CertificateSigningRequest ==== HTTP request ---- PATCH /apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$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/apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$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 CertificateSigningRequest |=== ==== 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|v1beta1.CertificateSigningRequest |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-apis-certificates.k8s.io-v1beta1-certificatesigningrequests-name]] === Delete a CertificateSigningRequest Delete a CertificateSigningRequest ==== HTTP request ---- DELETE /apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$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/apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$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 CertificateSigningRequest |=== ==== 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-apis-certificates.k8s.io-v1beta1-certificatesigningrequests]] === Delete all CertificateSigningRequests Delete collection of CertificateSigningRequest ==== HTTP request ---- DELETE /apis/certificates.k8s.io/v1beta1/certificatesigningrequests 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/apis/certificates.k8s.io/v1beta1/certificatesigningrequests ---- ==== 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 [[Put-apis-certificates.k8s.io-v1beta1-certificatesigningrequests-name-approval]] === Update approval of a CertificateSigningRequest Replace approval of the specified CertificateSigningRequest ==== HTTP request ---- PUT /apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME/approval HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""CertificateSigningRequest"", ""apiVersion"": ""certificates.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME/approval <<'EOF' { ""kind"": ""CertificateSigningRequest"", ""apiVersion"": ""certificates.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.CertificateSigningRequest |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the CertificateSigningRequest |=== ==== 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|v1beta1.CertificateSigningRequest |201 Created|v1beta1.CertificateSigningRequest |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-certificates.k8s.io-v1beta1-certificatesigningrequests-name-status]] === Get status of a CertificateSigningRequest Read status of the specified CertificateSigningRequest ==== HTTP request ---- GET /apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME/status 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/apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME/status ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the CertificateSigningRequest |=== ==== 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|v1beta1.CertificateSigningRequest |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Put-apis-certificates.k8s.io-v1beta1-certificatesigningrequests-name-status]] === Update status of a CertificateSigningRequest Replace status of the specified CertificateSigningRequest ==== HTTP request ---- PUT /apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME/status HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""CertificateSigningRequest"", ""apiVersion"": ""certificates.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME/status <<'EOF' { ""kind"": ""CertificateSigningRequest"", ""apiVersion"": ""certificates.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.CertificateSigningRequest |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the CertificateSigningRequest |=== ==== 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|v1beta1.CertificateSigningRequest |201 Created|v1beta1.CertificateSigningRequest |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-certificates.k8s.io-v1beta1-certificatesigningrequests-name-status]] === Patch status of a CertificateSigningRequest Partially update status of the specified CertificateSigningRequest ==== HTTP request ---- PATCH /apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME/status 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/apis/certificates.k8s.io/v1beta1/certificatesigningrequests/$NAME/status <<'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 CertificateSigningRequest |=== ==== 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|v1beta1.CertificateSigningRequest |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 ",12047,False,2308.656245069248,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]); } } std::exception_ptr eptr; #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 (...) { #pragma omp critical { eptr = std::current_exception(); } } // 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; } } try { if (eptr) { std::rethrow_exception(eptr); } } catch (const std::exception &e) { this->_logger->error(std::string(""Libtorch error: "") + e.what()); throw MLLibInternalException(std::string(""Libtorch error: "") + e.what()); } // 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 ",16274,True,2740.775042013417,median "/* Firmata is a generic protocol for communicating with microcontrollers from software on a host computer. It is intended to work with any host computer software package. To download a host software package, please click on the following link to open the list of Firmata client libraries in your default browser. https://github.com/firmata/arduino#firmata-client-libraries Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See file LICENSE.txt for further informations on licensing terms. Last updated October 16th, 2016 */ #include #include #include //************************************************************************************************************************************************************************************************* #define D0 2 // Le bit LSB de l'dentifiant. c'est une valeur input #define D1 3 // Le bit MSB de l'dentifiant. c'est une valeur input #define ACK 4 // Le bit didié pour confirmer la réception des données D0 et D1, en envoyant HIGH /* D1 D0 ->(valeur) * 0 0 -> NULL * 0 1 -> oussama * 1 0 -> ahal * 1 1 -> Inconnu */ //************************************************************************************************************************************************************************************************* #define I2C_WRITE B00000000 #define I2C_READ B00001000 #define I2C_READ_CONTINUOUSLY B00010000 #define I2C_STOP_READING B00011000 #define I2C_READ_WRITE_MODE_MASK B00011000 #define I2C_10BIT_ADDRESS_MODE_MASK B00100000 #define I2C_END_TX_MASK B01000000 #define I2C_STOP_TX 1 #define I2C_RESTART_TX 0 #define I2C_MAX_QUERIES 8 #define I2C_REGISTER_NOT_SPECIFIED -1 // the minimum interval for sampling analog input #define MINIMUM_SAMPLING_INTERVAL 1 //************************************************************************************************************************************************************************************************* #define lux_Pin A0 //entrée analogique, le pin de lecture pour la photorésistance float lux_Value; // la variable dont la valeur de la photorésistance sera stockée à chaque fois tout le lent de l'exécution de ce programme //************************************************************************************************************************************************************************************************* /*============================================================================== * GLOBAL VARIABLES *============================================================================*/ #ifdef FIRMATA_SERIAL_FEATURE SerialFirmata serialFeature; #endif /* analog inputs */ int analogInputsToReport = 0; // bitwise array to store pin reporting /* digital input ports */ byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent /* pins configuration */ byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else /* timer variables */ unsigned long currentMillis; // store the current value from millis() unsigned long previousMillis; // for comparison with currentMillis unsigned int samplingInterval = 19; // how often to run the main loop (in ms) /* i2c data */ struct i2c_device_info { byte addr; int reg; byte bytes; byte stopTX; }; /* for i2c read continuous more */ i2c_device_info query[I2C_MAX_QUERIES]; byte i2cRxData[64]; boolean isI2CEnabled = false; signed char queryIndex = -1; // default delay time between i2c read request and Wire.requestFrom() unsigned int i2cReadDelayTime = 0; Servo servos[MAX_SERVOS]; byte servoPinMap[TOTAL_PINS]; byte detachedServos[MAX_SERVOS]; byte detachedServoCount = 0; byte servoCount = 0; boolean isResetting = false; // Forward declare a few functions to avoid compiler errors with older versions // of the Arduino IDE. void setPinModeCallback(byte, int); void reportAnalogCallback(byte analogPin, int value); void sysexCallback(byte, byte, byte*); /* utility functions */ void wireWrite(byte data) { #if ARDUINO >= 100 Wire.write((byte)data); #else Wire.send(data); #endif } byte wireRead(void) { #if ARDUINO >= 100 return Wire.read(); #else return Wire.receive(); #endif } /*============================================================================== * FUNCTIONS *============================================================================*/ void attachServo(byte pin, int minPulse, int maxPulse) { if (servoCount < MAX_SERVOS) { // reuse indexes of detached servos until all have been reallocated if (detachedServoCount > 0) { servoPinMap[pin] = detachedServos[detachedServoCount - 1]; if (detachedServoCount > 0) detachedServoCount--; } else { servoPinMap[pin] = servoCount; servoCount++; } if (minPulse > 0 && maxPulse > 0) { servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); } else { servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); } } else { Firmata.sendString(""Max servos attached""); } } void detachServo(byte pin) { servos[servoPinMap[pin]].detach(); // if we're detaching the last servo, decrement the count // otherwise store the index of the detached servo if (servoPinMap[pin] == servoCount && servoCount > 0) { servoCount--; } else if (servoCount > 0) { // keep track of detached servos because we want to reuse their indexes // before incrementing the count of attached servos detachedServoCount++; detachedServos[detachedServoCount - 1] = servoPinMap[pin]; } servoPinMap[pin] = 255; } void enableI2CPins() { byte i; // is there a faster way to do this? would probaby require importing // Arduino.h to get SCL and SDA pins for (i = 0; i < TOTAL_PINS; i++) { if (IS_PIN_I2C(i)) { // mark pins as i2c so they are ignore in non i2c data requests setPinModeCallback(i, PIN_MODE_I2C); } } isI2CEnabled = true; Wire.begin(); } /* disable the i2c pins so they can be used for other functions */ void disableI2CPins() { isI2CEnabled = false; // disable read continuous mode for all devices queryIndex = -1; } void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { // allow I2C requests that don't require a register read // for example, some devices using an interrupt pin to signify new data available // do not always require the register read so upon interrupt you call Wire.requestFrom() if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { Wire.beginTransmission(address); wireWrite((byte)theRegister); Wire.endTransmission(stopTX); // default = true // do not set a value of 0 if (i2cReadDelayTime > 0) { // delay is necessary for some devices such as WiiNunchuck delayMicroseconds(i2cReadDelayTime); } } else { theRegister = 0; // fill the register with a dummy value } Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom // check to be sure correct number of bytes were returned by slave if (numBytes < Wire.available()) { Firmata.sendString(""I2C: Too many bytes received""); } else if (numBytes > Wire.available()) { Firmata.sendString(""I2C: Too few bytes received""); } i2cRxData[0] = address; i2cRxData[1] = theRegister; for (int i = 0; i < numBytes && Wire.available(); i++) { i2cRxData[2 + i] = wireRead(); } // send slave address, register and received bytes Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); } void outputPort(byte portNumber, byte portValue, byte forceSend) { // pins not configured as INPUT are cleared to zeros portValue = portValue & portConfigInputs[portNumber]; // only send if the value is different than previously sent if (forceSend || previousPINs[portNumber] != portValue) { Firmata.sendDigitalPort(portNumber, portValue); previousPINs[portNumber] = portValue; } } /* ----------------------------------------------------------------------------- * check all the active digital inputs for change of state, then add any events * to the Serial output queue using Serial.print() */ void checkDigitalInputs(void) { /* Using non-looping code allows constants to be given to readPort(). * The compiler will apply substantial optimizations if the inputs * to readPort() are compile-time constants. */ if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); } // ----------------------------------------------------------------------------- /* sets the pin mode to the correct state and sets the relevant bits in the * two bit-arrays that track Digital I/O and PWM status */ void setPinModeCallback(byte pin, int mode) { if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) return; if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { // disable i2c so pins can be used for other functions // the following if statements should reconfigure the pins properly disableI2CPins(); } if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { detachServo(pin); } } if (IS_PIN_ANALOG(pin)) { reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting } if (IS_PIN_DIGITAL(pin)) { if (mode == INPUT || mode == PIN_MODE_PULLUP) { portConfigInputs[pin / 8] |= (1 << (pin & 7)); } else { portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); } } Firmata.setPinState(pin, 0); switch (mode) { case PIN_MODE_ANALOG: if (IS_PIN_ANALOG(pin)) { if (IS_PIN_DIGITAL(pin)) { pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver #if ARDUINO <= 100 // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups #endif } Firmata.setPinMode(pin, PIN_MODE_ANALOG); } break; case INPUT: if (IS_PIN_DIGITAL(pin)) { pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver #if ARDUINO <= 100 // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups #endif Firmata.setPinMode(pin, INPUT); } break; case PIN_MODE_PULLUP: if (IS_PIN_DIGITAL(pin)) { pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); Firmata.setPinMode(pin, PIN_MODE_PULLUP); Firmata.setPinState(pin, 1); } break; case OUTPUT: if (IS_PIN_DIGITAL(pin)) { if (Firmata.getPinMode(pin) == PIN_MODE_PWM) { // Disable PWM if pin mode was previously set to PWM. digitalWrite(PIN_TO_DIGITAL(pin), LOW); } pinMode(PIN_TO_DIGITAL(pin), OUTPUT); Firmata.setPinMode(pin, OUTPUT); } break; case PIN_MODE_PWM: if (IS_PIN_PWM(pin)) { pinMode(PIN_TO_PWM(pin), OUTPUT); analogWrite(PIN_TO_PWM(pin), 0); Firmata.setPinMode(pin, PIN_MODE_PWM); } break; case PIN_MODE_SERVO: if (IS_PIN_DIGITAL(pin)) { Firmata.setPinMode(pin, PIN_MODE_SERVO); if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { // pass -1 for min and max pulse values to use default values set // by Servo library attachServo(pin, -1, -1); } } break; case PIN_MODE_I2C: if (IS_PIN_I2C(pin)) { // mark the pin as i2c // the user must call I2C_CONFIG to enable I2C for a device Firmata.setPinMode(pin, PIN_MODE_I2C); } break; case PIN_MODE_SERIAL: #ifdef FIRMATA_SERIAL_FEATURE serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); #endif break; default: Firmata.sendString(""Unknown pin mode""); // TODO: put error msgs in EEPROM } // TODO: save status to EEPROM here, if changed } /* * Sets the value of an individual pin. Useful if you want to set a pin value but * are not tracking the digital port state. * Can only be used on pins configured as OUTPUT. * Cannot be used to enable pull-ups on Digital INPUT pins. */ void setPinValueCallback(byte pin, int value) { if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { if (Firmata.getPinMode(pin) == OUTPUT) { Firmata.setPinState(pin, value); digitalWrite(PIN_TO_DIGITAL(pin), value); } } } void analogWriteCallback(byte pin, int value) { if (pin < TOTAL_PINS) { switch (Firmata.getPinMode(pin)) { case PIN_MODE_SERVO: if (IS_PIN_DIGITAL(pin)) servos[servoPinMap[pin]].write(value); Firmata.setPinState(pin, value); break; case PIN_MODE_PWM: if (IS_PIN_PWM(pin)) analogWrite(PIN_TO_PWM(pin), value); Firmata.setPinState(pin, value); break; } } } void digitalWriteCallback(byte port, int value) { byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; if (port < TOTAL_PORTS) { // create a mask of the pins on this port that are writable. lastPin = port * 8 + 8; if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; for (pin = port * 8; pin < lastPin; pin++) { // do not disturb non-digital pins (eg, Rx & Tx) if (IS_PIN_DIGITAL(pin)) { // do not touch pins in PWM, ANALOG, SERVO or other modes if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { pinValue = ((byte)value & mask) ? 1 : 0; if (Firmata.getPinMode(pin) == OUTPUT) { pinWriteMask |= mask; } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { // only handle INPUT here for backwards compatibility #if ARDUINO > 100 pinMode(pin, INPUT_PULLUP); #else // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier pinWriteMask |= mask; #endif } Firmata.setPinState(pin, pinValue); } } mask = mask << 1; } writePort(port, (byte)value, pinWriteMask); } } // ----------------------------------------------------------------------------- /* sets bits in a bit array (int) to toggle the reporting of the analogIns */ //void FirmataClass::setAnalogPinReporting(byte pin, byte state) { //} void reportAnalogCallback(byte analogPin, int value) { if (analogPin < TOTAL_ANALOG_PINS) { if (value == 0) { analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); } else { analogInputsToReport = analogInputsToReport | (1 << analogPin); // prevent during system reset or all analog pin values will be reported // which may report noise for unconnected analog pins if (!isResetting) { // Send pin value immediately. This is helpful when connected via // ethernet, wi-fi or bluetooth so pin states can be known upon // reconnecting. Firmata.sendAnalog(analogPin, analogRead(analogPin)); } } } // TODO: save status to EEPROM here, if changed } void reportDigitalCallback(byte port, int value) { if (port < TOTAL_PORTS) { reportPINs[port] = (byte)value; // Send port value immediately. This is helpful when connected via // ethernet, wi-fi or bluetooth so pin states can be known upon // reconnecting. if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); } // do not disable analog reporting on these 8 pins, to allow some // pins used for digital, others analog. Instead, allow both types // of reporting to be enabled, but check if the pin is configured // as analog when sampling the analog inputs. Likewise, while // scanning digital pins, portConfigInputs will mask off values from any // pins configured as analog } /*============================================================================== * SYSEX-BASED commands *============================================================================*/ void sysexCallback(byte command, byte argc, byte *argv) { byte mode; byte stopTX; byte slaveAddress; byte data; int slaveRegister; unsigned int delayTime; switch (command) { case I2C_REQUEST: mode = argv[1] & I2C_READ_WRITE_MODE_MASK; if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { Firmata.sendString(""10-bit addressing not supported""); return; } else { slaveAddress = argv[0]; } // need to invert the logic here since 0 will be default for client // libraries that have not updated to add support for restart tx if (argv[1] & I2C_END_TX_MASK) { stopTX = I2C_RESTART_TX; } else { stopTX = I2C_STOP_TX; // default } switch (mode) { case I2C_WRITE: Wire.beginTransmission(slaveAddress); for (byte i = 2; i < argc; i += 2) { data = argv[i] + (argv[i + 1] << 7); wireWrite(data); } Wire.endTransmission(); delayMicroseconds(70); break; case I2C_READ: if (argc == 6) { // a slave register is specified slaveRegister = argv[2] + (argv[3] << 7); data = argv[4] + (argv[5] << 7); // bytes to read } else { // a slave register is NOT specified slaveRegister = I2C_REGISTER_NOT_SPECIFIED; data = argv[2] + (argv[3] << 7); // bytes to read } readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); break; case I2C_READ_CONTINUOUSLY: if ((queryIndex + 1) >= I2C_MAX_QUERIES) { // too many queries, just ignore Firmata.sendString(""too many queries""); break; } if (argc == 6) { // a slave register is specified slaveRegister = argv[2] + (argv[3] << 7); data = argv[4] + (argv[5] << 7); // bytes to read } else { // a slave register is NOT specified slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; data = argv[2] + (argv[3] << 7); // bytes to read } queryIndex++; query[queryIndex].addr = slaveAddress; query[queryIndex].reg = slaveRegister; query[queryIndex].bytes = data; query[queryIndex].stopTX = stopTX; break; case I2C_STOP_READING: byte queryIndexToSkip; // if read continuous mode is enabled for only 1 i2c device, disable // read continuous reporting for that device if (queryIndex <= 0) { queryIndex = -1; } else { queryIndexToSkip = 0; // if read continuous mode is enabled for multiple devices, // determine which device to stop reading and remove it's data from // the array, shifiting other array data to fill the space for (byte i = 0; i < queryIndex + 1; i++) { if (query[i].addr == slaveAddress) { queryIndexToSkip = i; break; } } for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { if (i < I2C_MAX_QUERIES) { query[i].addr = query[i + 1].addr; query[i].reg = query[i + 1].reg; query[i].bytes = query[i + 1].bytes; query[i].stopTX = query[i + 1].stopTX; } } queryIndex--; } break; default: break; } break; case I2C_CONFIG: delayTime = (argv[0] + (argv[1] << 7)); if (delayTime > 0) { i2cReadDelayTime = delayTime; } if (!isI2CEnabled) { enableI2CPins(); } break; case SERVO_CONFIG: if (argc > 4) { // these vars are here for clarity, they'll optimized away by the compiler byte pin = argv[0]; int minPulse = argv[1] + (argv[2] << 7); int maxPulse = argv[3] + (argv[4] << 7); if (IS_PIN_DIGITAL(pin)) { if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { detachServo(pin); } attachServo(pin, minPulse, maxPulse); setPinModeCallback(pin, PIN_MODE_SERVO); } } break; case SAMPLING_INTERVAL: if (argc > 1) { samplingInterval = argv[0] + (argv[1] << 7); if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { samplingInterval = MINIMUM_SAMPLING_INTERVAL; } } else { //Firmata.sendString(""Not enough data""); } break; case EXTENDED_ANALOG: if (argc > 1) { int val = argv[1]; if (argc > 2) val |= (argv[2] << 7); if (argc > 3) val |= (argv[3] << 14); analogWriteCallback(argv[0], val); } break; case CAPABILITY_QUERY: Firmata.write(START_SYSEX); Firmata.write(CAPABILITY_RESPONSE); for (byte pin = 0; pin < TOTAL_PINS; pin++) { if (IS_PIN_DIGITAL(pin)) { Firmata.write((byte)INPUT); Firmata.write(1); Firmata.write((byte)PIN_MODE_PULLUP); Firmata.write(1); Firmata.write((byte)OUTPUT); Firmata.write(1); } if (IS_PIN_ANALOG(pin)) { Firmata.write(PIN_MODE_ANALOG); Firmata.write(10); // 10 = 10-bit resolution } if (IS_PIN_PWM(pin)) { Firmata.write(PIN_MODE_PWM); Firmata.write(DEFAULT_PWM_RESOLUTION); } if (IS_PIN_DIGITAL(pin)) { Firmata.write(PIN_MODE_SERVO); Firmata.write(14); } if (IS_PIN_I2C(pin)) { Firmata.write(PIN_MODE_I2C); Firmata.write(1); // TODO: could assign a number to map to SCL or SDA } #ifdef FIRMATA_SERIAL_FEATURE serialFeature.handleCapability(pin); #endif Firmata.write(127); } Firmata.write(END_SYSEX); break; case PIN_STATE_QUERY: if (argc > 0) { byte pin = argv[0]; Firmata.write(START_SYSEX); Firmata.write(PIN_STATE_RESPONSE); Firmata.write(pin); if (pin < TOTAL_PINS) { Firmata.write(Firmata.getPinMode(pin)); Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); } Firmata.write(END_SYSEX); } break; case ANALOG_MAPPING_QUERY: Firmata.write(START_SYSEX); Firmata.write(ANALOG_MAPPING_RESPONSE); for (byte pin = 0; pin < TOTAL_PINS; pin++) { Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); } Firmata.write(END_SYSEX); break; case SERIAL_MESSAGE: #ifdef FIRMATA_SERIAL_FEATURE serialFeature.handleSysex(command, argc, argv); #endif break; } } /*============================================================================== * SETUP() *============================================================================*/ void systemResetCallback() { isResetting = true; // initialize a defalt state // TODO: option to load config from EEPROM instead of default #ifdef FIRMATA_SERIAL_FEATURE serialFeature.reset(); #endif if (isI2CEnabled) { disableI2CPins(); } for (byte i = 0; i < TOTAL_PORTS; i++) { reportPINs[i] = false; // by default, reporting off portConfigInputs[i] = 0; // until activated previousPINs[i] = 0; } for (byte i = 0; i < TOTAL_PINS; i++) { // pins with analog capability default to analog input // otherwise, pins default to digital output if (IS_PIN_ANALOG(i)) { // turns off pullup, configures everything setPinModeCallback(i, PIN_MODE_ANALOG); } else if (IS_PIN_DIGITAL(i)) { // sets the output to 0, configures portConfigInputs setPinModeCallback(i, OUTPUT); } servoPinMap[i] = 255; } // by default, do not report any analog inputs analogInputsToReport = 0; detachedServoCount = 0; servoCount = 0; /* send digital inputs to set the initial state on the host computer, * since once in the loop(), this firmware will only send on change */ /* TODO: this can never execute, since no pins default to digital input but it will be needed when/if we support EEPROM stored config for (byte i=0; i < TOTAL_PORTS; i++) { outputPort(i, readPort(i, portConfigInputs[i]), true); } */ isResetting = false; } void setup() { //************************************************************************************************************************************************************************************************* Serial.begin(9600); //initialisation de la communication série pinMode(D0, INPUT); pinMode(D1, INPUT); pinMode(ACK, OUTPUT); digitalWrite(ACK, LOW); // initialement, ACK doit être égale à LOW, puisque on n'a rien reçu au lancement du programme //************************************************************************************************************************************************************************************************* Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); Firmata.attach(REPORT_ANALOG, reportAnalogCallback); Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); Firmata.attach(SET_PIN_MODE, setPinModeCallback); Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); Firmata.attach(START_SYSEX, sysexCallback); Firmata.attach(SYSTEM_RESET, systemResetCallback); // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega, // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this: // Serial1.begin(57600); // Firmata.begin(Serial1); // However do not do this if you are using SERIAL_MESSAGE Firmata.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101 } systemResetCallback(); // reset to default config } /*============================================================================== * LOOP() *============================================================================*/ void loop() { //************************************************************************************************************************************************************************************************* String client= ""NULL""; // cette vatriable conttiendra à chaque fois le nom de la personne dont le Tag RFID est détecté int un = digitalRead(D0); // Lire le LSB de l'identifiant int deux = digitalRead(D1); // Lire le MSB de l'identifiant /*Serial.print(""D0------------ ""); Serial.println(un); Serial.print(""D1------------ ""); Serial.println(deux);*/ if(!un && !deux) digitalWrite(ACK, LOW); //si on reçoit ""00"", alors ne rien faire else if(un && !deux){ // si on reçoit ""01"", alors il s'agit de Oussama client= ""Oussama Oulkaid""; digitalWrite(ACK, HIGH); // envoyer une confirmation de réception while(digitalRead(D0) && !digitalRead(D1)){} //tant que l'autre arduino envoi toujours la même valeur, attendre. if(!digitalRead(D0) && !digitalRead(D1)) digitalWrite(ACK, LOW); // une fois que l'autre arduino commence encore à envoyer ""00"", alors ne rien faire (mettre ACK à LOW). } else if(!un && deux){ // si on reçoit ""10"", alors il s'agit de Mohamed client= ""Mohamed Ahal""; digitalWrite(ACK, HIGH); while(!digitalRead(D0) && digitalRead(D1)){} if(!digitalRead(D0) && !digitalRead(D1)) digitalWrite(ACK, LOW); } else{ client= ""!!Inconnu!!""; // si on reçoit ""11"", alors il la personne est inconnue! digitalWrite(ACK, HIGH); while(digitalRead(D0) && digitalRead(D1)){} if(!digitalRead(D0) && !digitalRead(D1)) digitalWrite(ACK, LOW); } lux_Value = analogRead(lux_Pin); // lire la valeur de la photorésisitance à travers le Pin dédié //-> envoyer simultanément : la valeur de la luminosité et le nom de la personne en cours, séparés avec "";"" et terminés par un retour à la ligne. Serial.print(lux_Value); Serial.print("";""); Serial.print(client); Serial.println(); delay(700); //************************************************************************************************************************************************************************************************* byte pin, analogPin; /* DIGITALREAD - as fast as possible, check for changes and output them to the * FTDI buffer using Serial.print() */ checkDigitalInputs(); /* STREAMREAD - processing incoming messagse as soon as possible, while still * checking digital inputs. */ while (Firmata.available()) Firmata.processInput(); // TODO - ensure that Stream buffer doesn't go over 60 bytes currentMillis = millis(); if (currentMillis - previousMillis > samplingInterval) { previousMillis += samplingInterval; /* ANALOGREAD - do all analogReads() at the configured sampling interval */ for (pin = 0; pin < TOTAL_PINS; pin++) { if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { analogPin = PIN_TO_ANALOG(pin); if (analogInputsToReport & (1 << analogPin)) { Firmata.sendAnalog(analogPin, analogRead(analogPin)); } } } // report i2c data for all device with read continuous mode enabled if (queryIndex > -1) { for (byte i = 0; i < queryIndex + 1; i++) { readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); } } } #ifdef FIRMATA_SERIAL_FEATURE serialFeature.update(); #endif } ",8319,False,1593.8029055975044,median ":application_email_config_override_text: :optional_tag: pass:normal[[optional]#Optional#] :default_localhost: pass:normal[[default]#defaults to `localhost`#] :default_change_me: pass:normal[[default]#defaults to `change-me@fusionauth.io`#] :default_port_25: pass:normal[[default]#defaults to `25`#] :default_none: pass:normal[[default]#defaults to `NONE`#] :default_false: pass:normal[[default]#defaults to `none`#] :default_true: pass:normal[[default]#defaults to `true`#] :default_allow: pass:normal[[default]#defaults to `Allow`#] :show_feature_blurb: true :base_field_name: tenant :is_tenant: true ==== Request Body [.api] [field]#sourceTenantId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.14.0#:: The optional Id of an existing Tenant to make a copy of. A unique [field]#tenant.name# is required. If present, the [field]#tenant.id# value will used for the new Tenant. All other values will be copied from the source Tenant to the new Tenant. [field]#tenant.accessControlConfiguration.uiIPAccessControlListId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.30.0#:: The Id of the link:/docs/v1/tech/apis/ip-acl[IP Access Control List] limiting access to all applications in this tenant. + :enterprise_feature: IP ACLs include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.captchaConfiguration.captchaMethod# [type]#[String]# [optional]#Optional# [since]#Available since 1.30.0#:: The type of captcha method to use. This field is required when [field]#tenant.captchaConfiguration.enabled# is set to `true`. The possible values are: + * `GoogleRecaptchaV2` - use Google Recaptcha v2 * `GoogleRecaptchaV3` - use Google Recaptcha v3 * `HCaptcha` - use HCaptcha * `HCaptchaEnterprise` - use HCaptcha Enterprise - v25 + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] // You must keep the empty line above the `+` and you cannot undefine :enterprise_feature!: here it breaks the formatting because of the list. [field]#tenant.captchaConfiguration.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether captcha configuration is enabled. + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.captchaConfiguration.secretKey# [type]#[String]# [optional]#Optional# [since]#Available since 1.30.0#:: The secret key for this captcha method. This field is required when [field]#tenant.captchaConfiguration.enabled# is set to `true`. + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.captchaConfiguration.siteKey# [type]#[String]# [optional]#Optional# [since]#Available since 1.30.0#:: The site key for this captcha method. This field is required when [field]#tenant.captchaConfiguration.enabled# is set to `true`. + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.captchaConfiguration.threshold# [type]#[Float]# [optional]#Optional# [default]#defaults to `0.5`# [since]#Available since 1.30.0#:: The numeric threshold which separates a passing score from a failing one. This value only applies if using either the Google v3 or HCaptcha Enterprise method, otherwise this value is ignored. + The value must be between `0.0` and `1.0`. Values outside of that range will result in an error. + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.connectorPolicies# [type]#[Array]# [optional]#Optional# [since]#Available since 1.18.0#:: A list of Connector policies. Users will be authenticated against Connectors in order. Each Connector can be included in this list at most once and must exist. [field]#tenant.connectorPolicies``[x]``.connectorId# [type]#[UUID]# [optional]#Optional# [default]#defaults to the FusionAuth connector Id of `e3306678-a53a-4964-9040-1c96f36dda72`# [since]#Available since 1.18.0#:: The identifier of the Connector to which this policy refers. [field]#tenant.connectorPolicies``[x]``.domains# [type]#[Array]# [optional]#Optional# [default]#defaults to `[""*""]`# [since]#Available since 1.18.0#:: An list of email domains to which this connector should apply. + A value of `[""*""]` indicates this connector applies to all users. [field]#tenant.connectorPolicies``[x]``.migrate# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.18.0#:: If true, the user's data will be migrated to FusionAuth at first successful authentication; subsequent authentications will occur against the FusionAuth datastore. If false, the Connector's source will be treated as authoritative. + Prior to version 1.28.0 this value was required. [field]#tenant.data# [type]#[Object]# [optional]#Optional#:: An object that can hold any information about the Tenant that should be persisted. include::_tenant-application-email-configuration.adoc[] [field]#tenant.eventConfiguration.events# [type]#[Object]# [optional]#Optional# [since]#Available since 1.8.0#:: A mapping of the configuration for each event type that FusionAuth sends. The event types that are the keys into this Object are: + include::_event-types.adoc[] [field]#tenant.eventConfiguration.events``[type]``.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether or not FusionAuth should send these types of events to any configured Webhooks. [field]#tenant.eventConfiguration.events``[type]``.transactionType# [type]#[String]# [optional]#Optional# [since]#Available since 1.8.0#:: The transaction type that FusionAuth uses when sending these types of events to any configured Webhooks. The transaction types are: + include::_transaction-types.adoc[] [field]#tenant.externalIdentifierConfiguration.authorizationGrantIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `30`# [since]#Available since 1.8.0#:: The time in seconds until a OAuth authorization code in no longer valid to be exchanged for an access token. This is essentially the time allowed between the start of an Authorization request during the Authorization code grant and when you request an access token using this authorization code on the Token endpoint. + Value must be greater than 0 and less than or equal to 600. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.changePasswordIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: changePasswordIdGenerator :generator_display_name: change password Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.changePasswordIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: change password Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.changePasswordIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `600`# [since]#Available since 1.8.0#:: The time in seconds until a change password Id is no longer valid and cannot be used by the Change Password API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.deviceCodeTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `300`# [since]#Available since 1.11.0#:: The time in seconds until a device code Id is no longer valid and cannot be used by the Token API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.deviceUserCodeIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `6`# [since]#Available since 1.11.0#:: + :generator_type: deviceCodeTimeToLiveInSeconds :generator_display_name: device code Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.deviceUserCodeIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomAlphaNumeric`# [since]#Available since 1.11.0#:: + :generator_display_name: device code Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.emailVerificationIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: emailVerificationIdGenerator :generator_display_name: the email verification Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.emailVerificationIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: email verification Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.emailVerificationIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `86,400`# [since]#Available since 1.8.0#:: The time in seconds until a email verification Id is no longer valid and cannot be used by the Verify Email API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.emailVerificationOneTimeCodeGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `6`# [since]#Available since 1.27.0#:: + :generator_type: emailVerificationIdGenerator :generator_display_name: email verification one time code include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + [field]#tenant.externalIdentifierConfiguration.emailVerificationOneTimeCodeGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomAlphaNumeric`# [since]#Available since 1.27.0#:: + :generator_display_name: email verification one time code include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + [field]#tenant.externalIdentifierConfiguration.externalAuthenticationIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `300`# [since]#Available since 1.12.0#:: The time in seconds until an external authentication Id is no longer valid and cannot be used by the Token API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.oneTimePasswordTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.8.0#:: The time in seconds until a One Time Password is no longer valid and cannot be used by the Login API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.passwordlessLoginGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: passwordlessLoginGenerator :generator_display_name: passwordless login include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.passwordlessLoginGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: passwordless login include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.passwordlessLoginTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `180`# [since]#Available since 1.8.0#:: The time in seconds until a passwordless code is no longer valid and cannot be used by the Passwordless API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.pendingAccountLinkTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `3600`# [since]#Available since 1.28.0#:: The number of seconds before the pending account link identifier is no longer valid to complete an account link request. Value must be greater than 0. [field]#tenant.externalIdentifierConfiguration.registrationVerificationIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: registrationVerificationIdGenerator :generator_display_name: registration verification Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.registrationVerificationIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: registration verification Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.registrationVerificationIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `86,400`# [since]#Available since 1.8.0#:: The time in seconds until a registration verification Id is no longer valid and cannot be used by the Verify Registration API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.registrationVerificationOneTimeCodeGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `6`# [since]#Available since 1.27.0#:: + :generator_type: registrationVerificationIdGenerator :generator_display_name: registration verification one time code include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.registrationVerificationOneTimeCodeGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomAlphaNumeric`# [since]#Available since 1.27.0#:: + :generator_display_name: registration verification one time code include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.samlv2AuthNRequestIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `300`# [since]#Available since 1.19.0#:: The time in seconds that a SAML AuthN request Id returned by the Start SAML v2 Login Request API will be eligible to be used to complete a SAML v2 Login request. [field]#tenant.externalIdentifierConfiguration.setupPasswordIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: setupPasswordIdGenerator :generator_display_name: setup password Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.setupPasswordIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: setup password Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.setupPasswordIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `86,400`# [since]#Available since 1.8.0#:: The time in seconds until a setup password Id is no longer valid and cannot be used by the Change Password API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.trustTokenTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `180`# [since]#Available since 1.33.0#:: The number of seconds before the Trust Token is no longer valid to complete a request that requires trust. Value must be greater than 0. [field]#tenant.externalIdentifierConfiguration.twoFactorIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `300`# [since]#Available since 1.8.0#:: The time in seconds until a two factor Id is no longer valid and cannot be used by the Two Factor Login API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorOneTimeCodeIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `6`# [since]#Available since 1.27.0#:: + :generator_type: twoFactorOneTimeCodeIdGenerator :generator_display_name: the two factor code Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorOneTimeCodeIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomDigits`# [since]#Available since 1.27.0#:: + :generator_display_name: two factor one time code Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorOneTimeCodeIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.26.0#:: The number of seconds before the Two-Factor One Time Code used to enable or disable a two-factor method is no longer valid. Must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorTrustIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `2,592,000`# [since]#Available since 1.8.0#:: The time in seconds until an issued Two Factor trust Id is no longer valid and the User will be required to complete Two Factor authentication during the next authentication attempt. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.failedAuthenticationConfiguration.actionDuration# [type]#[Long]# [optional]#Optional# [default]#defaults to `3`# [since]#Available since 1.8.0#:: The duration of the User Action. This value along with the `actionDurationUnit` will be used to set the duration of the User Action. Value must be greater than 0. [field]#tenant.failedAuthenticationConfiguration.actionDurationUnit# [type]#[String]# [optional]#Optional# [default]#defaults to `""MINUTES""`# [since]#Available since 1.8.0#:: include::_expiry_unit.adoc[] [field]#tenant.failedAuthenticationConfiguration.resetCountInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.8.0#:: The length of time in seconds before the failed authentication count will be reset. Value must be greater than 0. + For example, if `tooManyAttempts` is set to `5` and you fail to authenticate `4` times in a row, waiting for the duration specified here will cause your fifth attempt to start back at `1`. [field]#tenant.failedAuthenticationConfiguration.tooManyAttempts# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.8.0#:: The number of failed attempts considered to be too many. Once this threshold is reached the specified User Action will be applied to the user for the duration specified. Value must be greater than 0. [field]#tenant.failedAuthenticationConfiguration.userActionId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.8.0#:: The Id of the User Action that is applied when the threshold is reached for too many failed authentication attempts. [field]#tenant.familyConfiguration.allowChildRegistrations# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.8.0#:: Whether to allow child registrations. [field]#tenant.familyConfiguration.confirmChildEmailTemplateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.8.0#:: The unique Id of the email template to use when confirming a child. [field]#tenant.familyConfiguration.deleteOrphanedAccounts# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Indicates that child users without parental verification will be permanently deleted after [field]#tenant.familyConfiguration.deleteOrphanedAccountsDays# days. [field]#tenant.familyConfiguration.deleteOrphanedAccountsDays# [type]#[Integer]# [optional]#Optional# [default]#defaults to `30`# [since]#Available since 1.8.0#:: The number of days from creation child users will be retained before being deleted for not completing parental verification. Value must be greater than 0. [field]#tenant.familyConfiguration.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether family configuration is enabled. [field]#tenant.familyConfiguration.familyRequestEmailTemplateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.8.0#:: The unique Id of the email template to use when a family request is made. [field]#tenant.familyConfiguration.maximumChildAge# [type]#[Integer]# [optional]#Optional# [default]#defaults to `12`# [since]#Available since 1.8.0#:: The maximum age of a child. Value must be greater than 0. [field]#tenant.familyConfiguration.minimumOwnerAge# [type]#[Integer]# [optional]#Optional# [default]#defaults to `21`# [since]#Available since 1.8.0#:: The minimum age to be an owner. Value must be greater than 0. [field]#tenant.familyConfiguration.parentEmailRequired# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether a parent email is required. [field]#tenant.familyConfiguration.parentRegistrationEmailTemplateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.8.0#:: The unique Id of the email template to use for parent registration. [field]#tenant.formConfiguration.adminUserFormId# [type]#[UUID]# [optional]#Optional# [default]#defaults to **[see description]**# [since]#Available since 1.20.0#:: The unique Id of the form to use for the Add and Edit User form when used in the FusionAuth admin UI. + When this parameter is not provided, it will default to the form Id currently assigned to the Default tenant. + :premium_feature: custom forms include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.httpSessionMaxInactiveInterval# [type]#[Integer]# [optional]#Optional# [default]#defaults to `3600`# [since]#Available since 1.8.0#:: Time in seconds until an inactive session will be invalidated. Used when creating a new session in the FusionAuth OAuth frontend. [field]#tenant.issuer# [type]#[String]# [optional]#Optional# [default]#defaults to `fusionauth.io`# [since]#Available since 1.8.0#:: The named issuer used to sign tokens, this is generally your public fully qualified domain. + Prior to version 1.30.0 this value was required. [field]#tenant.jwtConfiguration.accessTokenKeyId# [type]#[UUID]# [optional]#Optional# [default]#defaults to key value of the FusionAuth application# [since]#Available since 1.8.0#:: The unique id of the signing key used to sign the access token. + Prior to version 1.30.0 this value was required. [field]#tenant.jwtConfiguration.idTokenKeyId# [type]#[UUID]# [optional]#Optional# [default]#defaults to key value of the FusionAuth application# [since]#Available since 1.8.0#:: The unique id of the signing key used to sign the Id token. + Prior to version 1.30.0 this value was required. [field]#tenant.jwtConfiguration.refreshTokenExpirationPolicy# [type]#[String]# [optional]#Optional# [default]#defaults to `Fixed`# [since]#Available since 1.17.0#:: The refresh token expiration policy. The following are valid values: * `Fixed` - the expiration is calculated from the time the token is issued. * `SlidingWindow` - the expiration is calculated from the last time the token was used. [field]#tenant.jwtConfiguration.refreshTokenRevocationPolicy.onLoginPrevented# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.17.0#:: When enabled, the refresh token will be revoked when a user action, such as locking an account based on a number of failed login attempts, prevents user login. [field]#tenant.jwtConfiguration.refreshTokenRevocationPolicy.onPasswordChanged# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.17.0#:: When enabled, the refresh token will be revoked when a user changes their password. [field]#tenant.jwtConfiguration.refreshTokenTimeToLiveInMinutes# [type]#[Integer]# [optional]#Optional# [default]#defaults to `43,200`# [since]#Available since 1.8.0#:: The length of time in minutes a Refresh Token is valid from the time it was issued. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.jwtConfiguration.refreshTokenUsagePolicy# [type]#[String]# [optional]#Optional# [default]#defaults to `Reusable`# [since]#Available since 1.17.0#:: The refresh token usage policy. The following are valid values: * `Reusable` - the token does not change after it was issued. * `OneTimeUse` - the token value will be changed each time the token is used to refresh a JWT. The client must store the new value after each usage. + Prior to version 1.28.0 this value was required. [field]#tenant.jwtConfiguration.timeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `3,600`# [since]#Available since 1.8.0#:: The length of time in seconds this JWT is valid from the time it was issued. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.loginConfiguration.requireAuthentication# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.26.0#:: Indicates whether to require an API key for the Login API when an `applicationId` is not provided. When an `applicationId` is provided to the Login API call, the application configuration will take precedence. + In almost all cases, you will want to this to be `true`. [field]#tenant.logoutURL# [type]#[String]# [optional]#Optional# [since]#Available since 1.8.0#:: The logout redirect URL when sending the user's browser to the `/oauth2/logout` URI of the FusionAuth Front End. This value is only used when a logout URL is not defined in your Application. [field]#tenant.maximumPasswordAge.days# [type]#[Integer]# [optional]#Optional# [default]#defaults to `180`# [since]#Available since 1.8.0#:: The password maximum age in days. The number of days after which FusionAuth will require a user to change their password. Required when [field]#tenant.maximumPasswordAge.enabled# is set to `true`. [field]#tenant.maximumPasswordAge.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Indicates that the maximum password age is enabled and being enforced. [field]#tenant.minimumPasswordAge.seconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `30`# [since]#Available since 1.8.0#:: The password minimum age in seconds. When enabled FusionAuth will not allow a password to be changed until it reaches this minimum age. Required when [field]#tenant.minimumPasswordAge.enabled# is set to `true`. [field]#tenant.minimumPasswordAge.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Indicates that the minimum password age is enabled and being enforced. [field]#tenant.multiFactorConfiguration.authenticator.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.26.0#:: When enabled, users may utilize an authenticator application to complete a multi-factor authentication request. This method uses TOTP (Time-Based One-Time Password) as defined in link:https://tools.ietf.org/html/rfc6238[RFC 6238] and often uses an native mobile app such as Google Authenticator. [field]#tenant.multiFactorConfiguration.email.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.26.0#:: When enabled, users may utilize an email address to complete a multi-factor authentication request. [field]#tenant.multiFactorConfiguration.email.templateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.26.0#:: The Id of the email template that is used when notifying a user to complete a multi-factor authentication request. This field is required when [field]#tenant.multiFactorConfiguration.email.enabled# is set to `true`. [field]#tenant.multiFactorConfiguration.sms.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.26.0#:: When enabled, users may utilize a mobile phone number to complete a multi-factor authentication request. [field]#tenant.multiFactorConfiguration.sms.messengerId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.26.0#:: The messenger that is used to deliver a SMS multi-factor authentication request. This field is required when [field]#tenant.multiFactorConfiguration.sms.enabled# is set to `true`. [field]#tenant.multiFactorConfiguration.sms.templateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.26.0#:: The Id of the SMS template that is used when notifying a user to complete a multi-factor authentication request. This field is required when [field]#tenant.multiFactorConfiguration.sms.enabled# is set to `true`. [field]#tenant.name# [type]#[String]# [required]#Required#:: The unique name of the Tenant. [field]#tenant.oauthConfiguration.clientCredentialsAccessTokenPopulateLambdaId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.26.0#:: The Id of a lambda that will be called to populate the JWT during a client credentials grant. + :premium_feature: client credentials grant include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.passwordEncryptionConfiguration.encryptionScheme# [type]#[String]# [optional]#Optional# [default]#defaults to `""salted-pbkdf2-hmac-sha256""`# [since]#Available since 1.8.0#:: The default method for encrypting the User's password. The following encryptors are provided with FusionAuth: + * `link:/docs/v1/tech/reference/password-hashes#salted-md5[salted-md5]` * `link:/docs/v1/tech/reference/password-hashes#salted-sha-256[salted-sha256]` * `link:/docs/v1/tech/reference/password-hashes#salted-hmac-sha-256[salted-hmac-sha256]` * `link:/docs/v1/tech/reference/password-hashes#salted-pbkdf2-hmac-sha-256[salted-pbkdf2-hmac-sha256]` * `link:/docs/v1/tech/reference/password-hashes#salted-bcrypt[bcrypt]` [field]#tenant.passwordEncryptionConfiguration.encryptionSchemeFactor# [type]#[Integer]# [optional]#Optional# [default]#defaults to `24000`# [since]#Available since 1.8.0#:: The factor used by the password encryption scheme. If not provided, the `PasswordEncryptor` provides a default value. Generally this will be used as an iteration count to generate the hash. The actual use of this value is up to the `PasswordEncryptor` implementation. [field]#tenant.passwordEncryptionConfiguration.modifyEncryptionSchemeOnLogin# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: When enabled a user's hash configuration will be modified to match these configured settings. This can be useful to increase a password hash strength over time or upgrade imported users to a more secure encryption scheme after an initial import. [field]#tenant.passwordValidationRules.breachDetection.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.15.0#:: Whether to enable Reactor breach detection. Requires an activated license. [field]#tenant.passwordValidationRules.breachDetection.matchMode# [type]#[String]# [optional]#Optional# [since]#Available since 1.15.0#:: The level of severity where Reactor will consider a breach. The following are valid values: + * `High` Only requires a password match, this is the most secure and is recommended * `Medium` Exact match on username, email address or email sub-address * `Low` Exact match on an email or username, or the password is a common breached value [field]#tenant.passwordValidationRules.breachDetection.notifyUserEmailTemplateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.15.0#:: The Id of the email template to use when notifying user of breached password. Required if [field]#tenant.passwordValidationRules.breachDetection.onLogin# is set to `NotifyUser`. [field]#tenant.passwordValidationRules.breachDetection.onLogin# [type]#[String]# [optional]#Optional# [since]#Available since 1.15.0#:: The behavior when detecting breaches at time of user login. The following are valid values: + * `Off` Do not perform breach detection at login * `RecordOnly` Only record the result, take no action * `NotifyUser` Notify the end user via email * `RequireChange` Require immediate password change [field]#tenant.passwordValidationRules.maxLength# [type]#[Integer]# [optional]#Optional# [default]#defaults to `256`# [since]#Available since 1.8.0#:: The maximum length of a password when a new user is created or a user requests a password change. [field]#tenant.passwordValidationRules.minLength# [type]#[Integer]# [optional]#Optional# [default]#defaults to `8`# [since]#Available since 1.8.0#:: The minimum length of a password when a new user is created or a user requests a password change. [field]#tenant.passwordValidationRules.rememberPreviousPasswords.count# [type]#[Integer]# [optional]#Optional# [since]#Available since 1.8.0#:: The number of previous passwords to remember. Value must be greater than 0. [field]#tenant.passwordValidationRules.rememberPreviousPasswords.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether to prevent a user from using any of their previous passwords. [field]#tenant.passwordValidationRules.requireMixedCase# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether to force the user to use at least one uppercase and one lowercase character. [field]#tenant.passwordValidationRules.requireNonAlpha# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether to force the user to use at least one non-alphanumeric character. [field]#tenant.passwordValidationRules.requireNumber# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether to force the user to use at least one number. [field]#tenant.passwordValidationRules.validateOnLogin# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.15.0#:: When enabled the user's password will be validated during login. If the password does not meet the currently configured validation rules the user will be required to change their password. [field]#tenant.rateLimitConfiguration.failedLogin.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for failed login. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.failedLogin.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can fail to login within the configured [field]#timePeriodInSeconds# duration. If a Failed authentication action has been configured then it will take precedence. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.failedLogin.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can fail login before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.forgotPassword.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for forgot password. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.forgotPassword.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a forgot password email within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.forgotPassword.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a forgot password email before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendEmailVerification.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for send email verification. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendEmailVerification.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a verification email within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendEmailVerification.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a verification email before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendPasswordless.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for send passwordless. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendPasswordless.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a passwordless login email within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendPasswordless.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a passwordless login email before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendRegistrationVerification.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for send registration verification. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendRegistrationVerification.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a registration verification email within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendRegistrationVerification.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a registration verification email before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendTwoFactor.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for send two factor. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendTwoFactor.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a two-factor code by email or SMS within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendTwoFactor.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a two-factor code by email or SMS before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.registrationConfiguration.blockedDomains# [type]#[Array]# [optional]#Optional# [since]#Available since 1.30.0#:: A list of unique domains that are not allowed to register when self service is enabled. + :premium_feature: blocked domains include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.ssoConfiguration.deviceTrustTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `31,536,000` (1 year)# [since]#Available since 1.30.2#:: The number of seconds before a trusted device is reset. When reset, a user is forced to complete captcha during login and complete two factor authentication if applicable. [field]#tenant.themeId# [type]#[UUID]# [optional]#Optional# [default]#defaults to the default tenant theme Id of `75a068fd-e94b-451a-9aeb-3ddb9a3b5987`# [since]#Available since 1.8.0#:: The unique Id of the theme to be used to style the login page and other end user templates. + Prior to version 1.30.0 this value was required. [field]#tenant.userDeletePolicy.unverified.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.13.0#:: Indicates that users without a verified email address will be permanently deleted after [field]#tenant.userDeletePolicy.unverified.numberOfDaysToRetain# days. [field]#tenant.userDeletePolicy.unverified.numberOfDaysToRetain# [type]#[Integer]# [optional]#Optional# [since]#Available since 1.13.0#:: The number of days from creation users will be retained before being deleted for not completing email verification. This field is required when [field]#tenant.userDeletePolicy.unverified.enabled# is set to `true`. Value must be greater than 0. [field]#tenant.usernameConfiguration.unique.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.27.0#:: When `true`, FusionAuth will handle username collisions by generating a random suffix. + :premium_feature: unique usernames include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.usernameConfiguration.unique.numberOfDigits# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.27.0#:: The maximum number of digits to use when building a unique suffix for a username. A number will be randomly selected and will be 1 or more digits up to this configured value in length. For example, if this value is `5`, the suffix will be a number between `00001` and `99999`, inclusive. The value of this field must be greater than or equal to `3` and less than or equal to `10`. [field]#tenant.usernameConfiguration.unique.separator# [type]#[String]# [optional]#Optional# [default]#defaults to the `#` character# [since]#Available since 1.27.0#:: A single character to use as a separator from the requested username and a unique suffix that is added when a duplicate username is detected. This value can be a single non-alphanumeric ASCII character. [field]#tenant.usernameConfiguration.unique.strategy# [type]#[String]# [optional]#Optional# [default]#defaults to `OnCollision`# [since]#Available since 1.29.0#:: This strategy instructions FusionAuth when to append a unique suffix to the username. The possible values are: + * `Always` - Always append a unique suffix even when the requested username is not in use. * `OnCollision` - Only append a unique suffix when the requested username is in use. [source,json] .Example Request JSON ---- include::../../../src/json/tenants/request.json[] ---- ",12244,True,3043.3620083503774,median "[[netty-component]] = Netty Component :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 include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/netty.adoc[opts=optional] *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 73 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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}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. There are 6 enums and 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. There are 6 enums and 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 | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | 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 | *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 | *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. There are 2 enums and 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. There are 2 enums and 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. There are 3 enums and 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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}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. There are 6 enums and 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. There are 6 enums and 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 | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | 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 | *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 | 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. There are 2 enums and 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::{page-component-version}@camel-spring-boot::page$netty-starter.adoc[] ",12481,False,2368.2706502659235,median "= Learning all about WiFi data with Apache Kafka and friends *TODO*: diagram of the stuff that's going on in this article I've recently been looking at what's possible with streams of WiFi packet capture (""pcap"") data. It was prompted by initially setting up my https://rmoff.net/2020/03/11/streaming-wi-fi-trace-data-from-raspberry-pi-to-apache-kafka-with-confluent-cloud/[Raspberry Pi to capture this pcap data and stream it to Apache Kafka]. Because I was using Confluent Cloud it was easy enough to chuck the data at the Kafka cluster and not need to worry about where or how to run it. I set this running a month ago, and with a few blips in between (my Raspberry Pi is not deployed for _any_ nines of availability!) now have a bunch of raw pcap data that I thought it would be interesting to dig into using Apache Kafka and its surrounding ecosystem. At the heart of the data is https://www.wireshark.org/docs/dfref/w/wlan.html[wlan pcap data] captured from `tshark` (the command-line equivilant of Wireshark, which you may be familiar with). The data is stored in JSON on a partitioned Kafka topic, and a sample message looks like this: [source,javascript] ---- { ""timestamp"": ""1584802202655"", ""wlan_fc_type"": [ ""1"" ], ""wlan_fc_type_subtype"": [ ""25"" ], ""wlan_radio_channel"": [ ""1"" ], ""wlan_radio_signal_dbm"": [ ""-73"" ], ""wlan_radio_duration"": [ ""32"" ], ""wlan_ra"": [ ""a4:fc:77:6c:55:0d"" ], ""wlan_ra_resolved"": [ ""MegaWell_6c:55:0d"" ], ""wlan_ta"": [ ""48:d3:43:43:cd:d1"" ], ""wlan_ta_resolved"": [ ""ArrisGro_43:cd:d1"" ] } ---- These messages are coming in at a rate of about 100k per hour, c.30 per second. That's not ""Big Data"", but it's not insignificant either. ++++ ++++ It certainly gives me a bunch of data that's more than I can grok by just poking around it. I don't really know what I'm looking for in the data quite yet, I'm just interested what I've scooped up in my virtual net. Let's take two approaches, one visual and one numeric, to see if we can get a better handle on the data. == Understanding the overall dataset visually Kibana has a nice tool as part of its Machine Learning feature called *Data Visualizer*. Let's stream our raw wifi packet captures into Elasticsearch and check it out. [source,bash] ---- curl -i -X PUT -H ""Content-Type:application/json"" \\ http://localhost:8083/connectors/sink-elastic-pcap-00/config \\ -d '{ ""connector.class"": ""io.confluent.connect.elasticsearch.ElasticsearchSinkConnector"", ""topics"": ""pcap"", ""value.converter"": ""org.apache.kafka.connect.json.JsonConverter"", ""value.converter.schemas.enable"": ""false"", ""connection.url"": ""http://elasticsearch:9200"", ""type.name"": ""_doc"", ""key.ignore"": ""true"", ""schema.ignore"": ""true"" }' ---- The useful thing here is that we can see characteristics in the data including: * Record count per day + image::images/kib_doc_count01.png[] * The distribution of MAC addresses in senders (`sa`) and receivers (`ra`) + image::images/kib_ra_sa01.png[] * Which types of packet are most commonly found (`wlan_fc_subtype`) + image::images/kib_type_count01.png[] Based on https://books.google.co.uk/books?id=-AdTE9S3kigC&lpg=PA302&ots=Y8C-t2MKpN&dq=wireshark%20wlan.fc.type_subtype%2029%20ack&pg=PA301#v=onepage&q=wireshark%20wlan.fc.type_subtype%2029%20ack&f=false[this published table] we can see the top most common types of packets are: * 33% `ACK` (`wlan.fc.type_subtype` == 29) * 20% `Request to Send` (`wlan.fc.type_subtype` == 27) * 13% `Probe Request` (`wlan.fc.type_subtype` == 4) * 11% `NULL Data` (`wlan.fc.type_subtype` == 36) What about getting these numbers from analysing the data directly from the console, without Elasticsearch? == Understanding the overall dataset numerically With ksqlDB you can use SQL-like queries to inspect, aggregate, and process data. Let's see it in action here with the raw packet capture (pcap) data that we've got. First up, I'm going to declare a schema so that I can query attributes of the data in the topic. Since I'm only interested in a couple of fields at this point (the date, and the subtype ranges) I'm just going to specify a partial schema since in full it's fairly beefy and redundant to type out in full at this stage. [source,sql] ---- CREATE STREAM PCAP_RAW_00 (timestamp BIGINT, wlan_fc_type_subtype ARRAY) WITH (KAFKA_TOPIC='pcap', VALUE_FORMAT='JSON', TIMESTAMP='timestamp'); ---- A couple of things to point out here: * Notice that the `wlan_fc_type_subtype` is written by the source application (`tshark`) as an _array_ of `INT`, e.g. `""wlan_fc_type"": [ ""1"" ]` * I am telling ksqlDB to take the `timestamp` field from the payload as the timestamp of the message (`WITH … TIMESTAMP='timestamp'`). + If I didn't do this then it would default to the timestamp of the Kafka message as held in the message's metadata, which is not what I want in this case. Since we're going to be analysing the time attributes of the data it's important to be correctly handling **event time** vs **ingest time** here. With the stream created, I tell ksqlDB to process data from the beginning of the topic: [source,sql] ---- SET 'auto.offset.reset' = 'earliest'; ---- and then query it using SQL: [source,sql] ---- SELECT wlan_fc_type_subtype[1] AS SUBTYPE, COUNT(*) AS PACKET_COUNT, TIMESTAMPTOSTRING(MIN(ROWTIME),'yyyy-MM-dd HH:mm:ss','GMT') AS MIN_TS, TIMESTAMPTOSTRING(MAX(ROWTIME),'yyyy-MM-dd HH:mm:ss','GMT') AS MAX_TS FROM PCAP_RAW_00 WHERE ROWTIME < (UNIX_TIMESTAMP() - 1800000) GROUP BY wlan_fc_type_subtype[1] EMIT CHANGES; ---- Here we're aggregating by subtype for all messages received up until the last half hour, but you'll notice that it's calculating the numbers from the start of the topic and continually updating as newer messages are processed: ++++ ++++ Let's build on this example, and break down the subtype count by day. You'll notice here that instead of writing the aggregate result to the screen we're instead instantiating it as a table within ksqlDB: [source,sql] ---- SET 'auto.offset.reset' = 'earliest'; CREATE TABLE PCAP_STATS WITH (VALUE_FORMAT='AVRO') AS SELECT TIMESTAMPTOSTRING(WINDOWSTART,'yyyy-MM-dd','GMT') AS WINDOW_DAY, WLAN_FC_TYPE_SUBTYPE[1] AS SUBTYPE, COUNT(*) AS PACKET_COUNT, TIMESTAMPTOSTRING(MIN(ROWTIME),'HH:mm:ss','GMT') AS EARLIEST_TIME, TIMESTAMPTOSTRING(MAX(ROWTIME),'HH:mm:ss','GMT') AS LATEST_TIME FROM PCAP_RAW_00 WINDOW TUMBLING (SIZE 1 DAY) GROUP BY WLAN_FC_TYPE_SUBTYPE[1] EMIT CHANGES; ---- Now there's an actual materialised view of this data, backed by a persisted Kafka topic: [source,sql] ---- ksql> SHOW TABLES; Table Name | Kafka Topic | Format | Windowed ---------------------------------------------- PCAP_STATS | PCAP_STATS | AVRO | false ---------------------------------------------- ---- This table we can query either as a ""push"" query showing all updates as they arrive: ++++ ++++ or query the value directly with a ""pull"" query for any of the subtypes: [source,sql] ---- ksql> SELECT WINDOW_DAY, SUBTYPE, PACKET_COUNT, EARLIEST_TIME, LATEST_TIME FROM PCAP_STATS WHERE ROWKEY = 4 ; +-----------+--------+-------------+--------------+------------+ |WINDOW_DAY |SUBTYPE |PACKET_COUNT |EARLIEST_TIME |LATEST_TIME | +-----------+--------+-------------+--------------+------------+ |2020-02-28 |4 |84 |22:47:06 |23:59:35 | |2020-02-29 |4 |3934 |00:02:01 |23:58:19 | |2020-03-01 |4 |1601 |00:00:06 |23:58:07 | |2020-03-02 |4 |1125 |00:00:12 |23:59:13 | Query terminated ---- Since it's just a Kafka topic, you can persist this aggregate to a database, using the message key to ensure that values update in-place. We'll use Kafka Connect like we did above for Elasticsearch, but here using ksqlDB as the interface: [source,sql] ---- CREATE SINK CONNECTOR SINK_POSTGRES_PCAP_STATS_00 WITH ( 'connector.class' = 'io.confluent.connect.jdbc.JdbcSinkConnector', 'connection.url' = 'jdbc:postgresql://postgres:5432/', 'connection.user' = 'postgres', 'connection.password' = 'postgres', 'topics' = 'PCAP_STATS', 'key.converter' = 'org.apache.kafka.connect.storage.StringConverter', 'auto.create' = 'true', 'auto.evolve' = 'true', 'insert.mode' = 'upsert', 'pk.mode' = 'record_value', 'pk.fields' = 'WINDOW_DAY,SUBTYPE', 'table.name.format' = '${topic}' ); ---- Now as each message arrives in the source Kafka topic, it's incorporated in the aggregation by ksqlDB and the resulting change to the aggregate pushed to Postgres, where each key (which is a composite of the `SUBTYPE` plus the day) is updated in-place: [source,sql] ---- postgres=# SELECT * FROM ""PCAP_STATS"" WHERE ""SUBTYPE""=4 ORDER BY ""WINDOW_DAY"" ; WINDOW_DAY | SUBTYPE | PACKET_COUNT | EARLIEST_TIME | LATEST_TIME ------------+---------+--------------+---------------+------------- 2020-02-28 | 4 | 89 | 22:47:25 | 23:55:44 2020-02-29 | 4 | 4148 | 00:02:01 | 23:58:19 2020-03-01 | 4 | 1844 | 00:00:24 | 23:56:53 2020-03-02 | 4 | 847 | 00:00:12 | 23:59:13 … ---- ++++ ++++ == Analysing relationships in the data with Kibana As well as the Data Visualiser in Kibana, the Graph capabilities are quite interesting for exploring high-level relationships in the data: image::images/kib_probe_graph_01.png[] For dedicated Graph modelling and analysis of the data, see later in this article where we'll stream the data from Kafka into Neo4j and analyse it there. == Splitting the pcap data into separate topics Knowing from our above analysis the types of data that we've got, let's use ksqlDB to split them out into separate topics as we'll want to analyse them further separately and each may well have different schema. To start with, I'll declare a schema which covers fields across all types of packet: [source,sql] ---- CREATE STREAM pcap_raw (timestamp BIGINT, wlan_fc_type_subtype ARRAY, wlan_radio_channel ARRAY, wlan_radio_signal_percentage ARRAY, wlan_radio_signal_dbm ARRAY, wlan_radio_duration ARRAY, wlan_ra ARRAY, wlan_ra_resolved ARRAY, wlan_da ARRAY, wlan_da_resolved ARRAY, wlan_ta ARRAY, wlan_ta_resolved ARRAY, wlan_sa ARRAY, wlan_sa_resolved ARRAY, wlan_staa ARRAY, wlan_staa_resolved ARRAY, wlan_tagged_all ARRAY, wlan_tag_vendor_data ARRAY, wlan_tag_vendor_oui_type ARRAY, wlan_tag_oui ARRAY, wlan_country_info_code ARRAY, wps_device_name ARRAY, wlan_ssid ARRAY) WITH (KAFKA_TOPIC='pcap', VALUE_FORMAT='JSON', TIMESTAMP='timestamp'); ---- Now we can pull out records of different types into new streams, and take the opportunity to serialise the resulting data to Avro. [source,sql] ---- SET 'auto.offset.reset' = 'earliest'; CREATE STREAM PCAP_PROBE WITH (VALUE_FORMAT='AVRO') AS SELECT * FROM PCAP_RAW WHERE WLAN_FC_TYPE_SUBTYPE[1]=4; CREATE STREAM PCAP_BEACON WITH (VALUE_FORMAT='AVRO') AS SELECT * FROM PCAP_RAW WHERE WLAN_FC_TYPE_SUBTYPE[1]=8; CREATE STREAM PCAP_RTS WITH (VALUE_FORMAT='AVRO') AS SELECT * FROM PCAP_RAW WHERE WLAN_FC_TYPE_SUBTYPE[1]=27; CREATE STREAM PCAP_CTS WITH (VALUE_FORMAT='AVRO') AS SELECT * FROM PCAP_RAW WHERE WLAN_FC_TYPE_SUBTYPE[1]=28; CREATE STREAM PCAP_ACK WITH (VALUE_FORMAT='AVRO') AS SELECT * FROM PCAP_RAW WHERE WLAN_FC_TYPE_SUBTYPE[1]=29; CREATE STREAM PCAP_NULL WITH (VALUE_FORMAT='AVRO') AS SELECT * FROM PCAP_RAW WHERE WLAN_FC_TYPE_SUBTYPE[1]=36; ---- If we had a partition key strategy that we wanted to apply we could do this here too by specifying `PARTITION BY`—but since we're still at the early stages of analysis we'll leave the key unset for now (which means that messages will be distributed ""round robin"" evenly across all partitions). We could also opt to drop unused columns from the schema for particular message types by replacing `SELECT *` with a specific projection of required columns. You'll observe that this creates and populates new Kafka topics: [source,sql] ---- ksql> SHOW TOPICS; Kafka Topic | Partitions | Partition Replicas -------------------------------------------------------------------------- PCAP_ACK | 12 | 3 PCAP_BEACON | 12 | 3 PCAP_CTS | 12 | 3 PCAP_NULL | 12 | 3 PCAP_PROBE | 12 | 3 PCAP_RTS | 12 | 3 PCAP_STATS | 12 | 3 … ---- == Analysing WiFi probe requests Mobile devices send probe requests to see what Access Points (AP) are available, and are an interesting source of analysis. Kibana is a great tool here for ""slicing and dicing"" the data to explore it. By adding a filter for the subtype we can easily pick out the fields that have got relevant data: image::images/kib_probe_01.png[] * `wlan_sa` is the raw source MAC address, whilst `wlan_sa_resolved` includes in some cases the manufacturer's prefix * Most requests are looking for any AP but some are for a specific wireless network (`wlan_ssid`) === Enriching pcap data with lookups So in amongst all this ""digital exhaust"" is going to be a load of devices from within my house, plus others externally. Wouldn't it be nice to be able to identify them? This is where the real power of ksqlDB comes in, because I can use it to join a stream of events (pcap data) with lookup data from elsewhere. I've got a list of known MAC addresses for my household devices that I can draw from my router where they're stored on MongoDB. Let's pull that data into Kafka through ksqlDB: [source,sql] ---- CREATE SOURCE CONNECTOR SOURCE_MONGODB_UNIFI_01 WITH ( 'connector.class' = 'io.debezium.connector.mongodb.MongoDbConnector', 'mongodb.hosts' = 'rs0/mongodb:27017', 'mongodb.name' = 'unifi', 'collection.whitelist' = 'ace.device, ace.user' ); ---- With this data in Kafka we can use some of the data wrangling tricks to get two ksqlDB tables of devices (switches, APs, routers) and users (i.e. wifi clients - mobiles, laptops, etc). To get more background on what this ksqlDB code does and why, check out https://rmoff.net/2019/12/20/analysing-network-behaviour-with-ksqldb-and-mongodb/[this article]. [source,sql] ---- -- Model source topics CREATE STREAM DEVICES_RAW WITH (KAFKA_TOPIC='unifi.ace.device', VALUE_FORMAT='AVRO'); CREATE STREAM USERS_RAW WITH (KAFKA_TOPIC='unifi.ace.user', VALUE_FORMAT='AVRO'); -- Extract device data fields from JSON payload SET 'auto.offset.reset' = 'earliest'; CREATE STREAM ALL_DEVICES WITH (PARTITIONS=12, KAFKA_TOPIC='all_devices_00') AS SELECT 'ace.device' AS SOURCE, EXTRACTJSONFIELD(AFTER ,'$.mac') AS MAC, EXTRACTJSONFIELD(AFTER ,'$.ip') AS IP, EXTRACTJSONFIELD(AFTER ,'$.name') AS NAME, EXTRACTJSONFIELD(AFTER ,'$.model') AS MODEL, EXTRACTJSONFIELD(AFTER ,'$.type') AS TYPE, CAST('0' AS BOOLEAN) AS IS_GUEST FROM DEVICES_RAW -- Set the MAC address as a the message key PARTITION BY EXTRACTJSONFIELD(AFTER ,'$.mac') EMIT CHANGES; -- Extract user (client device) data from JSON payload with some -- wrangling to handle null/empty fields etc. -- Note that this is an ""INSERT INTO"" and thus in effect is a UNION of -- the two source topics with some wrangling to align the schemas. SET 'auto.offset.reset' = 'earliest'; INSERT INTO ALL_DEVICES SELECT 'ace.user' AS SOURCE, EXTRACTJSONFIELD(AFTER ,'$.mac') AS MAC, '' AS IP, -- Use a CASE statement to build a single label per device -- based on whether we have a name and/or hostname, and -- whether the device is a guest or not. CASE WHEN EXTRACTJSONFIELD(AFTER ,'$.name') IS NULL THEN CASE WHEN EXTRACTJSONFIELD(AFTER ,'$.hostname') IS NULL THEN CASE WHEN CAST(EXTRACTJSONFIELD(AFTER ,'$.is_guest') AS BOOLEAN) THEN 'guest_' ELSE 'nonguest_' END + EXTRACTJSONFIELD(AFTER ,'$.oui') ELSE EXTRACTJSONFIELD(AFTER ,'$.hostname') END ELSE CASE WHEN EXTRACTJSONFIELD(AFTER ,'$.hostname') IS NULL THEN EXTRACTJSONFIELD(AFTER ,'$.name') ELSE EXTRACTJSONFIELD(AFTER ,'$.name') + ' (' + EXTRACTJSONFIELD(AFTER ,'$.hostname') + ')' END END AS NAME, EXTRACTJSONFIELD(AFTER ,'$.oui') AS MODEL, '' AS TYPE, CAST(EXTRACTJSONFIELD(AFTER ,'$.is_guest') AS BOOLEAN) AS IS_GUEST FROM USERS_RAW -- Ignore Ubiquiti devices because these are picked up -- from the `unifi.ace.device` data WHERE EXTRACTJSONFIELD(AFTER ,'$.oui')!='Ubiquiti' -- Set the MAC address as a the message key PARTITION BY EXTRACTJSONFIELD(AFTER ,'$.mac') EMIT CHANGES; -- Declare a materialised ksqlDB table over the resulting combined stream SET 'auto.offset.reset' = 'earliest'; CREATE TABLE DEVICES AS SELECT MAC, LATEST_BY_OFFSET(SOURCE) AS SOURCE, LATEST_BY_OFFSET(NAME) AS NAME, LATEST_BY_OFFSET(IS_GUEST) AS IS_GUEST FROM ALL_DEVICES GROUP BY MAC; ---- We've built a lookup table which because we've used an aggregation (`LATEST_BY_OFFSET`) is materialised. This means that as well as the usual ksqlDB ""push query"" of streaming updates as the data changes, we can also query the state directly (known as a ""pull query""): [source,sql] ---- SELECT MAC, SOURCE, NAME, IS_GUEST FROM DEVICES WHERE ROWKEY='88:ae:07:29:e6:75' ; ---- [source,sql] ---- +------------------+----------+---------------+---------+ |MAC |SOURCE |NAME |IS_GUEST | +------------------+----------+---------------+---------+ |88:ae:07:29:e6:75 |ace.user |rmoff-ipad-pro |false | Query terminated ---- With this lookup data in place and available through ksqlDB, we can join it to the stream of pcap probe data, so instead of this: [source,sql] ---- SELECT TIMESTAMPTOSTRING(ROWTIME,'yyyy-MM-dd HH:mm:ss','GMT') AS PCAP_TS, WLAN_SA[1] AS SOURCE_ADDRESS, WLAN_SA_RESOLVED[1] AS SOURCE_ADDRESS_RESOLVED, WLAN_DA[1] AS DESTINATION_ADDRESS, WLAN_DA_RESOLVED[1] AS DESTINATION_ADDRESS_RESOLVED, WLAN_RADIO_SIGNAL_DBM[1] AS RADIO_SIGNAL_DBM, WLAN_SSID[1] AS SSID FROM PCAP_PROBE EMIT CHANGES LIMIT 5; ---- [source,sql] ---- +--------------------+------------------+------------------------+--------------------+-----------------------------+-----------------+------+ |PCAP_TS |SOURCE_ADDRESS |SOURCE_ADDRESS_RESOLVED |DESTINATION_ADDRESS |DESTINATION_ADDRESS_RESOLVED |RADIO_SIGNAL_DBM |SSID | +--------------------+------------------+------------------------+--------------------+-----------------------------+-----------------+------+ |2020-03-31 13:07:14 |f0:c3:71:2a:04:20 |f0:c3:71:2a:04:20 |ff:ff:ff:ff:ff:ff |Broadcast |-75.0 |RNM0 | |2020-03-31 13:09:41 |40:b4:cd:58:40:8f |AmazonTe_58:40:8f |ff:ff:ff:ff:ff:ff |Broadcast |-75.0 | | |2020-03-31 12:47:31 |e8:b2:ac:6f:3f:a8 |Apple_6f:3f:a8 |ff:ff:ff:ff:ff:ff |Broadcast |-79.0 | | |2020-03-31 13:12:24 |f0:c3:71:2a:04:20 |f0:c3:71:2a:04:20 |ff:ff:ff:ff:ff:ff |Broadcast |-81.0 | | |2020-03-31 13:14:31 |e8:b2:ac:6f:3f:a8 |Apple_6f:3f:a8 |ff:ff:ff:ff:ff:ff |Broadcast |-77.0 | | Limit Reached Query terminated ---- We can get this: [source,sql] ---- SELECT TIMESTAMPTOSTRING(P.ROWTIME,'yyyy-MM-dd HH:mm:ss','GMT') AS PCAP_TS, WLAN_SA[1] AS SOURCE_ADDRESS, NAME AS DEVICE_NAME, CASE WHEN IS_GUEST IS NULL THEN FALSE ELSE CASE WHEN IS_GUEST THEN FALSE ELSE TRUE END END AS IS_KNOWN_DEVICE, WLAN_SA_RESOLVED[1] AS SOURCE_ADDRESS_RESOLVED, WLAN_DA[1] AS DESTINATION_ADDRESS, WLAN_DA_RESOLVED[1] AS DESTINATION_ADDRESS_RESOLVED, WLAN_RADIO_SIGNAL_DBM[1] AS RADIO_SIGNAL_DBM, WLAN_SSID[1] AS SSID FROM PCAP_PROBE P LEFT JOIN DEVICES D ON P.WLAN_SA[1] = D.ROWKEY EMIT CHANGES LIMIT 5; ---- [source,sql] ---- +--------------------+------------------+---------------+----------------+------------------------+--------------------+-----------------------------+-----------------+-------------+ |PCAP_TS |SOURCE_ADDRESS |DEVICE_NAME |IS_KNOWN_DEVICE |SOURCE_ADDRESS_RESOLVED |DESTINATION_ADDRESS |DESTINATION_ADDRESS_RESOLVED |RADIO_SIGNAL_DBM |SSID | +--------------------+------------------+---------------+----------------+------------------------+--------------------+-----------------------------+-----------------+-------------+ |2020-03-31 13:15:49 |78:67:d7:48:e5:c7 |null |false |Apple_48:e5:c7 |ff:ff:ff:ff:ff:ff |Broadcast |-81.0 |VM9654567 | |2020-03-23 18:12:12 |e8:b2:ac:6f:3f:a8 |Gillians-iPad |true |Apple_6f:3f:a8 |ff:ff:ff:ff:ff:ff |Broadcast |-77.0 | | |2020-03-31 19:59:03 |62:45:b6:c6:7e:03 |null |false |62:45:b6:c6:7e:03 |ff:ff:ff:ff:ff:ff |Broadcast |-77.0 | | |2020-03-31 22:53:25 |44:65:0d:e0:94:66 |Robin's Kindle |true |AmazonTe_e0:94:66 |ff:ff:ff:ff:ff:ff |Broadcast |-63.0 |RNM0 | |2020-03-31 20:25:00 |30:07:4d:91:96:56 |null |false |SamsungE_91:96:56 |ff:ff:ff:ff:ff:ff |Broadcast |-79.0 |VodafoneWiFi | Limit Reached Query terminated ---- Now we can write this enriched data back into Kafka and from there to Elasticsearch: [source,sql] ---- SET 'auto.offset.reset' = 'earliest'; CREATE STREAM PCAP_PROBE_ENRICHED WITH (KAFKA_TOPIC='pcap_probe_enriched_00') AS SELECT WLAN_SA[1] AS SOURCE_ADDRESS, NAME AS SOURCE_DEVICE_NAME, CASE WHEN IS_GUEST IS NULL THEN FALSE ELSE CASE WHEN IS_GUEST THEN FALSE ELSE TRUE END END AS IS_KNOWN_DEVICE, WLAN_SA_RESOLVED[1] AS SOURCE_ADDRESS_RESOLVED, WLAN_DA[1] AS DESTINATION_ADDRESS, WLAN_DA_RESOLVED[1] AS DESTINATION_ADDRESS_RESOLVED, WLAN_RADIO_SIGNAL_DBM[1] AS RADIO_SIGNAL_DBM, WLAN_SSID[1] AS SSID, WLAN_TAG_VENDOR_DATA, WLAN_TAG_VENDOR_OUI_TYPE, WLAN_TAG_OUI FROM PCAP_PROBE P LEFT JOIN DEVICES D ON P.WLAN_SA[1] = D.ROWKEY EMIT CHANGES; CREATE SINK CONNECTOR SINK_ELASTIC_PCAP_ENRICHED_00 WITH ( 'connector.class' = 'io.confluent.connect.elasticsearch.ElasticsearchSinkConnector', 'connection.url' = 'http://elasticsearch:9200', 'topics' = 'pcap_probe_enriched_00', 'type.name' = '_doc', 'key.ignore' = 'true', 'schema.ignore' = 'true', 'key.converter' = 'org.apache.kafka.connect.storage.StringConverter', 'transforms'= 'ExtractTimestamp', 'transforms.ExtractTimestamp.type'= 'org.apache.kafka.connect.transforms.InsertField$Value', 'transforms.ExtractTimestamp.timestamp.field' = 'PCAP_TS', 'flush.timeout.ms'= 60000, 'batch.size'= 200000, 'linger.ms'= 1000, 'read.timeout.ms'= 60000 ); ---- So what can we do with this data that we couldn't if streaming the pcap directly from source into Elasticsearch directly? We can use the device names, and a filter on whether the device is known or not (based on whether the MAC has an entry in the router's internal table). Here's a useful illustration with the data. It shows, per device, the average signal strength through a period of time. Darker green means a stronger signal. image::images/kib_probe_02.png[] 1. We can accurately label all the devices, and filter for ones which are known devices 2. There's only data when a device runs a probe request - and if the device is absent there'll be no probes at all. The time period highlighted towards the bottom of the image matches when I (and my laptop, phone, and iPad) were away from home at a conference. ** You'll also notice for the iPad and `asgard03` devices (and to an extent `asgard-04`) that the signal—when present—is much stronger - because the devices are in the same room as the https://rmoff.net/2020/03/11/streaming-wi-fi-trace-data-from-raspberry-pi-to-apache-kafka-with-confluent-cloud/[Raspberry Pi that is capturing the pcap data]. One of the things that I was interested to see was whether there would be a discernable pattern in the data relating to the impact of the Coronavirus pandemic. Unfortunately my test-rig failed right around the time when the severe restrictions were put in place, but this is what it looks like for the first three weeks of March: image::images/kib_probe_03.png[] As discussed above, there's a huge caveat to this data though - tracking MAC addresses alone is not accurate, because of MAC address randomisation used by many newer devices. You can read more about it https://papers.mathyvanhoef.com/asiaccs2016.pdf[here] but in essence, this is done deliberately for privacy reasons. By charting the data out this way we can actually dig into this randomisation a bit. Looking at the recent probe activity I can see a relatively consistent number of probes, but a spike in the number of unique MACs on one of the days. image::images/kib_probe_04.png[] Drilling into that particular day there's a couple of spikes at specific points in the day: image::images/kib_probe_05.png[] So let's take a closer look at one of those. If we use a similar heatplot to above we can see that some devices (1) retain the same MAC address, and so we see multiple probes over time from it at varying strength. In other cases those (2) we can see signals of approximately the same strength (`-69` - `-67`, in orange on the image below ), but with just single probes recorded. image::images/kib_probe_06.png[] There are two scenarios that would account for the latter behaviour. The first is that there are multiple devices, each of a similar proximity to the device capturing the wifi probes, and each _only sending a single probe request in the 30 minute interval_. The second scenario is that it is a smaller number of devices, issuing multiple probe requests over time, but changing the MAC address each time. Let's see what else the data can offer us to help us pursue these hypotheses. By filtering the probe data for the signal range observed above we get this set of data, in which there's an interesting pattern to observe: image::images/kib_probe_07.png[] When devices send out probe requests they include other data about the kind of protocol that they support, and so on. These fields (including `wlan.tag.oui` and `wlan.tag.vendor.oui.type`) are not unique to each device, but the combination of the values per packet forms a lower cardinality set than the probe results alone. Looking at this set of probe requests, at the same signal strength, in the same time period, we can see that almost all of them share the same set of `wlan.tag.oui` properties image::images/kib_probe_08.png[] Using the https://gitlab.com/wireshark/wireshark/raw/master/manuf[Manufacturer's database from Wireshark] the OUIs can be decoded based on their hex representation * 4120 == 00:10:18 == Broadcom * 20722 == 00:50:F2 == Microsoft Corp. * 6130 == 00:17:F2 == Apple, Inc. If you want to dig even further into this, the data that we're streaming into Kafka can also be written to a local pcap file (add `-b duration:3600 -b files:12 -w /pcap_data/mon0` to the `shark` command to keep 12 hourly files of data), and this pcap file loaded into Wireshark to see the real guts of the data that's captured: image::images/wireshark_probe00.png[] === Wi-Fi Probe pcap pattern matching with ksqlDB The above analysis in Kibana showed how we can eyeball the data to explore and identify patterns of interest. But can we take a stream of data and automagically look for such patterns? Sure we can - with ksqlDB. [source,sql] ---- SET 'auto.offset.reset' = 'earliest'; CREATE TABLE OUI_FINGERPRINT_PROBES_01 AS SELECT WLAN_TAG_VENDOR_DATA, WLAN_TAG_VENDOR_OUI_TYPE, WLAN_TAG_OUI, COUNT(*) AS PROBE_COUNT, COUNT_DISTINCT(WLAN_SA[1]) AS SOURCE_MAC_ADDRESS_COUNT, COLLECT_SET(WLAN_SA[1]) AS SOURCE_MAC_ADDRESSES, TIMESTAMPTOSTRING(WINDOWSTART,'yyyy-MM-dd HH:mm:ss','GMT') AS FIRST_PROBE, TIMESTAMPTOSTRING(WINDOWEND,'yyyy-MM-dd HH:mm:ss','GMT') AS LAST_PROBE, (WINDOWEND-WINDOWSTART)/1000 AS SESSION_LENGTH_SEC, MAX(WLAN_RADIO_SIGNAL_DBM[1])-MIN(WLAN_RADIO_SIGNAL_DBM[1]) AS SIGNAL_DBM_RANGE, HISTOGRAM(CAST(WLAN_RADIO_SIGNAL_DBM[1] AS VARCHAR)) AS SIGNAL_DBM_DISTRIBUTION FROM PCAP_PROBE WINDOW SESSION (5 MINUTES) GROUP BY WLAN_TAG_VENDOR_DATA, WLAN_TAG_VENDOR_OUI_TYPE, WLAN_TAG_OUI HAVING COUNT_DISTINCT(WLAN_SA[1]) > 2 EMIT CHANGES ; ---- This uses a *session window* to identify probe requests matching this pattern: * identical set of properties (`wlan.tag.oui`, `wlan.tag.vendor.oui.type`, `wlan.tag.vendor.data`) * issued with a gap of no more than five minutes apart * more than two different source MAC addresses * Signal strength of all probes within 3 https://en.wikipedia.org/wiki/DBm[dBm] of each other All requests matching this pattern are grouped into a single result, from which we can see how many requests there were, which source MACs were used (and how many), the range of signal strengths, and so on: [source,sql] ---- SELECT ROWKEY AS FINGERPRINT, PROBE_COUNT, SOURCE_MAC_ADDRESS_COUNT, SOURCE_MAC_ADDRESSES, FIRST_PROBE, LAST_PROBE, SIGNAL_DBM_DISTRIBUTION FROM OUI_FINGERPRINT_PROBES_01 WHERE WINDOWSTART > STRINGTOTIMESTAMP('2020-04-12 14:55:00','yyyy-MM-dd HH:mm:ss') AND WINDOWSTART < STRINGTOTIMESTAMP('2020-04-12 15:35:00','yyyy-MM-dd HH:mm:ss') EMIT CHANGES; ---- [source,sql] ---- +---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+ |FINGERPRINT |PROBE_COUNT |SOURCE_MAC_ADDRESS_CO|SOURCE_MAC_ADDRESSES |FIRST_PROBE |LAST_PROBE |SIGNAL_DBM_DISTRIBUTI| | | |UNT | | | |ON | +---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+---------------------+ |[0a:00:01:04:00:00:00|16 |14 |[6e:6f:18:05:08:16, 7|2020-04-13 14:21:56 |2020-04-13 14:45:03 |{-73.0=4, -71.0=11, -| |:00, 02:00:00:10:00:0| | |2:97:6c:9b:18:e9, 7e:| | |65.0=1} | |0]|+|[10, 8, 2]|+|[61| | |08:a9:8e:6c:79, 9e:89| | | | |30, 20722, 4120] | | |:88:d4:3f:64, 7a:5f:3| | | | | | | |f:52:1d:ae, a6:ae:14:| | | | | | | |78:b4:6a, 8e:2b:57:2a| | | | | | | |:e7:ff, 86:d8:dc:50:a| | | | | | | |a:b0, 8a:db:cf:ba:65:| | | | | | | |3a, 5a:83:54:0a:4f:8c| | | | | | | |, 62:d4:97:c2:ac:62, | | | | | | | |52:b2:39:e7:b1:cf, 42| | | | | | | |:c4:7b:48:99:54, d6:5| | | | | | | |f:7b:35:0b:a6] | | | | ---- == Analysing streams of data with ksqlDB Let us now take a step back from the nitty-gritty of Wi-Fi probe requests and randomisation of MAC addresses, and take a higher level view of the data we're capturing. Using the enriched stream of data that we've created from the live stream of packet captures joined to device information from my router, we can build a picture of all the devices that we see along with some summary statistics about them - when they last probed, which SSIDs they look for, and so on. [source,sql] ---- SET 'auto.offset.reset' = 'earliest'; CREATE TABLE PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02 AS SELECT CASE WHEN SOURCE_DEVICE_NAME IS NULL THEN SOURCE_ADDRESS_RESOLVED ELSE SOURCE_DEVICE_NAME END AS SOURCE, COUNT(*) AS PCAP_PROBES, MIN(ROWTIME) AS EARLIEST_PROBE, MAX(ROWTIME) AS LATEST_PROBE, MIN(RADIO_SIGNAL_DBM) AS MIN_RADIO_SIGNAL_DBM, MAX(RADIO_SIGNAL_DBM) AS MAX_RADIO_SIGNAL_DBM, AVG(RADIO_SIGNAL_DBM) AS AVG_RADIO_SIGNAL_DBM, COLLECT_SET(SSID) AS PROBED_SSIDS, COUNT_DISTINCT(SSID) AS UNIQUE_SSIDS_PROBED, COUNT_DISTINCT(DESTINATION_ADDRESS) AS UNIQUE_DESTINATION_ADDRESSES FROM PCAP_PROBE_ENRICHED GROUP BY CASE WHEN SOURCE_DEVICE_NAME IS NULL THEN SOURCE_ADDRESS_RESOLVED ELSE SOURCE_DEVICE_NAME END; ---- Under the covers, this aggregation is materialised by ksqlDB, which means that we can query the state directly: [source,sql] ---- SELECT SOURCE_DEVICE_NAME, PCAP_PROBES, TIMESTAMPTOSTRING(EARLIEST_PROBE,'yyyy-MM-dd HH:mm:ss','GMT') AS EARLIEST_PROBE, TIMESTAMPTOSTRING(LATEST_PROBE,'yyyy-MM-dd HH:mm:ss','GMT') AS LATEST_PROBE, PROBED_SSIDS, UNIQUE_SSIDS_PROBED FROM PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02 WHERE ROWKEY='asgard03'; ---- [source,sql] ---- +-------------------+------------+--------------------+--------------------+----------------------------+--------------------+ |SOURCE_DEVICE_NAME |PCAP_PROBES |EARLIEST_PROBE |LATEST_PROBE |PROBED_SSIDS |UNIQUE_SSIDS_PROBED | +-------------------+------------+--------------------+--------------------+----------------------------+--------------------+ |asgard03 |3110 |2020-02-28 22:51:22 |2020-04-14 11:06:13 |[null, , FULLERS, RNM0, loew|12 | | | | | |s_conf, _The Wheatley Free W| | | | | | |iFi, skyclub, CrossCountryWi| | | | | | |Fi, QConLondon2020, FreePubW| | | | | | |iFi, Marriott_PUBLIC, Loews,| | | | | | | Escape Lounge WiFi] | | Query terminated ---- This is for my Mac laptop, and you can see various public and private networks being looked for. The names of these match those on my known WiFi networks settings image::images/mac_wifi01.png[] ksqlDB is proving pretty handy here. We've taken a raw stream of data, and using a couple of SQL statements built a stateful, scalable, aggregation that we can query in place from the ksqlDB prompt. We can also use the REST API to query it programatically, for example to see when a given device last ran a probe: [source,bash] ---- $ curl -s -XPOST ""http://localhost:8088/query"" \\ -H ""Content-Type: application/vnd.ksql.v1+json; charset=utf-8"" \\ -d '{""ksql"":""SELECT TIMESTAMPTOSTRING(LATEST_PROBE,'\\''yyyy-MM-dd HH:mm:ss'\\'','\\''GMT'\\'') AS LATEST_PROBE FROM PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02 WHERE ROWKEY='\\''asgard03'\\'';""}' |jq '.[].row.columns' [ ""2020-04-08 06:39:45"" ] ---- And of course, we can take the data that ksqlDB is aggregating for us and push it down to one, or more, target systems for further use and analysis: *TODO*: diagram showing pcap -> kafka -> ksqlDB -> Kafka -> postgres & elastic * Elasticsearch + [source,sql] ---- CREATE SINK CONNECTOR SINK_ELASTIC_PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02 WITH ( 'connector.class' = 'io.confluent.connect.elasticsearch.ElasticsearchSinkConnector', 'connection.url' = 'http://elasticsearch:9200', 'topics' = 'PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02', 'type.name' = '_doc', 'key.ignore' = 'false', 'schema.ignore' = 'true', 'transforms' = 'appendTimestampToColName', 'transforms.appendTimestampToColName.type' = 'org.apache.kafka.connect.transforms.ReplaceField$Value', 'transforms.appendTimestampToColName.renames' = 'EARLIEST_PROBE:EARLIEST_PROBE_TS,LATEST_PROBE:LATEST_PROBE_TS', 'key.converter' = 'org.apache.kafka.connect.storage.StringConverter' ); ---- + ** `'key.ignore' = 'false'` which means that it takes the key of the Kafka message (which is set in the `CREATE TABLE` above to the `SOURCE` field) and so will update documents in place when changes occur in the source table. ** A Single Message Transform (SMT) is used to append `_TS` to the date fields. I created a document mapping template in Elasticsearch to match any field named `*_TS` as a date, which these two fields are (but stored as `BIGINT` epoch in ksqlDB) * Postgres + [source,sql] ---- CREATE SINK CONNECTOR SINK_POSTGRES_PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02 WITH ( 'connector.class' = 'io.confluent.connect.jdbc.JdbcSinkConnector', 'connection.url' = 'jdbc:postgresql://postgres:5432/', 'connection.user' = 'postgres', 'connection.password' = 'postgres', 'topics' = 'PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02', 'key.converter' = 'org.apache.kafka.connect.storage.StringConverter', 'auto.create' = 'true', 'auto.evolve' = 'true', 'insert.mode' = 'upsert', 'pk.mode' = 'record_value', 'pk.fields' = 'SOURCE', 'table.name.format' = '${topic}', 'transforms' = 'dropArray,setTimestampType0,setTimestampType1', 'transforms.dropArray.type' = 'org.apache.kafka.connect.transforms.ReplaceField$Value', 'transforms.dropArray.blacklist' = 'PROBED_SSIDS', 'transforms.setTimestampType0.type'= 'org.apache.kafka.connect.transforms.TimestampConverter$Value', 'transforms.setTimestampType0.field'= 'EARLIEST_PROBE', 'transforms.setTimestampType0.target.type' ='Timestamp', 'transforms.setTimestampType1.type'= 'org.apache.kafka.connect.transforms.TimestampConverter$Value', 'transforms.setTimestampType1.field'= 'LATEST_PROBE', 'transforms.setTimestampType1.target.type' ='Timestamp' ); ---- + ** Since the JDBC sink doesn't support writing array objects to Postgres (you'll get the error `org.apache.kafka.connect.errors.ConnectException: null (ARRAY) type doesn't have a mapping to the SQL database column type`) we just drop it here using the `ReplaceField` SMT. ** The `TimestampConverter` Single Message Transform is used to set the type of the two timestamp fields so that they're ingested into Postgres as timestamps (and not BIGINT) ** To get the rows updating in place as the source table in ksqlDB changes `'insert.mode'` is set to `upsert`. The primary key on the target table in Postgres is set to be built from the value of `SOURCE` (`pk.fields`) in the message value (`record_value`). + [source,sql] ---- postgres=# \\d ""PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02"" Table ""public.PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02"" Column | Type | Collation | Nullable | Default ------------------------------+------------------+-----------+----------+--------- SOURCE | text | | not null | … Indexes: ""PCAP_PROBE_STATS_BY_SOURCE_DEVICE_02_pkey"" PRIMARY KEY, btree (""SOURCE"") ---- + Since `SOURCE` is also the record _key_ in the Kafka message you could use `pk.mode` = `record_key` here, but it would still need to be materialised onto the Postgres table, and so you'd end up with two fields in Postgres with the same value (`SOURCE`, plus whatever you set `pk.fields` to as in this context it would be used by the connector as the _name of the field in Postgres_ to store the Kafka message key in): + [source,sql] ---- 'pk.mode' = 'record_key', 'pk.fields' = 'PK', ---- + [source,sql] ---- postgres=# \\d ""PCAP_PROBE_STATS_BY_SOURCE_DEVICE"" Table ""public.PCAP_PROBE_STATS_BY_SOURCE_DEVICE"" Column | Type | Collation | Nullable | Default ------------------------------+------------------+-----------+----------+--------- SOURCE | text | | | … PK | text | | not null | Indexes: ""PCAP_PROBE_STATS_BY_SOURCE_DEVICE_pkey"" PRIMARY KEY, btree (""PK"") postgres=# SELECT ""SOURCE"",""PK"" FROM ""PCAP_PROBE_STATS_BY_SOURCE_DEVICE""; SOURCE | PK -------------------+------------------- ea:28:50:4d:44:fb | ea:28:50:4d:44:fb 12:c3:06:85:53:96 | 12:c3:06:85:53:96 … (3 rows) ---- == Graph relationships in the data *TODO*: diagram showing pcap -> kafka -> ksqlDB -> Kafka -> neo4j Phew. That was some deep stuff we did there with both Elasticsearch & Kibana for analysis and identifying patterns, and ksqlDB for building stateful aggregations of these patterns and general statistics on the data. Let's look at what else we can do with streams of data that we've got in Kafka. Here we'll take the stream of probe requests that we filtered into its own topic and stream it to Neo4j: [source,sql] ---- CREATE SINK CONNECTOR SINK_NEO4J_PROBES_01 WITH ( 'connector.class'= 'streams.kafka.connect.sink.Neo4jSinkConnector', 'topics'= 'pcap_probe_enriched_00', 'neo4j.server.uri'= 'bolt://neo4j:7687', 'neo4j.authentication.basic.username'= 'neo4j', 'neo4j.authentication.basic.password'= 'connect', 'neo4j.topic.cypher.pcap_probe_enriched_00'= 'MERGE (source:source{mac: event.SOURCE_ADDRESS, mac_resolved: event.SOURCE_ADDRESS_RESOLVED, device_name: coalesce(event.SOURCE_DEVICE_NAME,""""), is_known: event.IS_KNOWN_DEVICE}) MERGE (ssid:ssid{name: coalesce(event.SSID, """")}) MERGE (ssid)<-[:LOOKED_FOR_SSID]-(source)' ); ---- From here we can really dig into the property graph relationships, for example that exist between devices and the Wi-Fi networks (SSIDs) that they scan for. Here we can see my known devices (denoted by diamonds with red edging) scanning for my home Wi-Fi network, and a couple of these devices also scanning for other public networks (pubs, airline lounges, train Wi-Fi, etc) which other non-known devices also scan for: image::images/cyto01.png[] You also get patterns like this, where some devices (yellow dots) have evidently connected to (and are thus scanning for) many networks, whilst others overlap only on common public ones (`Northern-FreeWiFi` is from the local train company, `BTWiFi-with-FON` is a shared Wi-Fi service) image::images/cyto02.png[] Other devices clearly just connect to one network only, ignoring all others image::images/cyto03.png[] == Conclusion Kafka is a great platform into which you can stream and store high volumes of data, and on which you can process and analyse it using tools such as ksqlDB, Elasticsearch, and Neo4j. With the ability to create connectors from within ksqlDB it is easy to integrate systems both pulling data into Kafka and pushing it out downstream. >>>>> Move to other posts: == Testing with Confluent Cloud locally (replicator) set local retention to match remote retention ? ",12431,False,2417.2211759388692,median "[[production-ready]] = Spring Boot Actuator: Production-ready features [partintro] -- Spring Boot includes a number of additional features to help you monitor and manage your application when it's pushed to production. You can choose to manage and monitor your application using HTTP endpoints, with JMX or even by remote shell (SSH or Telnet). Auditing, health and metrics gathering can be automatically applied to your application. Actuator HTTP endpoints are only available with a Spring MVC-based application. In particular, it will not work with Jersey unless you enable Spring MVC as well. -- [[production-ready-enabling]] == Enabling production-ready features The {github-code}/spring-boot-actuator[`spring-boot-actuator`] module provides all of Spring Boot's production-ready features. The simplest way to enable the features is to add a dependency to the `spring-boot-starter-actuator` '`Starter POM`'. .Definition of Actuator **** An actuator is a manufacturing term, referring to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change. **** To add the actuator to a Maven based project, add the following '`starter`' dependency: [source,xml,indent=0] ---- org.springframework.boot spring-boot-starter-actuator ---- For Gradle, use the declaration: [source,groovy,indent=0] ---- dependencies { compile(""org.springframework.boot:spring-boot-starter-actuator"") } ---- [[production-ready-endpoints]] == Endpoints Actuator endpoints allow you to monitor and interact with your application. Spring Boot includes a number of built-in endpoints and you can also add your own. For example the `health` endpoint provides basic application health information. The way that endpoints are exposed will depend on the type of technology that you choose. Most applications choose HTTP monitoring, where the ID of the endpoint is mapped to a URL. For example, by default, the `health` endpoint will be mapped to `/health`. The following endpoints are available: [cols=""2,5,1""] |=== | ID | Description | Sensitive |`actuator` |Provides a hypermedia-based ""`discovery page`"" for the other endpoints. Requires Spring HATEOAS to be on the classpath. |true |`autoconfig` |Displays an auto-configuration report showing all auto-configuration candidates and the reason why they '`were`' or '`were not`' applied. |true |`beans` |Displays a complete list of all the Spring beans in your application. |true |`configprops` |Displays a collated list of all `@ConfigurationProperties`. |true |`dump` |Performs a thread dump. |true |`env` |Exposes properties from Spring's `ConfigurableEnvironment`. |true |`flyway` |Shows any Flyway database migrations that have been applied. |true |`health` |Shows application health information (when the application is secure, a simple '`status`' when accessed over an unauthenticated connection or full message details when authenticated). |false |`info` |Displays arbitrary application info. |false |`liquibase` |Shows any Liquibase database migrations that have been applied. |true |`logfile` |Returns the contents of the logfile (if `logging.file` or `logging.path` properties have been set). Only available via MVC. |true |`metrics` |Shows '`metrics`' information for the current application. |true |`mappings` |Displays a collated list of all `@RequestMapping` paths. |true |`shutdown` |Allows the application to be gracefully shutdown (not enabled by default). |true |`trace` |Displays trace information (by default the last few HTTP requests). |true |=== NOTE: Depending on how an endpoint is exposed, the `sensitive` property may be used as a security hint. For example, sensitive endpoints will require a username/password when they are accessed over HTTP (or simply disabled if web security is not enabled). [[production-ready-customizing-endpoints]] === Customizing endpoints Endpoints can be customized using Spring properties. You can change if an endpoint is `enabled`, if it is considered `sensitive` and even its `id`. For example, here is an `application.properties` that changes the sensitivity and id of the `beans` endpoint and also enables `shutdown`. [source,properties,indent=0] ---- endpoints.beans.id=springbeans endpoints.beans.sensitive=false endpoints.shutdown.enabled=true ---- NOTE: The prefix ‟`endpoints` + `.` + `name`” is used to uniquely identify the endpoint that is being configured. By default, all endpoints except for `shutdown` are enabled. If you prefer to specifically ""`opt-in`"" endpoint enablement you can use the `endpoints.enabled` property. For example, the following will disable _all_ endpoints except for `info`: [source,properties,indent=0] ---- endpoints.enabled=false endpoints.info.enabled=true ---- [[production-ready-endpoint-hypermedia]] === Hypermedia for actuator MVC endpoints If http://projects.spring.io/spring-hateoas[Spring HATEOAS] is on the classpath (e.g. through the `spring-boot-starter-hateoas` or if you are using http://projects.spring.io/spring-data-rest[Spring Data REST]) then the HTTP endpoints from the Actuator are enhanced with hypermedia links, and a ""`discovery page`"" is added with links to all the endpoints. The ""`discovery page`"" is available on `/actuator` by default. It is implemented as an endpoint, allowing properties to be used to configure its path (`endpoints.actuator.path`) and whether or not it is enabled (`endpoints.actuator.enabled`). When a custom management context path is configured, the ""`discovery page`"" will automatically move from `/actuator` to the root of the management context. For example, if the management context path is `/management` then the discovery page will be available from `/management`. If the https://github.com/mikekelly/hal-browser[HAL Browser] is on the classpath via its webjar (`org.webjars:hal-browser`), or via the `spring-data-rest-hal-browser` then an HTML ""`discovery page`"", in the form of the HAL Browser, is also provided. [[production-ready-endpoint-cors]] === CORS support http://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a http://www.w3.org/TR/cors/[W3C specification] that allows you to specify in a flexible way what kind of cross domain requests are authorized. Actuator's MVC endpoints can be configured to support such scenario. CORS support is disabled by default and is only enabled once the `endpoints.cors.allowed-origins` property has been set. The configuration below permits `GET` and `POST` calls from the `example.com` domain: [source,properties,indent=0] ---- endpoints.cors.allowed-origins=http://example.com endpoints.cors.allowed-methods=GET,POST ---- TIP: Check {sc-spring-boot-actuator}/autoconfigure/EndpointCorsProperties.{sc-ext}[EndpointCorsProperties] for a complete list of options. [[production-ready-customizing-endpoints-programmatically]] === Adding custom endpoints If you add a `@Bean` of type `Endpoint` then it will automatically be exposed over JMX and HTTP (if there is an server available). An HTTP endpoints can be customized further by creating a bean of type `MvcEndpoint`. Your `MvcEndpoint` is not a `@Controller` but it can use `@RequestMapping` (and `@Managed*`) to expose resources. TIP: If you are doing this as a library feature consider adding a configuration class to `/META-INF/spring.factories` under the key `org.springframework.boot.actuate.autoconfigure.EndpointWebMvcConfiguration`. If you do that then the endpoint will move to a child context with all the other MVC endpoints if your users ask for a separate management port or address. A configuration declared this way can be a `WebConfigurerAdapter` if it wants to add static resources (for instance) to the management endpoints. [[production-ready-health]] === Health information Health information can be used to check the status of your running application. It is often used by monitoring software to alert someone if a production system goes down. The default information exposed by the `health` endpoint depends on how it is accessed. For an unauthenticated connection in a secure application a simple '`status`' message is returned, and for an authenticated connection additional details are also displayed (see <> for HTTP details). Health information is collected from all {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] beans defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `HealthIndicators` and you can also write your own. === Security with HealthIndicators Information returned by `HealthIndicators` is often somewhat sensitive in nature. For example, you probably don't want to publish details of your database server to the world. For this reason, by default, only the health status is exposed over an unauthenticated HTTP connection. If you are happy for complete health information to always be exposed you can set `endpoints.health.sensitive` to `false`. Health responses are also cached to prevent ""`denial of service`"" attacks. Use the `endpoints.health.time-to-live` property if you want to change the default cache period of 1000 milliseconds. ==== Auto-configured HealthIndicators The following `HealthIndicators` are auto-configured by Spring Boot when appropriate: [cols=""1,4""] |=== |Name |Description |{sc-spring-boot-actuator}/health/DiskSpaceHealthIndicator.{sc-ext}[`DiskSpaceHealthIndicator`] |Checks for low disk space. |{sc-spring-boot-actuator}/health/DataSourceHealthIndicator.{sc-ext}[`DataSourceHealthIndicator`] |Checks that a connection to `DataSource` can be obtained. |{sc-spring-boot-actuator}/health/ElasticsearchHealthIndicator.{sc-ext}[`ElasticsearchHealthIndicator`] |Checks that an ElasticSearch cluster is up. |{sc-spring-boot-actuator}/health/JmsHealthIndicator.{sc-ext}[`JmsHealthIndicator`] |Checks that a JMS broker is up. |{sc-spring-boot-actuator}/health/MailHealthIndicator.{sc-ext}[`MailHealthIndicator`] |Checks that a mail server is up. |{sc-spring-boot-actuator}/health/MongoHealthIndicator.{sc-ext}[`MongoHealthIndicator`] |Checks that a Mongo database is up. |{sc-spring-boot-actuator}/health/RabbitHealthIndicator.{sc-ext}[`RabbitHealthIndicator`] |Checks that a Rabbit server is up. |{sc-spring-boot-actuator}/health/RedisHealthIndicator.{sc-ext}[`RedisHealthIndicator`] |Checks that a Redis server is up. |{sc-spring-boot-actuator}/health/SolrHealthIndicator.{sc-ext}[`SolrHealthIndicator`] |Checks that a Solr server is up. |=== TIP: It is possible to disable them all using the `management.health.defaults.enabled` property. ==== Writing custom HealthIndicators To provide custom health information you can register Spring beans that implement the {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] interface. You need to provide an implementation of the `health()` method and return a `Health` response. The `Health` response should include a status and can optionally include additional details to be displayed. [source,java,indent=0] ---- import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MyHealth implements HealthIndicator { @Override public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { return Health.down().withDetail(""Error Code"", errorCode).build(); } return Health.up().build(); } } ---- In addition to Spring Boot's predefined {sc-spring-boot-actuator}/health/Status.{sc-ext}[`Status`] types, it is also possible for `Health` to return a custom `Status` that represents a new system state. In such cases a custom implementation of the {sc-spring-boot-actuator}/health/HealthAggregator.{sc-ext}[`HealthAggregator`] interface also needs to be provided, or the default implementation has to be configured using the `management.health.status.order` configuration property. For example, assuming a new `Status` with code `FATAL` is being used in one of your `HealthIndicator` implementations. To configure the severity order add the following to your application properties: [source,properties,indent=0] ---- management.health.status.order=DOWN, OUT_OF_SERVICE, UNKNOWN, UP ---- You might also want to register custom status mappings with the `HealthMvcEndpoint` if you access the health endpoint over HTTP. For example you could map `FATAL` to `HttpStatus.SERVICE_UNAVAILABLE`. [[production-ready-application-info]] === Custom application info information You can customize the data exposed by the `info` endpoint by setting `+info.*+` Spring properties. All `Environment` properties under the info key will be automatically exposed. For example, you could add the following to your `application.properties`: [source,properties,indent=0] ---- info.app.name=MyService info.app.description=My awesome service info.app.version=1.0.0 ---- [[production-ready-application-info-automatic-expansion]] ==== Automatically expand info properties at build time Rather than hardcoding some properties that are also specified in your project's build configuration, you can automatically expand info properties using the existing build configuration instead. This is possible in both Maven and Gradle. [[production-ready-application-info-automatic-expansion-maven]] ===== Automatic property expansion using Maven You can automatically expand info properties from the Maven project using resource filtering. If you use the `spring-boot-starter-parent` you can then refer to your Maven '`project properties`' via `@..@` placeholders, e.g. [source,properties,indent=0] ---- project.artifactId=myproject project.name=Demo project.version=X.X.X.X project.description=Demo project for info endpoint info.build.artifact=@project.artifactId@ info.build.name=@project.name@ info.build.description=@project.description@ info.build.version=@project.version@ ---- TIP: The `spring-boot:run` can add `src/main/resources` directly to the classpath (for hot reloading purposes) if you enable the `addResources` flag. This circumvents the resource filtering and this feature. You can use the `exec:java` goal instead or customize the plugin's configuration, see the {spring-boot-maven-plugin-site}/usage.html[plugin usage page] for more details. If you don't use the starter parent, in your `pom.xml` you need (inside the `` element): [source,xml,indent=0] ---- src/main/resources true ---- and (inside ``): [source,xml,indent=0] ---- org.apache.maven.plugins maven-resources-plugin 2.6 @ false ---- NOTE: The `useDefaultDelimiters` property is important if you are using standard Spring placeholders in your configuration (e.g. `${foo}`). These may be expanded by the build if that property is not set to `false`. [[production-ready-application-info-automatic-expansion-gradle]] ===== Automatic property expansion using Gradle You can automatically expand info properties from the Gradle project by configuring the Java plugin's `processResources` task to do so: [source,groovy,indent=0] ---- processResources { expand(project.properties) } ---- You can then refer to your Gradle project's properties via placeholders, e.g. [source,properties,indent=0] ---- info.build.name=${name} info.build.description=${description} info.build.version=${version} ---- NOTE: Gradle's `expand` method uses Groovy's `SimpleTemplateEngine` which transforms `${..}` tokens. The `${..}` style conflicts with Spring's own property placeholder mechanism. To use Spring property placeholders together with automatic expansion the Spring property placeholders need to be escaped like `\\${..}`. [[production-ready-git-commit-information]] ==== Git commit information Another useful feature of the `info` endpoint is its ability to publish information about the state of your `git` source code repository when the project was built. If a `git.properties` file is contained in your jar the `git.branch` and `git.commit` properties will be loaded. For Maven users the `spring-boot-starter-parent` POM includes a pre-configured plugin to generate a `git.properties` file. Simply add the following declaration to your POM: [source,xml,indent=0] ---- pl.project13.maven git-commit-id-plugin ---- Gradle users can achieve the same result using the https://plugins.gradle.org/plugin/com.gorylenko.gradle-git-properties[`gradle-git-properties`] plugin [source,groovy,indent=0] ---- plugins { id ""com.gorylenko.gradle-git-properties"" version ""1.4.6"" } ---- [[production-ready-monitoring]] == Monitoring and management over HTTP If you are developing a Spring MVC application, Spring Boot Actuator will auto-configure all enabled endpoints to be exposed over HTTP. The default convention is to use the `id` of the endpoint as the URL path. For example, `health` is exposed as `/health`. [[production-ready-sensitive-endpoints]] === Securing sensitive endpoints If you add '`Spring Security`' to your project, all sensitive endpoints exposed over HTTP will be protected. By default '`basic`' authentication will be used with the username `user` and a generated password (which is printed on the console when the application starts). TIP: Generated passwords are logged as the application starts. Search for '`Using default security password`'. You can use Spring properties to change the username and password and to change the security role required to access the endpoints. For example, you might set the following in your `application.properties`: [source,properties,indent=0] ---- security.user.name=admin security.user.password=secret management.security.role=SUPERUSER ---- TIP: If you don't use Spring Security and your HTTP endpoints are exposed publicly, you should carefully consider which endpoints you enable. See <> for details of how you can set `endpoints.enabled` to `false` then ""`opt-in`"" only specific endpoints. [[production-ready-customizing-management-server-context-path]] === Customizing the management endpoint paths Sometimes it is useful to group all management endpoints under a single path. For example, your application might already use `/info` for another purpose. You can use the `management.context-path` property to set a prefix for your management endpoint: [source,properties,indent=0] ---- management.context-path=/manage ---- The `application.properties` example above will change the endpoint from `/{id}` to `/manage/{id}` (e.g. `/manage/info`). You can also change the ""`id`"" of an endpoint (using `endpoints.{name}.id`) which then changes the default resource path for the MVC endpoint. Legal endpoint ids are composed only of alphanumeric characters (because they can be exposed in a number of places, including JMX object names, where special characters are forbidden). The MVC path can be changed separately by configuring `endpoints.{name}.path`, and there is no validation on those values (so you can use anything that is legal in a URL path). For example, to change the location of the `/health` endpoint to `/ping/me` you can set `endpoints.health.path=/ping/me`. TIP: If you provide a custom `MvcEndpoint` remember to include a settable `path` property, and default it to `/{id}` if you want your code to behave like the standard MVC endpoints. (Take a look at the `HealthMvcEndpoint` to see how you might do that.) If your custom endpoint is an `Endpoint` (not an `MvcEndpoint`) then Spring Boot will take care of the path for you. [[production-ready-customizing-management-server-port]] === Customizing the management server port Exposing management endpoints using the default HTTP port is a sensible choice for cloud based deployments. If, however, your application runs inside your own data center you may prefer to expose endpoints using a different HTTP port. The `management.port` property can be used to change the HTTP port. [source,properties,indent=0] ---- management.port=8081 ---- Since your management port is often protected by a firewall, and not exposed to the public you might not need security on the management endpoints, even if your main application is secure. In that case you will have Spring Security on the classpath, and you can disable management security like this: [source,properties,indent=0] ---- management.security.enabled=false ---- (If you don't have Spring Security on the classpath then there is no need to explicitly disable the management security in this way, and it might even break the application.) [[production-ready-customizing-management-server-address]] === Customizing the management server address You can customize the address that the management endpoints are available on by setting the `management.address` property. This can be useful if you want to listen only on an internal or ops-facing network, or to only listen for connections from `localhost`. NOTE: You can only listen on a different address if the port is different to the main server port. Here is an example `application.properties` that will not allow remote management connections: [source,properties,indent=0] ---- management.port=8081 management.address=127.0.0.1 ---- [[production-ready-disabling-http-endpoints]] === Disabling HTTP endpoints If you don't want to expose endpoints over HTTP you can set the management port to `-1`: [source,properties,indent=0] ---- management.port=-1 ---- [[production-ready-health-access-restrictions]] === HTTP health endpoint access restrictions The information exposed by the health endpoint varies depending on whether or not it's accessed anonymously, and whether or not the enclosing application is secure. By default, when accessed anonymously in a secure application, any details about the server's health are hidden and the endpoint will simply indicate whether or not the server is up or down. Furthermore, when accessed anonymously, the response is cached for a configurable period to prevent the endpoint being used in a denial of service attack. The `endpoints.health.time-to-live` property is used to configure the caching period in milliseconds. It defaults to 1000, i.e. one second. The above-described restrictions can be enhanced, thereby allowing only authenticated users full access to the health endpoint in a secure application. To do so, set `endpoints.health.sensitive` to `true`. Here's a summary of behavior (with default `sensitive` flag value ""`false`"" indicated in bold): |==== | `management.security.enabled` | `endpoints.health.sensitive` | Unauthenticated | Authenticated |false |**false** |Full content |Full content |false |true |Status only |Full content |true |**false** |Status only |Full content |true |true |No content |Full content |==== [[production-ready-jmx]] == Monitoring and management over JMX Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default Spring Boot will expose management endpoints as JMX MBeans under the `org.springframework.boot` domain. [[production-ready-custom-mbean-names]] === Customizing MBean names The name of the MBean is usually generated from the `id` of the endpoint. For example the `health` endpoint is exposed as `org.springframework.boot/Endpoint/healthEndpoint`. If your application contains more than one Spring `ApplicationContext` you may find that names clash. To solve this problem you can set the `endpoints.jmx.unique-names` property to `true` so that MBean names are always unique. You can also customize the JMX domain under which endpoints are exposed. Here is an example `application.properties`: [source,properties,indent=0] ---- endpoints.jmx.domain=myapp endpoints.jmx.unique-names=true ---- [[production-ready-disable-jmx-endpoints]] === Disabling JMX endpoints If you don't want to expose endpoints over JMX you can set the `endpoints.jmx.enabled` property to `false`: [source,properties,indent=0] ---- endpoints.jmx.enabled=false ---- [[production-ready-jolokia]] === Using Jolokia for JMX over HTTP Jolokia is a JMX-HTTP bridge giving an alternative method of accessing JMX beans. To use Jolokia, simply include a dependency to `org.jolokia:jolokia-core`. For example, using Maven you would add the following: [source,xml,indent=0] ---- org.jolokia jolokia-core ---- Jolokia can then be accessed using `/jolokia` on your management HTTP server. [[production-ready-customizing-jolokia]] ==== Customizing Jolokia Jolokia has a number of settings that you would traditionally configure using servlet parameters. With Spring Boot you can use your `application.properties`, simply prefix the parameter with `jolokia.config.`: [source,properties,indent=0] ---- jolokia.config.debug=true ---- [[production-ready-disabling-jolokia]] ==== Disabling Jolokia If you are using Jolokia but you don't want Spring Boot to configure it, simply set the `endpoints.jolokia.enabled` property to `false`: [source,properties,indent=0] ---- endpoints.jolokia.enabled=false ---- [[production-ready-remote-shell]] == Monitoring and management using a remote shell Spring Boot supports an integrated Java shell called '`CRaSH`'. You can use CRaSH to `ssh` or `telnet` into your running application. To enable remote shell support, add the following dependency to your project: [source,xml,indent=0] ---- org.springframework.boot spring-boot-starter-remote-shell ---- TIP: If you want to also enable telnet access you will additionally need a dependency on `org.crsh:crsh.shell.telnet`. NOTE: CRaSH requires to run with a JDK as it compiles commands on the fly. If a basic `help` command fails, you are probably running with a JRE. [[production-ready-connecting-to-the-remote-shell]] === Connecting to the remote shell By default the remote shell will listen for connections on port `2000`. The default user is `user` and the default password will be randomly generated and displayed in the log output. If your application is using Spring Security, the shell will use <> by default. If not, a simple authentication will be applied and you should see a message like this: [indent=0] ---- Using default password for shell access: ec03e16c-4cf4-49ee-b745-7c8255c1dd7e ---- Linux and OSX users can use `ssh` to connect to the remote shell, Windows users can download and install http://www.putty.org/[PuTTY]. [indent=0,subs=""attributes""] ---- $ ssh -p 2000 user@localhost user@localhost's password: . ____ _ __ _ _ /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\ ( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\ \\\\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v{spring-boot-version}) on myhost ---- Type `help` for a list of commands. Spring Boot provides `metrics`, `beans`, `autoconfig` and `endpoint` commands. [[production-ready-remote-shell-credentials]] ==== Remote shell credentials You can use the `shell.auth.simple.user.name` and `shell.auth.simple.user.password` properties to configure custom connection credentials. It is also possible to use a '`Spring Security`' `AuthenticationManager` to handle login duties. See the {dc-spring-boot-actuator}/autoconfigure/CrshAutoConfiguration.{dc-ext}[`CrshAutoConfiguration`] and {dc-spring-boot-actuator}/autoconfigure/ShellProperties.{dc-ext}[`ShellProperties`] Javadoc for full details. [[production-ready-extending-the-remote-shell]] === Extending the remote shell The remote shell can be extended in a number of interesting ways. [[production-ready-remote-commands]] ==== Remote shell commands You can write additional shell commands using Groovy or Java (see the CRaSH documentation for details). By default Spring Boot will search for commands in the following locations: * `+classpath*:/commands/**+` * `+classpath*:/crash/commands/**+` TIP: You can change the search path by settings a `shell.command-path-patterns` property. Here is a simple '`hello`' command that could be loaded from `src/main/resources/commands/hello.groovy` [source,groovy,indent=0] ---- package commands import org.crsh.cli.Command import org.crsh.cli.Usage import org.crsh.command.InvocationContext class hello { @Usage(""Say Hello"") @Command def main(InvocationContext context) { return ""Hello"" } } ---- Spring Boot adds some additional attributes to `InvocationContext` that you can access from your command: [cols=""2,3""] |=== | Attribute Name | Description |`spring.boot.version` |The version of Spring Boot |`spring.version` |The version of the core Spring Framework |`spring.beanfactory` |Access to the Spring `BeanFactory` |`spring.environment` |Access to the Spring `Environment` |=== [[production-ready-remote-shell-plugins]] ==== Remote shell plugins In addition to new commands, it is also possible to extend other CRaSH shell features. All Spring Beans that extend `org.crsh.plugin.CRaSHPlugin` will be automatically registered with the shell. For more information please refer to the http://www.crashub.org/[CRaSH reference documentation]. [[production-ready-metrics]] == Metrics Spring Boot Actuator includes a metrics service with '`gauge`' and '`counter`' support. A '`gauge`' records a single value; and a '`counter`' records a delta (an increment or decrement). Spring Boot Actuator also provides a {sc-spring-boot-actuator}/endpoint/PublicMetrics.{sc-ext}[`PublicMetrics`] interface that you can implement to expose metrics that you cannot record via one of those two mechanisms. Look at {sc-spring-boot-actuator}/endpoint/SystemPublicMetrics.{sc-ext}[`SystemPublicMetrics`] for an example. Metrics for all HTTP requests are automatically recorded, so if you hit the `metrics` endpoint you should see a response similar to this: [source,json,indent=0] ---- { ""counter.status.200.root"": 20, ""counter.status.200.metrics"": 3, ""counter.status.200.star-star"": 5, ""counter.status.401.root"": 4, ""gauge.response.star-star"": 6, ""gauge.response.root"": 2, ""gauge.response.metrics"": 3, ""classes"": 5808, ""classes.loaded"": 5808, ""classes.unloaded"": 0, ""heap"": 3728384, ""heap.committed"": 986624, ""heap.init"": 262144, ""heap.used"": 52765, ""mem"": 986624, ""mem.free"": 933858, ""processors"": 8, ""threads"": 15, ""threads.daemon"": 11, ""threads.peak"": 15, ""uptime"": 494836, ""instance.uptime"": 489782, ""datasource.primary.active"": 5, ""datasource.primary.usage"": 0.25 } ---- Here we can see basic `memory`, `heap`, `class loading`, `processor` and `thread pool` information along with some HTTP metrics. In this instance the `root` ('`/`') and `/metrics` URLs have returned `HTTP 200` responses `20` and `3` times respectively. It also appears that the `root` URL returned `HTTP 401` (unauthorized) `4` times. The double asterisks (`star-star`) comes from a request matched by Spring MVC as `+/**+` (normally a static resource). The `gauge` shows the last response time for a request. So the last request to `root` took `2ms` to respond and the last to `/metrics` took `3ms`. NOTE: In this example we are actually accessing the endpoint over HTTP using the `/metrics` URL, this explains why `metrics` appears in the response. [[production-ready-system-metrics]] === System metrics The following system metrics are exposed by Spring Boot: * The total system memory in KB (`mem`) * The amount of free memory in KB (`mem.free`) * The number of processors (`processors`) * The system uptime in milliseconds (`uptime`) * The application context uptime in milliseconds (`instance.uptime`) * The average system load (`systemload.average`) * Heap information in KB (`heap`, `heap.committed`, `heap.init`, `heap.used`) * Thread information (`threads`, `thread.peak`, `thread.daemon`) * Class load information (`classes`, `classes.loaded`, `classes.unloaded`) * Garbage collection information (`gc.xxx.count`, `gc.xxx.time`) [[production-ready-datasource-metrics]] === DataSource metrics The following metrics are exposed for each supported `DataSource` defined in your application: * The number of active connections (`datasource.xxx.active`) * The current usage of the connection pool (`datasource.xxx.usage`). All data source metrics share the `datasource.` prefix. The prefix is further qualified for each data source: * If the data source is the primary data source (that is either the only available data source or the one flagged `@Primary` amongst the existing ones), the prefix is `datasource.primary`. * If the data source bean name ends with `DataSource`, the prefix is the name of the bean without `DataSource` (i.e. `datasource.batch` for `batchDataSource`). * In all other cases, the name of the bean is used. It is possible to override part or all of those defaults by registering a bean with a customized version of `DataSourcePublicMetrics`. By default, Spring Boot provides metadata for all supported data sources; you can add additional `DataSourcePoolMetadataProvider` beans if your favorite data source isn't supported out of the box. See `DataSourcePoolMetadataProvidersConfiguration` for examples. [[production-ready-datasource-cache]] === Cache metrics The following metrics are exposed for each supported cache defined in your application: * The current size of the cache (`cache.xxx.size`) * Hit ratio (`cache.xxx.hit.ratio`) * Miss ratio (`cache.xxx.miss.ratio`) NOTE: Cache providers do not expose the hit/miss ratio in a consistent way. While some expose an **aggregated** value (i.e. the hit ratio since the last time the stats were cleared), others expose a **temporal** value (i.e. the hit ratio of the last second). Check your caching provider documentation for more details. If two different cache managers happen to define the same cache, the name of the cache is prefixed by the name of the `CacheManager` bean. It is possible to override part or all of those defaults by registering a bean with a customized version of `CachePublicMetrics`. By default, Spring Boot provides cache statistics for EhCache, Hazelcast, Infinispan, JCache and Guava. You can add additional `CacheStatisticsProvider` beans if your favorite caching library isn't supported out of the box. See `CacheStatisticsAutoConfiguration` for examples. [[production-ready-session-metrics]] === Tomcat session metrics If you are using Tomcat as your embedded servlet container, session metrics will automatically be exposed. The `httpsessions.active` and `httpsessions.max` keys provide the number of active and maximum sessions. [[production-ready-recording-metrics]] === Recording your own metrics To record your own metrics inject a {sc-spring-boot-actuator}/metrics/CounterService.{sc-ext}[`CounterService`] and/or {sc-spring-boot-actuator}/metrics/GaugeService.{sc-ext}[`GaugeService`] into your bean. The `CounterService` exposes `increment`, `decrement` and `reset` methods; the `GaugeService` provides a `submit` method. Here is a simple example that counts the number of times that a method is invoked: [source,java,indent=0] ---- import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.metrics.CounterService; import org.springframework.stereotype.Service; @Service public class MyService { private final CounterService counterService; @Autowired public MyService(CounterService counterService) { this.counterService = counterService; } public void exampleMethod() { this.counterService.increment(""services.system.myservice.invoked""); } } ---- TIP: You can use any string as a metric name but you should follow guidelines of your chosen store/graphing technology. Some good guidelines for Graphite are available on http://matt.aimonetti.net/posts/2013/06/26/practical-guide-to-graphite-monitoring/[Matt Aimonetti's Blog]. [[production-ready-public-metrics]] === Adding your own public metrics To add additional metrics that are computed every time the metrics endpoint is invoked, simply register additional `PublicMetrics` implementation bean(s). By default, all such beans are gathered by the endpoint. You can easily change that by defining your own `MetricsEndpoint`. [[production-ready-metric-repositories]] === Special features with Java 8 The default implementation of `GaugeService` and `CounterService` provided by Spring Boot depends on the version of Java that you are using. With Java 8 (or better) the implementation switches to a high-performance version optimized for fast writes, backed by atomic in-memory buffers, rather than by the immutable but relatively expensive `Metric` type (counters are approximately 5 times faster and gauges approximately twice as fast as the repository-based implementations). The Dropwizard metrics services (see below) are also very efficient even for Java 7 (they have backports of some of the Java 8 concurrency libraries), but they do not record timestamps for metric values. If performance of metric gathering is a concern then it is always advisable to use one of the high-performance options, and also to only read metrics infrequently, so that the writes are buffered locally and only read when needed. NOTE: The old `MetricRepository` and its `InMemoryMetricRepository` implementation are not used by default if you are on Java 8 or if you are using Dropwizard metrics. [[production-ready-metric-writers]] === Metric writers, exporters and aggregation Spring Boot provides a couple of implementations of a marker interface called `Exporter` which can be used to copy metric readings from the in-memory buffers to a place where they can be analyzed and displayed. Indeed, if you provide a `@Bean` that implements the `MetricWriter` interface (or `GaugeWriter` for simple use cases) and mark it `@ExportMetricWriter`, then it will automatically be hooked up to an `Exporter` and fed metric updates every 5 seconds (configured via `spring.metrics.export.delay-millis`). In addition, any `MetricReader` that you define and mark as `@ExportMetricReader` will have its values exported by the default exporter. The default exporter is a `MetricCopyExporter` which tries to optimize itself by not copying values that haven't changed since it was last called (the optimization can be switched off using a flag `spring.metrics.export.send-latest`). Note also that the Dropwizard `MetricRegistry` has no support for timestamps, so the optimization is not available if you are using Dropwizard metrics (all metrics will be copied on every tick). The default values for the export trigger (`delay-millis`, `includes`, `excludes` and `send-latest`) can be set as `spring.metrics.export.\\*`. Individual values for specific `MetricWriters` can be set as `spring.metrics.export.triggers..*` where `` is a bean name (or pattern for matching bean names). WARNING: The automatic export of metrics is disabled if you switch off the default `MetricRepository` (e.g. by using Dropwizard metrics). You can get back the same functionality be declaring a bean of your own of type `MetricReader` and declaring it to be `@ExportMetricReader`. [[production-ready-metric-writers-export-to-redis]] ==== Example: Export to Redis If you provide a `@Bean` of type `RedisMetricRepository` and mark it `@ExportMetricWriter` the metrics are exported to a Redis cache for aggregation. The `RedisMetricRepository` has two important parameters to configure it for this purpose: `prefix` and `key` (passed into its constructor). It is best to use a prefix that is unique to the application instance (e.g. using a random value and maybe the logical name of the application to make it possible to correlate with other instances of the same application). The ""`key`"" is used to keep a global index of all metric names, so it should be unique ""`globally`"", whatever that means for your system (e.g. two instances of the same system could share a Redis cache if they have distinct keys). Example: [source,java,indent=0] ---- @Bean @ExportMetricWriter MetricWriter metricWriter(MetricExportProperties export) { return new RedisMetricRepository(connectionFactory, export.getRedis().getPrefix(), export.getRedis().getKey()); } ---- .application.properties [source,properties] ---- spring.metrics.export.redis.prefix: metrics.mysystem.${spring.application.name:application}.${random.value:0000} spring.metrics.export.redis.key: keys.metrics.mysystem ---- The prefix is constructed with the application name and id at the end, so it can easily be used to identify a group of processes with the same logical name later. NOTE: It's important to set both the `key` and the `prefix`. The key is used for all repository operations, and can be shared by multiple repositories. If multiple repositories share a key (like in the case where you need to aggregate across them), then you normally have a read-only ""`master`"" repository that has a short, but identifiable, prefix (like ""`metrics.mysystem`""), and many write-only repositories with prefixes that start with the master prefix (like `metrics.mysystem.*` in the example above). It is efficient to read all the keys from a ""`master`"" repository like that, but inefficient to read a subset with a longer prefix (e.g. using one of the writing repositories). TIP: The example above uses `MetricExportProperties` to inject and extract the key and prefix. This is provided to you as a convenience by Spring Boot, configured with sensible defaults. There is nothing to stop you using your own values as long as they follow the recommendations. [[production-ready-metric-writers-export-to-open-tsdb]] ==== Example: Export to Open TSDB If you provide a `@Bean` of type `OpenTsdbGaugeWriter` and mark it `@ExportMetricWriter` metrics are exported to http://opentsdb.net/[Open TSDB] for aggregation. The `OpenTsdbGaugeWriter` has a `url` property that you need to set to the Open TSDB ""`/put`"" endpoint, e.g. `http://localhost:4242/api/put`). It also has a `namingStrategy` that you can customize or configure to make the metrics match the data structure you need on the server. By default it just passes through the metric name as an Open TSDB metric name, and adds the tags ""`domain`"" (with value ""`org.springframework.metrics`"") and ""`process`"" (with the value equal to the object hash of the naming strategy). Thus, after running the application and generating some metrics you can inspect the metrics in the TSD UI (http://localhost:4242 by default). Example: [source,indent=0] ---- curl localhost:4242/api/query?start=1h-ago&m=max:counter.status.200.root [ { ""metric"": ""counter.status.200.root"", ""tags"": { ""domain"": ""org.springframework.metrics"", ""process"": ""b968a76"" }, ""aggregateTags"": [], ""dps"": { ""1430492872"": 2, ""1430492875"": 6 } } ] ---- [[production-ready-metric-writers-export-to-statsd]] ==== Example: Export to Statsd To export metrics to Statsd, make sure first that you have added `com.timgroup:java-statsd-client` as a dependency of your project (Spring Boot provides a dependency management for it). Then add a `spring.metrics.export.statsd.host` value to your `application.properties` file. Connections will be opened to port `8125` unless a `spring.metrics.export.statsd.port` override is provided. You can use `spring.metrics.export.statsd.prefix` if you want a custom prefix. Alternatively, you can provide a `@Bean` of type `StatsdMetricWriter` and mark it `@ExportMetricWriter`: [source,java,indent=0] ---- @Value(""${spring.application.name:application}.${random.value:0000}"") private String prefix = ""metrics""; @Bean @ExportMetricWriter MetricWriter metricWriter() { return new StatsdMetricWriter(prefix, ""localhost"", ""8125""); } ---- [[production-ready-metric-writers-export-to-jmx]] ==== Example: Export to JMX If you provide a `@Bean` of type `JmxMetricWriter` marked `@ExportMetricWriter` the metrics are exported as MBeans to the local server (the `MBeanExporter` is provided by Spring Boot JMX auto-configuration as long as it is switched on). Metrics can then be inspected, graphed, alerted etc. using any tool that understands JMX (e.g. JConsole or JVisualVM). Example: [source,java,indent=0] ---- @Bean @ExportMetricWriter MetricWriter metricWriter(MBeanExporter exporter) { return new JmxMetricWriter(exporter); } ---- Each metric is exported as an individual MBean. The format for the `ObjectNames` is given by an `ObjectNamingStrategy` which can be injected into the `JmxMetricWriter` (the default breaks up the metric name and tags the first two period-separated sections in a way that should make the metrics group nicely in JVisualVM or JConsole). [[production-ready-metric-aggregation]] === Aggregating metrics from multiple sources There is an `AggregateMetricReader` that you can use to consolidate metrics from different physical sources. Sources for the same logical metric just need to publish them with a period-separated prefix, and the reader will aggregate (by truncating the metric names, and dropping the prefix). Counters are summed and everything else (i.e. gauges) take their most recent value. This is very useful if multiple application instances are feeding to a central (e.g. Redis) repository and you want to display the results. Particularly recommended in conjunction with a `MetricReaderPublicMetrics` for hooking up to the results to the ""`/metrics`"" endpoint. Example: [source,java,indent=0] ---- @Autowired private MetricExportProperties export; @Bean public PublicMetrics metricsAggregate() { return new MetricReaderPublicMetrics(aggregatesMetricReader()); } private MetricReader globalMetricsForAggregation() { return new RedisMetricRepository(this.connectionFactory, this.export.getRedis().getAggregatePrefix(), this.export.getRedis().getKey()); } private MetricReader aggregatesMetricReader() { AggregateMetricReader repository = new AggregateMetricReader( globalMetricsForAggregation()); return repository; } ---- NOTE: The example above uses `MetricExportProperties` to inject and extract the key and prefix. This is provided to you as a convenience by Spring Boot, and the defaults will be sensible. They are set up in `MetricExportAutoConfiguration`. NOTE: The `MetricReaders` above are not `@Beans` and are not marked as `@ExportMetricReader` because they are just collecting and analyzing data from other repositories, and don't want to export their values. [[production-ready-dropwizard-metrics]] === Dropwizard Metrics A default `MetricRegistry` Spring bean will be created when you declare a dependency to the `io.dropwizard.metrics:metrics-core` library; you can also register you own `@Bean` instance if you need customizations. Users of the https://dropwizard.github.io/metrics/[Dropwizard '`Metrics`' library] will find that Spring Boot metrics are automatically published to `com.codahale.metrics.MetricRegistry`. Metrics from the `MetricRegistry` are also automatically exposed via the `/metrics` endpoint When Dropwizard metrics are in use, the default `CounterService` and `GaugeService` are replaced with a `DropwizardMetricServices`, which is a wrapper around the `MetricRegistry` (so you can `@Autowired` one of those services and use it as normal). You can also create ""`special`"" Dropwizard metrics by prefixing your metric names with the appropriate type (i.e. `+timer.*+`, `+histogram.*+` for gauges, and `+meter.*+` for counters). [[production-ready-metrics-message-channel-integration]] === Message channel integration If a `MessageChannel` bean called `metricsChannel` exists, then a `MetricWriter` will be created that writes metrics to that channel. The writer is automatically hooked up to an exporter (as for all writers), so all metric values will appear on the channel, and additional analysis or actions can be taken by subscribers (it's up to you to provide the channel and any subscribers you need). [[production-ready-auditing]] == Auditing Spring Boot Actuator has a flexible audit framework that will publish events once Spring Security is in play ('`authentication success`', '`failure`' and '`access denied`' exceptions by default). This can be very useful for reporting, and also to implement a lock-out policy based on authentication failures. You can also choose to use the audit services for your own business events. To do that you can either inject the existing `AuditEventRepository` into your own components and use that directly, or you can simply publish `AuditApplicationEvent` via the Spring `ApplicationEventPublisher` (using `ApplicationEventPublisherAware`). [[production-ready-tracing]] == Tracing Tracing is automatically enabled for all HTTP requests. You can view the `trace` endpoint and obtain basic information about the last few requests: [source,json,indent=0] ---- [{ ""timestamp"": 1394343677415, ""info"": { ""method"": ""GET"", ""path"": ""/trace"", ""headers"": { ""request"": { ""Accept"": ""text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"", ""Connection"": ""keep-alive"", ""Accept-Encoding"": ""gzip, deflate"", ""User-Agent"": ""Mozilla/5.0 Gecko/Firefox"", ""Accept-Language"": ""en-US,en;q=0.5"", ""Cookie"": ""_ga=GA1.1.827067509.1390890128; ..."" ""Authorization"": ""Basic ..."", ""Host"": ""localhost:8080"" }, ""response"": { ""Strict-Transport-Security"": ""max-age=31536000 ; includeSubDomains"", ""X-Application-Context"": ""application:8080"", ""Content-Type"": ""application/json;charset=UTF-8"", ""status"": ""200"" } } } },{ ""timestamp"": 1394343684465, ... }] ---- [[production-ready-custom-tracing]] === Custom tracing If you need to trace additional events you can inject a {sc-spring-boot-actuator}/trace/TraceRepository.{sc-ext}[`TraceRepository`] into your Spring beans. The `add` method accepts a single `Map` structure that will be converted to JSON and logged. By default an `InMemoryTraceRepository` will be used that stores the last 100 events. You can define your own instance of the `InMemoryTraceRepository` bean if you need to expand the capacity. You can also create your own alternative `TraceRepository` implementation if needed. [[production-ready-process-monitoring]] == Process monitoring In Spring Boot Actuator you can find a couple of classes to create files that are useful for process monitoring: * `ApplicationPidFileWriter` creates a file containing the application PID (by default in the application directory with the file name `application.pid`). * `EmbeddedServerPortFileWriter` creates a file (or files) containing the ports of the embedded server (by default in the application directory with the file name `application.port`). These writers are not activated by default, but you can enable them in one of the ways described below. [[production-ready-process-monitoring-configuration]] === Extend configuration In `META-INF/spring.factories` file you can activate the listener(s) that writes a PID file. Example: [indent=0] ---- org.springframework.context.ApplicationListener=\\ org.springframework.boot.actuate.system.ApplicationPidFileWriter, org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter ---- [[production-ready-process-monitoring-programmatically]] === Programmatically You can also activate a listener by invoking the `SpringApplication.addListeners(...)` method and passing the appropriate `Writer` object. This method also allows you to customize the file name and path via the `Writer` constructor. [[production-ready-whats-next]] == What to read next If you want to explore some of the concepts discussed in this chapter, you can take a look at the actuator {github-code}/spring-boot-samples[sample applications]. You also might want to read about graphing tools such as http://graphite.wikidot.com/[Graphite]. Otherwise, you can continue on, to read about <> or jump ahead for some in-depth information about Spring Boot's _<>_. ",12434,False,2193.0535467654404,median "--- title: Chapter 7. Multimedia part: Part II. Common Tasks prev: books/handbook/desktop next: books/handbook/kernelconfig description: FreeBSD supports a wide variety of sound cards, allowing users to enjoy high fidelity output from a FreeBSD system tags: [""multimedia"", ""sound card"", ""MP3"", ""MythTV"", ""scanner"", ""SANE""] showBookMenu: true weight: 10 path: ""/books/handbook/"" --- [[multimedia]] = Multimedia :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 7 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/multimedia/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[multimedia-synopsis]] == Synopsis FreeBSD supports a wide variety of sound cards, allowing users to enjoy high fidelity output from a FreeBSD system. This includes the ability to record and play back audio in the MPEG Audio Layer 3 (`MP3`), Waveform Audio File (`WAV`), Ogg Vorbis, and other formats. The FreeBSD Ports Collection contains many applications for editing recorded audio, adding sound effects, and controlling attached MIDI devices. FreeBSD also supports the playback of video files and ``DVD``s. The FreeBSD Ports Collection contains applications to encode, convert, and playback various video media. This chapter describes how to configure sound cards, video playback, TV tuner cards, and scanners on FreeBSD. It also describes some of the applications which are available for using these devices. After reading this chapter, you will know how to: * Configure a sound card on FreeBSD. * Troubleshoot the sound setup. * Playback and encode MP3s and other audio. * Prepare a FreeBSD system for video playback. * Play ``DVD``s, [.filename]#.mpg#, and [.filename]#.avi# files. * Rip `CD` and `DVD` content into files. * Configure a TV card. * Install and setup MythTV on FreeBSD * Configure an image scanner. * Configure a Bluetooth headset. Before reading this chapter, you should: * Know how to install applications as described in crossref:ports[ports,Installing Applications: Packages and Ports]. [[sound-setup]] == Setting Up the Sound Card Before beginning the configuration, determine the model of the sound card and the chip it uses. FreeBSD supports a wide variety of sound cards. Check the supported audio devices list of the link:{u-rel120-hardware}[Hardware Notes] to see if the card is supported and which FreeBSD driver it uses. In order to use the sound device, its device driver must be loaded. The easiest way is to load a kernel module for the sound card with man:kldload[8]. This example loads the driver for a built-in audio chipset based on the Intel specification: [source,shell] .... # kldload snd_hda .... To automate the loading of this driver at boot time, add the driver to [.filename]#/boot/loader.conf#. The line for this driver is: [.programlisting] .... snd_hda_load=""YES"" .... Other available sound modules are listed in [.filename]#/boot/defaults/loader.conf#. When unsure which driver to use, load the [.filename]#snd_driver# module: [source,shell] .... # kldload snd_driver .... This is a metadriver which loads all of the most common sound drivers and can be used to speed up the search for the correct driver. It is also possible to load all sound drivers by adding the metadriver to [.filename]#/boot/loader.conf#. To determine which driver was selected for the sound card after loading the [.filename]#snd_driver# metadriver, type `cat /dev/sndstat`. === Configuring a Custom Kernel with Sound Support This section is for users who prefer to statically compile in support for the sound card in a custom kernel. For more information about recompiling a kernel, refer to crossref:kernelconfig[kernelconfig,Configuring the FreeBSD Kernel]. When using a custom kernel to provide sound support, make sure that the audio framework driver exists in the custom kernel configuration file: [.programlisting] .... device sound .... Next, add support for the sound card. To continue the example of the built-in audio chipset based on the Intel specification from the previous section, use the following line in the custom kernel configuration file: [.programlisting] .... device snd_hda .... Be sure to read the manual page of the driver for the device name to use for the driver. Non-PnP ISA sound cards may require the IRQ and I/O port settings of the card to be added to [.filename]#/boot/device.hints#. During the boot process, man:loader[8] reads this file and passes the settings to the kernel. For example, an old Creative SoundBlaster(R) 16 ISA non-PnP card will use the man:snd_sbc[4] driver in conjunction with `snd_sb16`. For this card, the following lines must be added to the kernel configuration file: [.programlisting] .... device snd_sbc device snd_sb16 .... If the card uses the `0x220` I/O port and IRQ `5`, these lines must also be added to [.filename]#/boot/device.hints#: [.programlisting] .... hint.sbc.0.at=""isa"" hint.sbc.0.port=""0x220"" hint.sbc.0.irq=""5"" hint.sbc.0.drq=""1"" hint.sbc.0.flags=""0x15"" .... The syntax used in [.filename]#/boot/device.hints# is described in man:sound[4] and the manual page for the driver of the sound card. The settings shown above are the defaults. In some cases, the IRQ or other settings may need to be changed to match the card. Refer to man:snd_sbc[4] for more information about this card. [[sound-testing]] === Testing Sound After loading the required module or rebooting into the custom kernel, the sound card should be detected. To confirm, run `dmesg | grep pcm`. This example is from a system with a built-in Conexant CX20590 chipset: [source,shell] .... pcm0: at nid 5 on hdaa0 pcm1: at nid 6 on hdaa0 pcm2: at nid 31,25 and 35,27 on hdaa1 .... The status of the sound card may also be checked using this command: [source,shell] .... # cat /dev/sndstat FreeBSD Audio Driver (newpcm: 64bit 2009061500/amd64) Installed devices: pcm0: (play) pcm1: (play) pcm2: (play/rec) default .... The output will vary depending upon the sound card. If no [.filename]#pcm# devices are listed, double-check that the correct device driver was loaded or compiled into the kernel. The next section lists some common problems and their solutions. If all goes well, the sound card should now work in FreeBSD. If the `CD` or `DVD` drive is properly connected to the sound card, one can insert an audio `CD` in the drive and play it with man:cdcontrol[1]: [source,shell] .... % cdcontrol -f /dev/acd0 play 1 .... [WARNING] ==== Audio ``CD``s have specialized encodings which means that they should not be mounted using man:mount[8]. ==== Various applications, such as package:audio/workman[], provide a friendlier interface. The package:audio/mpg123[] port can be installed to listen to MP3 audio files. Another quick way to test the card is to send data to [.filename]#/dev/dsp#: [source,shell] .... % cat filename > /dev/dsp .... where [.filename]#filename# can be any type of file. This command should produce some noise, confirming that the sound card is working. [NOTE] ==== The [.filename]#/dev/dsp*# device nodes will be created automatically as needed. When not in use, they do not exist and will not appear in the output of man:ls[1]. ==== [[bluetooth-headset]] === Setting up Bluetooth Sound Devices Connecting to a Bluetooth device is out of scope for this chapter. Refer to crossref:advanced-networking[network-bluetooth,“Bluetooth”] for more information. To get Bluetooth sound sink working with FreeBSD's sound system, users have to install package:audio/virtual_oss[] first: [source,shell] .... # pkg install virtual_oss .... package:audio/virtual_oss[] requires `cuse` to be loaded into the kernel: [source,shell] .... # kldload cuse .... To load `cuse` during system startup, run this command: [source,shell] .... # echo 'cuse_load=yes' >> /boot/loader.conf .... To use headphones as a sound sink with package:audio/virtual_oss[], users need to create a virtual device after connecting to a Bluetooth audio device: [source,shell] .... # virtual_oss -C 2 -c 2 -r 48000 -b 16 -s 768 -R /dev/null -P /dev/bluetooth/headphones -d dsp .... [NOTE] ==== _headphones_ in this example is a hostname from [.filename]#/etc/bluetooth/hosts#. `BT_ADDR` could be used instead. ==== Refer to man:virtual_oss[8] for more information. [[troubleshooting]] === Troubleshooting Sound <> lists some common error messages and their solutions: [[multimedia-sound-common-error-messages]] .Common Error Messages [cols=""1,1"", frame=""none"", options=""header""] |=== | Error | Solution |`sb_dspwr(XX) timed out` | The I/O port is not set correctly. |`bad irq XX` | The IRQ is set incorrectly. Make sure that the set IRQ and the sound IRQ are the same. |`xxx: gus pcm not attached, out of memory` | There is not enough available memory to use the device. |`xxx: can't open /dev/dsp!` | Type `fstat \\| grep` dsp to check if another application is holding the device open. Noteworthy troublemakers are esound and KDE's sound support. |=== Modern graphics cards often come with their own sound driver for use with `HDMI`. This sound device is sometimes enumerated before the sound card meaning that the sound card will not be used as the default playback device. To check if this is the case, run dmesg and look for `pcm`. The output looks something like this: [.programlisting] .... ... hdac0: HDA Driver Revision: 20100226_0142 hdac1: HDA Driver Revision: 20100226_0142 hdac0: HDA Codec #0: NVidia (Unknown) hdac0: HDA Codec #1: NVidia (Unknown) hdac0: HDA Codec #2: NVidia (Unknown) hdac0: HDA Codec #3: NVidia (Unknown) pcm0: at cad 0 nid 1 on hdac0 pcm1: at cad 1 nid 1 on hdac0 pcm2: at cad 2 nid 1 on hdac0 pcm3: at cad 3 nid 1 on hdac0 hdac1: HDA Codec #2: Realtek ALC889 pcm4: at cad 2 nid 1 on hdac1 pcm5: at cad 2 nid 1 on hdac1 pcm6: at cad 2 nid 1 on hdac1 pcm7: at cad 2 nid 1 on hdac1 ... .... In this example, the graphics card (`NVidia`) has been enumerated before the sound card (`Realtek ALC889`). To use the sound card as the default playback device, change `hw.snd.default_unit` to the unit that should be used for playback: [source,shell] .... # sysctl hw.snd.default_unit=n .... where `n` is the number of the sound device to use. In this example, it should be `4`. Make this change permanent by adding the following line to [.filename]#/etc/sysctl.conf#: [.programlisting] .... hw.snd.default_unit=4 .... Programs using package:audio/pulseaudio[] might need to restart the package:audio/pulseaudio[] daemon for the changes in `hw.snd.default_unit` to take effect. Alternatively, package:audio/pulseaudio[] settings can be changed on the fly. man:pacmd[1] opens a command line connection to the package:audio/pulseaudio[] daemon: [source,shell] .... # pacmd Welcome to PulseAudio 14.2! Use ""help"" for usage information. >>> .... The following command changes the default sink to card number 4 as in the previous example: [.programlisting] .... set-default-sink 4 .... [WARNING] ==== Do not use the `exit` command to exit the command line interface. That will kill the package:audio/pulseaudio[] daemon. Use kbd:[Ctrl+D] instead. ==== [[sound-multiple-sources]] === Utilizing Multiple Sound Sources It is often desirable to have multiple sources of sound that are able to play simultaneously. FreeBSD uses ""Virtual Sound Channels"" to multiplex the sound card's playback by mixing sound in the kernel. Three man:sysctl[8] knobs are available for configuring virtual channels: [source,shell] .... # sysctl dev.pcm.0.play.vchans=4 # sysctl dev.pcm.0.rec.vchans=4 # sysctl hw.snd.maxautovchans=4 .... This example allocates four virtual channels, which is a practical number for everyday use. Both `dev.pcm.0.play.vchans=4` and `dev.pcm.0.rec.vchans=4` are configurable after a device has been attached and represent the number of virtual channels [.filename]#pcm0# has for playback and recording. Since the [.filename]#pcm# module can be loaded independently of the hardware drivers, `hw.snd.maxautovchans` indicates how many virtual channels will be given to an audio device when it is attached. Refer to man:pcm[4] for more information. [NOTE] ==== The number of virtual channels for a device cannot be changed while it is in use. First, close any programs using the device, such as music players or sound daemons. ==== The correct [.filename]#pcm# device will automatically be allocated transparently to a program that requests [.filename]#/dev/dsp0#. === Setting Default Values for Mixer Channels The default values for the different mixer channels are hardcoded in the source code of the man:pcm[4] driver. While sound card mixer levels can be changed using man:mixer[8] or third-party applications and daemons, this is not a permanent solution. To instead set default mixer values at the driver level, define the appropriate values in [.filename]#/boot/device.hints#, as seen in this example: [.programlisting] .... hint.pcm.0.vol=""50"" .... This will set the volume channel to a default value of `50` when the man:pcm[4] module is loaded. [[sound-mp3]] == MP3 Audio This section describes some `MP3` players available for FreeBSD, how to rip audio `CD` tracks, and how to encode and decode ``MP3``s. [[mp3-players]] === MP3 Players A popular graphical `MP3` player is Audacious. It supports Winamp skins and additional plugins. The interface is intuitive, with a playlist, graphic equalizer, and more. Those familiar with Winamp will find Audacious simple to use. On FreeBSD, Audacious can be installed from the package:multimedia/audacious[] port or package. Audacious is a descendant of XMMS. The package:audio/mpg123[] package or port provides an alternative, command-line `MP3` player. Once installed, specify the `MP3` file to play on the command line. If the system has multiple audio devices, the sound device can also be specified: [source,shell] .... # mpg123 -a /dev/dsp1.0 Foobar-GreatestHits.mp3 High Performance MPEG 1.0/2.0/2.5 Audio Player for Layers 1, 2 and 3 version 1.18.1; written and copyright by Michael Hipp and others free software (LGPL) without any warranty but with best wishes Playing MPEG stream from Foobar-GreatestHits.mp3 ... MPEG 1.0 layer III, 128 kbit/s, 44100 Hz joint-stereo .... Additional `MP3` players are available in the FreeBSD Ports Collection. [[rip-cd]] === Ripping `CD` Audio Tracks Before encoding a `CD` or `CD` track to `MP3`, the audio data on the `CD` must be ripped to the hard drive. This is done by copying the raw `CD` Digital Audio (`CDDA`) data to `WAV` files. The `cdda2wav` tool, which is installed with the package:sysutils/cdrtools[] suite, can be used to rip audio information from ``CD``s. With the audio `CD` in the drive, the following command can be issued as `root` to rip an entire `CD` into individual, per track, `WAV` files: [source,shell] .... # cdda2wav -D 0,1,0 -B .... In this example, the `-D _0,1,0_` indicates the `SCSI` device [.filename]#0,1,0# containing the `CD` to rip. Use `cdrecord -scanbus` to determine the correct device parameters for the system. To rip individual tracks, use `-t` to specify the track: [source,shell] .... # cdda2wav -D 0,1,0 -t 7 .... To rip a range of tracks, such as track one to seven, specify a range: [source,shell] .... # cdda2wav -D 0,1,0 -t 1+7 .... To rip from an `ATAPI` (`IDE`) `CDROM` drive, specify the device name in place of the `SCSI` unit numbers. For example, to rip track 7 from an IDE drive: [source,shell] .... # cdda2wav -D /dev/acd0 -t 7 .... Alternately, `dd` can be used to extract audio tracks on `ATAPI` drives, as described in crossref:disks[duplicating-audiocds,“Duplicating Audio CDs”]. [[mp3-encoding]] === Encoding and Decoding MP3s Lame is a popular `MP3` encoder which can be installed from the package:audio/lame[] port. Due to patent issues, a package is not available. The following command will convert the ripped `WAV` file [.filename]#audio01.wav# to [.filename]#audio01.mp3#: [source,shell] .... # lame -h -b 128 --tt ""Foo Song Title"" --ta ""FooBar Artist"" --tl ""FooBar Album"" \\ --ty ""2014"" --tc ""Ripped and encoded by Foo"" --tg ""Genre"" audio01.wav audio01.mp3 .... The specified 128 kbits is a standard `MP3` bitrate while the 160 and 192 bitrates provide higher quality. The higher the bitrate, the larger the size of the resulting `MP3`. The `-h` turns on the ""higher quality but a little slower"" mode. The options beginning with `--t` indicate `ID3` tags, which usually contain song information, to be embedded within the `MP3` file. Additional encoding options can be found in the lame manual page. In order to burn an audio `CD` from ``MP3``s, they must first be converted to a non-compressed file format. XMMS can be used to convert to the `WAV` format, while mpg123 can be used to convert to the raw Pulse-Code Modulation (`PCM`) audio data format. To convert [.filename]#audio01.mp3# using mpg123, specify the name of the `PCM` file: [source,shell] .... # mpg123 -s audio01.mp3 > audio01.pcm .... To use XMMS to convert a `MP3` to `WAV` format, use these steps: [.procedure] .Procedure: Converting to `WAV` Format in XMMS . Launch XMMS. . Right-click the window to bring up the XMMS menu. . Select `Preferences` under `Options`. . Change the Output Plugin to ""Disk Writer Plugin"". . Press `Configure`. . Enter or browse to a directory to write the uncompressed files to. . Load the `MP3` file into XMMS as usual, with volume at 100% and EQ settings turned off. . Press `Play`. The XMMS will appear as if it is playing the `MP3`, but no music will be heard. It is actually playing the `MP3` to a file. . When finished, be sure to set the default Output Plugin back to what it was before in order to listen to ``MP3``s again. Both the `WAV` and `PCM` formats can be used with cdrecord. When using `WAV` files, there will be a small tick sound at the beginning of each track. This sound is the header of the `WAV` file. The package:audio/sox[] port or package can be used to remove the header: [source,shell] .... % sox -t wav -r 44100 -s -w -c 2 track.wav track.raw .... Refer to crossref:disks[creating-cds,“Creating and Using CD Media”] for more information on using a `CD` burner in FreeBSD. [[video-playback]] == Video Playback Before configuring video playback, determine the model and chipset of the video card. While Xorg supports a wide variety of video cards, not all provide good playback performance. To obtain a list of extensions supported by the Xorg server using the card, run `xdpyinfo` while Xorg is running. It is a good idea to have a short MPEG test file for evaluating various players and options. Since some `DVD` applications look for `DVD` media in [.filename]#/dev/dvd# by default, or have this device name hardcoded in them, it might be useful to make a symbolic link to the proper device: [source,shell] .... # ln -sf /dev/cd0 /dev/dvd .... Due to the nature of man:devfs[5], manually created links will not persist after a system reboot. In order to recreate the symbolic link automatically when the system boots, add the following line to [.filename]#/etc/devfs.conf#: [.programlisting] .... link cd0 dvd .... `DVD` decryption invokes certain functions that require write permission to the `DVD` device. To enhance the shared memory Xorg interface, it is recommended to increase the values of these man:sysctl[8] variables: [.programlisting] .... kern.ipc.shmmax=67108864 kern.ipc.shmall=32768 .... [[video-interface]] === Determining Video Capabilities There are several possible ways to display video under Xorg and what works is largely hardware dependent. Each method described below will have varying quality across different hardware. Common video interfaces include: . Xorg: normal output using shared memory. . XVideo: an extension to the Xorg interface which allows video to be directly displayed in drawable objects through a special acceleration. This extension provides good quality playback even on low-end machines. The next section describes how to determine if this extension is running. . `SDL`: the Simple Directmedia Layer is a porting layer for many operating systems, allowing cross-platform applications to be developed which make efficient use of sound and graphics. `SDL` provides a low-level abstraction to the hardware which can sometimes be more efficient than the Xorg interface. On FreeBSD, `SDL` can be installed using the package:devel/sdl20[] package or port. . `DGA`: the Direct Graphics Access is an Xorg extension which allows a program to bypass the Xorg server and directly alter the framebuffer. As it relies on a low-level memory mapping, programs using it must be run as `root`. The `DGA` extension can be tested and benchmarked using man:dga[1]. When `dga` is running, it changes the colors of the display whenever a key is pressed. To quit, press kbd:[q]. . SVGAlib: a low level console graphics layer. [[video-interface-xvideo]] ==== XVideo To check whether this extension is running, use `xvinfo`: [source,shell] .... % xvinfo .... XVideo is supported for the card if the result is similar to: [source,shell] .... X-Video Extension version 2.2 screen #0 Adaptor #0: ""Savage Streams Engine"" number of ports: 1 port base: 43 operations supported: PutImage supported visuals: depth 16, visualID 0x22 depth 16, visualID 0x23 number of attributes: 5 ""XV_COLORKEY"" (range 0 to 16777215) client settable attribute client gettable attribute (current value is 2110) ""XV_BRIGHTNESS"" (range -128 to 127) client settable attribute client gettable attribute (current value is 0) ""XV_CONTRAST"" (range 0 to 255) client settable attribute client gettable attribute (current value is 128) ""XV_SATURATION"" (range 0 to 255) client settable attribute client gettable attribute (current value is 128) ""XV_HUE"" (range -180 to 180) client settable attribute client gettable attribute (current value is 0) maximum XvImage size: 1024 x 1024 Number of image formats: 7 id: 0x32595559 (YUY2) guid: 59555932-0000-0010-8000-00aa00389b71 bits per pixel: 16 number of planes: 1 type: YUV (packed) id: 0x32315659 (YV12) guid: 59563132-0000-0010-8000-00aa00389b71 bits per pixel: 12 number of planes: 3 type: YUV (planar) id: 0x30323449 (I420) guid: 49343230-0000-0010-8000-00aa00389b71 bits per pixel: 12 number of planes: 3 type: YUV (planar) id: 0x36315652 (RV16) guid: 52563135-0000-0000-0000-000000000000 bits per pixel: 16 number of planes: 1 type: RGB (packed) depth: 0 red, green, blue masks: 0x1f, 0x3e0, 0x7c00 id: 0x35315652 (RV15) guid: 52563136-0000-0000-0000-000000000000 bits per pixel: 16 number of planes: 1 type: RGB (packed) depth: 0 red, green, blue masks: 0x1f, 0x7e0, 0xf800 id: 0x31313259 (Y211) guid: 59323131-0000-0010-8000-00aa00389b71 bits per pixel: 6 number of planes: 3 type: YUV (packed) id: 0x0 guid: 00000000-0000-0000-0000-000000000000 bits per pixel: 0 number of planes: 0 type: RGB (packed) depth: 1 red, green, blue masks: 0x0, 0x0, 0x0 .... The formats listed, such as YUV2 and YUV12, are not present with every implementation of XVideo and their absence may hinder some players. If the result instead looks like: [source,shell] .... X-Video Extension version 2.2 screen #0 no adaptors present .... XVideo is probably not supported for the card. This means that it will be more difficult for the display to meet the computational demands of rendering video, depending on the video card and processor. [[video-ports]] === Ports and Packages Dealing with Video This section introduces some of the software available from the FreeBSD Ports Collection which can be used for video playback. [[video-mplayer]] ==== MPlayer and MEncoder MPlayer is a command-line video player with an optional graphical interface which aims to provide speed and flexibility. Other graphical front-ends to MPlayer are available from the FreeBSD Ports Collection. MPlayer can be installed using the package:multimedia/mplayer[] package or port. Several compile options are available and a variety of hardware checks occur during the build process. For these reasons, some users prefer to build the port rather than install the package. When compiling the port, the menu options should be reviewed to determine the type of support to compile into the port. If an option is not selected, MPlayer will not be able to display that type of video format. Use the arrow keys and spacebar to select the required formats. When finished, press kbd:[Enter] to continue the port compile and installation. By default, the package or port will build the `mplayer` command line utility and the `gmplayer` graphical utility. To encode videos, compile the package:multimedia/mencoder[] port. Due to licensing restrictions, a package is not available for MEncoder. The first time MPlayer is run, it will create [.filename]#~/.mplayer# in the user's home directory. This subdirectory contains default versions of the user-specific configuration files. This section describes only a few common uses. Refer to mplayer(1) for a complete description of its numerous options. To play the file [.filename]#testfile.avi#, specify the video interfaces with `-vo`, as seen in the following examples: [source,shell] .... % mplayer -vo xv testfile.avi .... [source,shell] .... % mplayer -vo sdl testfile.avi .... [source,shell] .... % mplayer -vo x11 testfile.avi .... [source,shell] .... # mplayer -vo dga testfile.avi .... [source,shell] .... # mplayer -vo 'sdl:dga' testfile.avi .... It is worth trying all of these options, as their relative performance depends on many factors and will vary significantly with hardware. To play a `DVD`, replace [.filename]#testfile.avi# with `dvd://_N_ -dvd-device _DEVICE_`, where _N_ is the title number to play and _DEVICE_ is the device node for the `DVD`. For example, to play title 3 from [.filename]#/dev/dvd#: [source,shell] .... # mplayer -vo xv dvd://3 -dvd-device /dev/dvd .... [NOTE] ==== The default `DVD` device can be defined during the build of the MPlayer port by including the `WITH_DVD_DEVICE=/path/to/desired/device` option. By default, the device is [.filename]#/dev/cd0#. More details can be found in the port's [.filename]#Makefile.options#. ==== To stop, pause, advance, and so on, use a keybinding. To see the list of keybindings, run `mplayer -h` or read mplayer(1). Additional playback options include `-fs -zoom`, which engages fullscreen mode, and `-framedrop`, which helps performance. Each user can add commonly used options to their [.filename]#~/.mplayer/config# like so: [.programlisting] .... vo=xv fs=yes zoom=yes .... `mplayer` can be used to rip a `DVD` title to a [.filename]#.vob#. To dump the second title from a `DVD`: [source,shell] .... # mplayer -dumpstream -dumpfile out.vob dvd://2 -dvd-device /dev/dvd .... The output file, [.filename]#out.vob#, will be in `MPEG` format. Anyone wishing to obtain a high level of expertise with UNIX(R) video should consult http://www.mplayerhq.hu/DOCS/[mplayerhq.hu/DOCS] as it is technically informative. This documentation should be considered as required reading before submitting any bug reports. Before using `mencoder`, it is a good idea to become familiar with the options described at http://www.mplayerhq.hu/DOCS/HTML/en/mencoder.html[mplayerhq.hu/DOCS/HTML/en/mencoder.html]. There are innumerable ways to improve quality, lower bitrate, and change formats, and some of these options may make the difference between good or bad performance. Improper combinations of command line options can yield output files that are unplayable even by `mplayer`. Here is an example of a simple copy: [source,shell] .... % mencoder input.avi -oac copy -ovc copy -o output.avi .... To rip to a file, use `-dumpfile` with `mplayer`. To convert [.filename]#input.avi# to the MPEG4 codec with MPEG3 audio encoding, first install the package:audio/lame[] port. Due to licensing restrictions, a package is not available. Once installed, type: [source,shell] .... % mencoder input.avi -oac mp3lame -lameopts br=192 \\ -ovc lavc -lavcopts vcodec=mpeg4:vhq -o output.avi .... This will produce output playable by applications such as `mplayer` and `xine`. [.filename]#input.avi# can be replaced with `dvd://1 -dvd-device /dev/dvd` and run as `root` to re-encode a `DVD` title directly. Since it may take a few tries to get the desired result, it is recommended to instead dump the title to a file and to work on the file. [[video-xine]] ==== The xine Video Player xine is a video player with a reusable base library and a modular executable which can be extended with plugins. It can be installed using the package:multimedia/xine[] package or port. In practice, xine requires either a fast CPU with a fast video card, or support for the XVideo extension. The xine video player performs best on XVideo interfaces. By default, the xine player starts a graphical user interface. The menus can then be used to open a specific file. Alternatively, xine may be invoked from the command line by specifying the name of the file to play: [source,shell] .... % xine -g -p mymovie.avi .... Refer to http://www.xine-project.org/faq[xine-project.org/faq] for more information and troubleshooting tips. [[video-ports-transcode]] ==== The Transcode Utilities Transcode provides a suite of tools for re-encoding video and audio files. Transcode can be used to merge video files or repair broken files using command line tools with stdin/stdout stream interfaces. In FreeBSD, Transcode can be installed using the package:multimedia/transcode[] package or port. Many users prefer to compile the port as it provides a menu of compile options for specifying the support and codecs to compile in. If an option is not selected, Transcode will not be able to encode that format. Use the arrow keys and spacebar to select the required formats. When finished, press kbd:[Enter] to continue the port compile and installation. This example demonstrates how to convert a DivX file into a PAL MPEG-1 file (PAL VCD): [source,shell] .... % transcode -i input.avi -V --export_prof vcd-pal -o output_vcd % mplex -f 1 -o output_vcd.mpg output_vcd.m1v output_vcd.mpa .... The resulting `MPEG` file, [.filename]#output_vcd.mpg#, is ready to be played with MPlayer. The file can be burned on a `CD` media to create a video `CD` using a utility such as package:multimedia/vcdimager[] or package:sysutils/cdrdao[]. In addition to the manual page for `transcode`, refer to http://www.transcoding.org/cgi-bin/transcode[transcoding.org/cgi-bin/transcode] for further information and examples. [[tvcard]] == TV Cards TV cards can be used to watch broadcast or cable TV on a computer. Most cards accept composite video via an `RCA` or S-video input and some cards include a `FM` radio tuner. FreeBSD provides support for PCI-based TV cards using a Brooktree Bt848/849/878/879 video capture chip with the man:bktr[4] driver. This driver supports most Pinnacle PCTV video cards. Before purchasing a TV card, consult man:bktr[4] for a list of supported tuners. === Loading the Driver In order to use the card, the man:bktr[4] driver must be loaded. To automate this at boot time, add the following line to [.filename]#/boot/loader.conf#: [.programlisting] .... bktr_load=""YES"" .... Alternatively, one can statically compile support for the TV card into a custom kernel. In that case, add the following lines to the custom kernel configuration file: [.programlisting] .... device bktr device iicbus device iicbb device smbus .... These additional devices are necessary as the card components are interconnected via an I2C bus. Then, build and install a new kernel. To test that the tuner is correctly detected, reboot the system. The TV card should appear in the boot messages, as seen in this example: [.programlisting] .... bktr0: mem 0xd7000000-0xd7000fff irq 10 at device 10.0 on pci0 iicbb0: on bti2c0 iicbus0: on iicbb0 master-only iicbus1: on iicbb0 master-only smbus0: on bti2c0 bktr0: Pinnacle/Miro TV, Philips SECAM tuner. .... The messages will differ according to the hardware. If necessary, it is possible to override some of the detected parameters using man:sysctl[8] or custom kernel configuration options. For example, to force the tuner to a Philips SECAM tuner, add the following line to a custom kernel configuration file: [.programlisting] .... options OVERRIDE_TUNER=6 .... or, use man:sysctl[8]: [source,shell] .... # sysctl hw.bt848.tuner=6 .... Refer to man:bktr[4] for a description of the available man:sysctl[8] parameters and kernel options. === Useful Applications To use the TV card, install one of the following applications: * package:multimedia/fxtv[] provides TV-in-a-window and image/audio/video capture capabilities. * package:multimedia/xawtv[] is another TV application with similar features. * package:audio/xmradio[] provides an application for using the FM radio tuner of a TV card. More applications are available in the FreeBSD Ports Collection. === Troubleshooting If any problems are encountered with the TV card, check that the video capture chip and the tuner are supported by man:bktr[4] and that the right configuration options were used. For more support or to ask questions about supported TV cards, refer to the {freebsd-multimedia} mailing list. [[mythtv]] == MythTV MythTV is a popular, open source Personal Video Recorder (`PVR`) application. This section demonstrates how to install and setup MythTV on FreeBSD. Refer to http://www.mythtv.org/wiki/[mythtv.org/wiki] for more information on how to use MythTV. MythTV requires a frontend and a backend. These components can either be installed on the same system or on different machines. The frontend can be installed on FreeBSD using the package:multimedia/mythtv-frontend[] package or port. Xorg must also be installed and configured as described in crossref:x11[x11,The X Window System]. Ideally, this system has a video card that supports X-Video Motion Compensation (`XvMC`) and, optionally, a Linux Infrared Remote Control (`LIRC`)-compatible remote. To install both the backend and the frontend on FreeBSD, use the package:multimedia/mythtv[] package or port. A MySQL(TM) database server is also required and should automatically be installed as a dependency. Optionally, this system should have a tuner card and sufficient storage to hold recorded data. === Hardware MythTV uses Video for Linux (`V4L`) to access video input devices such as encoders and tuners. In FreeBSD, MythTV works best with `USB` DVB-S/C/T cards as they are well supported by the package:multimedia/webcamd[] package or port which provides a `V4L` userland application. Any Digital Video Broadcasting (`DVB`) card supported by webcamd should work with MythTV. A list of known working cards can be found at https://wiki.freebsd.org/WebcamCompat[wiki.freebsd.org/WebcamCompat]. Drivers are also available for Hauppauge cards in the package:multimedia/pvr250[] and package:multimedia/pvrxxx[] ports, but they provide a non-standard driver interface that does not work with versions of MythTV greater than 0.23. Due to licensing restrictions, no packages are available and these two ports must be compiled. The https://wiki.freebsd.org/HTPC[wiki.freebsd.org/HTPC] page contains a list of all available `DVB` drivers. === Setting up the MythTV Backend To install MythTV using binary packages: [source,shell] .... # pkg install mythtv .... Alternatively, to install from the Ports Collection: [source,shell] .... # cd /usr/ports/multimedia/mythtv # make install .... Once installed, set up the MythTV database: [source,shell] .... # mysql -uroot -p < /usr/local/share/mythtv/database/mc.sql .... Then, configure the backend: [source,shell] .... # mythtv-setup .... Finally, start the backend: [source,shell] .... # sysrc mythbackend_enable=yes # service mythbackend start .... [[scanners]] == Image Scanners In FreeBSD, access to image scanners is provided by SANE (Scanner Access Now Easy), which is available in the FreeBSD Ports Collection. SANE will also use some FreeBSD device drivers to provide access to the scanner hardware. FreeBSD supports both `SCSI` and `USB` scanners. Depending upon the scanner interface, different device drivers are required. Be sure the scanner is supported by SANE prior to performing any configuration. Refer to http://www.sane-project.org/sane-supported-devices.html[http://www.sane-project.org/sane-supported-devices.html] for more information about supported scanners. This chapter describes how to determine if the scanner has been detected by FreeBSD. It then provides an overview of how to configure and use SANE on a FreeBSD system. [[scanners-kernel-usb]] === Checking the Scanner The [.filename]#GENERIC# kernel includes the device drivers needed to support `USB` scanners. Users with a custom kernel should ensure that the following lines are present in the custom kernel configuration file: [.programlisting] .... device usb device uhci device ohci device ehci device xhci .... To determine if the `USB` scanner is detected, plug it in and use `dmesg` to determine whether the scanner appears in the system message buffer. If it does, it should display a message similar to this: [source,shell] .... ugen0.2: at usbus0 .... In this example, an EPSON Perfection(R) 1650 `USB` scanner was detected on [.filename]#/dev/ugen0.2#. If the scanner uses a `SCSI` interface, it is important to know which `SCSI` controller board it will use. Depending upon the `SCSI` chipset, a custom kernel configuration file may be needed. The [.filename]#GENERIC# kernel supports the most common `SCSI` controllers. Refer to [.filename]#/usr/src/sys/conf/NOTES# to determine the correct line to add to a custom kernel configuration file. In addition to the `SCSI` adapter driver, the following lines are needed in a custom kernel configuration file: [.programlisting] .... device scbus device pass .... Verify that the device is displayed in the system message buffer: [source,shell] .... pass2 at aic0 bus 0 target 2 lun 0 pass2: Fixed Scanner SCSI-2 device pass2: 3.300MB/s transfers .... If the scanner was not powered-on at system boot, it is still possible to manually force detection by performing a `SCSI` bus scan with `camcontrol`: [source,shell] .... # camcontrol rescan all Re-scan of bus 0 was successful Re-scan of bus 1 was successful Re-scan of bus 2 was successful Re-scan of bus 3 was successful .... The scanner should now appear in the `SCSI` devices list: [source,shell] .... # camcontrol devlist at scbus0 target 5 lun 0 (pass0,da0) at scbus0 target 6 lun 0 (pass1,da1) at scbus1 target 2 lun 0 (pass3) at scbus2 target 0 lun 0 (pass2,cd0) .... Refer to man:scsi[4] and man:camcontrol[8] for more details about `SCSI` devices on FreeBSD. === SANE Configuration The SANE system provides the access to the scanner via backends (package:graphics/sane-backends[]). Refer to http://www.sane-project.org/sane-supported-devices.html[http://www.sane-project.org/sane-supported-devices.html] to determine which backend supports the scanner. A graphical scanning interface is provided by third party applications like Kooka (package:graphics/kooka[]) or XSane (package:graphics/xsane[]). SANE's backends are enough to test the scanner. To install the backends from binary package: [source,shell] .... # pkg install sane-backends .... Alternatively, to install from the Ports Collection [source,shell] .... # cd /usr/ports/graphics/sane-backends # make install clean .... After installing the package:graphics/sane-backends[] port or package, use `sane-find-scanner` to check the scanner detection by the SANE system: [source,shell] .... # sane-find-scanner -q found SCSI scanner ""AGFA SNAPSCAN 600 1.10"" at /dev/pass3 .... The output should show the interface type of the scanner and the device node used to attach the scanner to the system. The vendor and the product model may or may not appear. [NOTE] ==== Some `USB` scanners require firmware to be loaded. Refer to sane-find-scanner(1) and sane(7) for details. ==== Next, check if the scanner will be identified by a scanning frontend. The SANE backends include `scanimage` which can be used to list the devices and perform an image acquisition. Use `-L` to list the scanner devices. The first example is for a `SCSI` scanner and the second is for a `USB` scanner: [source,shell] .... # scanimage -L device `snapscan:/dev/pass3' is a AGFA SNAPSCAN 600 flatbed scanner # scanimage -L device 'epson2:libusb:000:002' is a Epson GT-8200 flatbed scanner .... In this second example, `epson2` is the backend name and `libusb:000:002` means [.filename]#/dev/ugen0.2# is the device node used by the scanner. If `scanimage` is unable to identify the scanner, this message will appear: [source,shell] .... # scanimage -L No scanners were identified. If you were expecting something different, check that the scanner is plugged in, turned on and detected by the sane-find-scanner tool (if appropriate). Please read the documentation which came with this software (README, FAQ, manpages). .... If this happens, edit the backend configuration file in [.filename]#/usr/local/etc/sane.d/# and define the scanner device used. For example, if the undetected scanner model is an EPSON Perfection(R) 1650 and it uses the `epson2` backend, edit [.filename]#/usr/local/etc/sane.d/epson2.conf#. When editing, add a line specifying the interface and the device node used. In this case, add the following line: [.programlisting] .... usb /dev/ugen0.2 .... Save the edits and verify that the scanner is identified with the right backend name and the device node: [source,shell] .... # scanimage -L device 'epson2:libusb:000:002' is a Epson GT-8200 flatbed scanner .... Once `scanimage -L` sees the scanner, the configuration is complete and the scanner is now ready to use. While `scanimage` can be used to perform an image acquisition from the command line, it is often preferable to use a graphical interface to perform image scanning. Applications like Kooka or XSane are popular scanning frontends. They offer advanced features such as various scanning modes, color correction, and batch scans. XSane is also usable as a GIMP plugin. === Scanner Permissions In order to have access to the scanner, a user needs read and write permissions to the device node used by the scanner. In the previous example, the `USB` scanner uses the device node [.filename]#/dev/ugen0.2# which is really a symlink to the real device node [.filename]#/dev/usb/0.2.0#. The symlink and the device node are owned, respectively, by the `wheel` and `operator` groups. While adding the user to these groups will allow access to the scanner, it is considered insecure to add a user to `wheel`. A better solution is to create a group and make the scanner device accessible to members of this group. This example creates a group called `_usb_`: [source,shell] .... # pw groupadd usb .... Then, make the [.filename]#/dev/ugen0.2# symlink and the [.filename]#/dev/usb/0.2.0# device node accessible to the `usb` group with write permissions of `0660` or `0664` by adding the following lines to [.filename]#/etc/devfs.rules#: [.programlisting] .... [system=5] add path ugen0.2 mode 0660 group usb add path usb/0.2.0 mode 0666 group usb .... [NOTE] ==== It happens the device node changes with the addition or removal of devices, so one may want to give access to all USB devices using this ruleset instead: [.programlisting] .... [system=5] add path 'ugen*' mode 0660 group usb add path 'usb/*' mode 0666 group usb .... ==== Refer to man:devfs.rules[5] for more information about this file. Next, enable the ruleset in /etc/rc.conf: [.programlisting] .... devfs_system_ruleset=""system"" .... And, restart the man:devfs[8] system: [source,shell] .... # service devfs restart .... Finally, add the users to `_usb_` in order to allow access to the scanner: [source,shell] .... # pw groupmod usb -m joe .... For more details refer to man:pw[8]. ",12241,False,2116.1911264739347,median "/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include ""cmGlobalNinjaGenerator.h"" #include ""cm_jsoncpp_reader.h"" #include ""cm_jsoncpp_value.h"" #include ""cm_jsoncpp_writer.h"" #include ""cmsys/FStream.hxx"" #include #include #include #include #include // IWYU pragma: keep #include #include #include ""cmAlgorithms.h"" #include ""cmDocumentationEntry.h"" #include ""cmFortranParser.h"" #include ""cmGeneratedFileStream.h"" #include ""cmGeneratorExpressionEvaluationFile.h"" #include ""cmGeneratorTarget.h"" #include ""cmLocalGenerator.h"" #include ""cmLocalNinjaGenerator.h"" #include ""cmMakefile.h"" #include ""cmNinjaLinkLineComputer.h"" #include ""cmOutputConverter.h"" #include ""cmState.h"" #include ""cmStateDirectory.h"" #include ""cmStateSnapshot.h"" #include ""cmStateTypes.h"" #include ""cmSystemTools.h"" #include ""cmTarget.h"" #include ""cmTargetDepend.h"" #include ""cmVersion.h"" #include ""cmake.h"" class cmLinkLineComputer; const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = ""build.ninja""; const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = ""rules.ninja""; const char* cmGlobalNinjaGenerator::INDENT = "" ""; #ifdef _WIN32 std::string const cmGlobalNinjaGenerator::SHELL_NOOP = ""cd .""; #else std::string const cmGlobalNinjaGenerator::SHELL_NOOP = "":""; #endif void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count) { for (int i = 0; i < count; ++i) { os << cmGlobalNinjaGenerator::INDENT; } } void cmGlobalNinjaGenerator::WriteDivider(std::ostream& os) { os << ""# ======================================"" ""=======================================\\n""; } void cmGlobalNinjaGenerator::WriteComment(std::ostream& os, const std::string& comment) { if (comment.empty()) { return; } std::string::size_type lpos = 0; std::string::size_type rpos; os << ""\\n#############################################\\n""; while ((rpos = comment.find('\\n', lpos)) != std::string::npos) { os << ""# "" << comment.substr(lpos, rpos - lpos) << ""\\n""; lpos = rpos + 1; } os << ""# "" << comment.substr(lpos) << ""\\n\\n""; } cmLinkLineComputer* cmGlobalNinjaGenerator::CreateLinkLineComputer( cmOutputConverter* outputConverter, cmStateDirectory const& /* stateDir */) const { return new cmNinjaLinkLineComputer( outputConverter, this->LocalGenerators[0]->GetStateSnapshot().GetDirectory(), this); } std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name) { // Ninja rule names must match ""[a-zA-Z0-9_.-]+"". Use "".xx"" to encode // ""."" and all invalid characters as hexadecimal. std::string encoded; for (char i : name) { if (isalnum(i) || i == '_' || i == '-') { encoded += i; } else { char buf[16]; sprintf(buf, "".%02x"", static_cast(i)); encoded += buf; } } return encoded; } static bool IsIdentChar(char c) { return ('a' <= c && c <= 'z') || ('+' <= c && c <= '9') || // +,-./ and numbers ('A' <= c && c <= 'Z') || (c == '_') || (c == '$') || (c == '\\\\') || (c == ' ') || (c == ':'); } std::string cmGlobalNinjaGenerator::EncodeIdent(const std::string& ident, std::ostream& vars) { if (std::find_if(ident.begin(), ident.end(), std::not1(std::ptr_fun(IsIdentChar))) != ident.end()) { static unsigned VarNum = 0; std::ostringstream names; names << ""ident"" << VarNum++; vars << names.str() << "" = "" << ident << ""\\n""; return ""$"" + names.str(); } std::string result = ident; cmSystemTools::ReplaceString(result, "" "", ""$ ""); cmSystemTools::ReplaceString(result, "":"", ""$:""); return result; } std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string& lit) { std::string result = lit; cmSystemTools::ReplaceString(result, ""$"", ""$$""); cmSystemTools::ReplaceString(result, ""\\n"", ""$\\n""); return result; } std::string cmGlobalNinjaGenerator::EncodePath(const std::string& path) { std::string result = path; // NOLINT(clang-tidy) #ifdef _WIN32 if (this->IsGCCOnWindows()) std::replace(result.begin(), result.end(), '\\\\', '/'); else std::replace(result.begin(), result.end(), '/', '\\\\'); #endif return EncodeLiteral(result); } void cmGlobalNinjaGenerator::WriteBuild( std::ostream& os, const std::string& comment, const std::string& rule, const cmNinjaDeps& outputs, const cmNinjaDeps& implicitOuts, const cmNinjaDeps& explicitDeps, const cmNinjaDeps& implicitDeps, const cmNinjaDeps& orderOnlyDeps, const cmNinjaVars& variables, const std::string& rspfile, int cmdLineLimit, bool* usedResponseFile) { // Make sure there is a rule. if (rule.empty()) { cmSystemTools::Error(""No rule for WriteBuildStatement! called "" ""with comment: "", comment.c_str()); return; } // Make sure there is at least one output file. if (outputs.empty()) { cmSystemTools::Error(""No output files for WriteBuildStatement! called "" ""with comment: "", comment.c_str()); return; } cmGlobalNinjaGenerator::WriteComment(os, comment); std::string arguments; // TODO: Better formatting for when there are multiple input/output files. // Write explicit dependencies. for (std::string const& explicitDep : explicitDeps) { arguments += "" "" + EncodeIdent(EncodePath(explicitDep), os); } // Write implicit dependencies. if (!implicitDeps.empty()) { arguments += "" |""; for (std::string const& implicitDep : implicitDeps) { arguments += "" "" + EncodeIdent(EncodePath(implicitDep), os); } } // Write order-only dependencies. if (!orderOnlyDeps.empty()) { arguments += "" ||""; for (std::string const& orderOnlyDep : orderOnlyDeps) { arguments += "" "" + EncodeIdent(EncodePath(orderOnlyDep), os); } } arguments += ""\\n""; std::string build; // Write outputs files. build += ""build""; for (std::string const& output : outputs) { build += "" "" + EncodeIdent(EncodePath(output), os); if (this->ComputingUnknownDependencies) { this->CombinedBuildOutputs.insert(output); } } if (!implicitOuts.empty()) { build += "" |""; for (std::string const& implicitOut : implicitOuts) { build += "" "" + EncodeIdent(EncodePath(implicitOut), os); } } build += "":""; // Write the rule. build += "" "" + rule; // Write the variables bound to this build statement. std::ostringstream variable_assignments; for (auto const& variable : variables) { cmGlobalNinjaGenerator::WriteVariable(variable_assignments, variable.first, variable.second, """", 1); } // check if a response file rule should be used std::string buildstr = build; std::string assignments = variable_assignments.str(); bool useResponseFile = false; if (cmdLineLimit < 0 || (cmdLineLimit > 0 && (arguments.size() + buildstr.size() + assignments.size() + 1000) > static_cast(cmdLineLimit))) { variable_assignments.str(std::string()); cmGlobalNinjaGenerator::WriteVariable(variable_assignments, ""RSP_FILE"", rspfile, """", 1); assignments += variable_assignments.str(); useResponseFile = true; } if (usedResponseFile) { *usedResponseFile = useResponseFile; } os << buildstr << arguments << assignments; } void cmGlobalNinjaGenerator::WritePhonyBuild( std::ostream& os, const std::string& comment, const cmNinjaDeps& outputs, const cmNinjaDeps& explicitDeps, const cmNinjaDeps& implicitDeps, const cmNinjaDeps& orderOnlyDeps, const cmNinjaVars& variables) { this->WriteBuild(os, comment, ""phony"", outputs, /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps, orderOnlyDeps, variables); } void cmGlobalNinjaGenerator::AddCustomCommandRule() { this->AddRule(""CUSTOM_COMMAND"", ""$COMMAND"", ""$DESC"", ""Rule for running custom commands."", /*depfile*/ """", /*deptype*/ """", /*rspfile*/ """", /*rspcontent*/ """", /*restat*/ """", // bound on each build statement as needed /*generator*/ false); } void cmGlobalNinjaGenerator::WriteCustomCommandBuild( const std::string& command, const std::string& description, const std::string& comment, const std::string& depfile, bool uses_terminal, bool restat, const cmNinjaDeps& outputs, const cmNinjaDeps& deps, const cmNinjaDeps& orderOnly) { std::string cmd = command; // NOLINT(clang-tidy) #ifdef _WIN32 if (cmd.empty()) // TODO Shouldn't an empty command be handled by ninja? cmd = ""cmd.exe /c""; #endif this->AddCustomCommandRule(); cmNinjaVars vars; vars[""COMMAND""] = cmd; vars[""DESC""] = EncodeLiteral(description); if (restat) { vars[""restat""] = ""1""; } if (uses_terminal && SupportsConsolePool()) { vars[""pool""] = ""console""; } if (!depfile.empty()) { vars[""depfile""] = depfile; } this->WriteBuild(*this->BuildFileStream, comment, ""CUSTOM_COMMAND"", outputs, /*implicitOuts=*/cmNinjaDeps(), deps, cmNinjaDeps(), orderOnly, vars); if (this->ComputingUnknownDependencies) { // we need to track every dependency that comes in, since we are trying // to find dependencies that are side effects of build commands for (std::string const& dep : deps) { this->CombinedCustomCommandExplicitDependencies.insert(dep); } } } void cmGlobalNinjaGenerator::AddMacOSXContentRule() { cmLocalGenerator* lg = this->LocalGenerators[0]; std::ostringstream cmd; cmd << lg->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL) << "" -E copy $in $out""; this->AddRule(""COPY_OSX_CONTENT"", cmd.str(), ""Copying OS X Content $out"", ""Rule for copying OS X bundle content file."", /*depfile*/ """", /*deptype*/ """", /*rspfile*/ """", /*rspcontent*/ """", /*restat*/ """", /*generator*/ false); } void cmGlobalNinjaGenerator::WriteMacOSXContentBuild(const std::string& input, const std::string& output) { this->AddMacOSXContentRule(); cmNinjaDeps outputs; outputs.push_back(output); cmNinjaDeps deps; deps.push_back(input); cmNinjaVars vars; this->WriteBuild(*this->BuildFileStream, """", ""COPY_OSX_CONTENT"", outputs, /*implicitOuts=*/cmNinjaDeps(), deps, cmNinjaDeps(), cmNinjaDeps(), cmNinjaVars()); } void cmGlobalNinjaGenerator::WriteRule( std::ostream& os, const std::string& name, const std::string& command, const std::string& description, const std::string& comment, const std::string& depfile, const std::string& deptype, const std::string& rspfile, const std::string& rspcontent, const std::string& restat, bool generator) { // Make sure the rule has a name. if (name.empty()) { cmSystemTools::Error(""No name given for WriteRuleStatement! called "" ""with comment: "", comment.c_str()); return; } // Make sure a command is given. if (command.empty()) { cmSystemTools::Error(""No command given for WriteRuleStatement! called "" ""with comment: "", comment.c_str()); return; } cmGlobalNinjaGenerator::WriteComment(os, comment); // Write the rule. os << ""rule "" << name << ""\\n""; // Write the depfile if any. if (!depfile.empty()) { cmGlobalNinjaGenerator::Indent(os, 1); os << ""depfile = "" << depfile << ""\\n""; } // Write the deptype if any. if (!deptype.empty()) { cmGlobalNinjaGenerator::Indent(os, 1); os << ""deps = "" << deptype << ""\\n""; } // Write the command. cmGlobalNinjaGenerator::Indent(os, 1); os << ""command = "" << command << ""\\n""; // Write the description if any. if (!description.empty()) { cmGlobalNinjaGenerator::Indent(os, 1); os << ""description = "" << description << ""\\n""; } if (!rspfile.empty()) { if (rspcontent.empty()) { cmSystemTools::Error(""No rspfile_content given!"", comment.c_str()); return; } cmGlobalNinjaGenerator::Indent(os, 1); os << ""rspfile = "" << rspfile << ""\\n""; cmGlobalNinjaGenerator::Indent(os, 1); os << ""rspfile_content = "" << rspcontent << ""\\n""; } if (!restat.empty()) { cmGlobalNinjaGenerator::Indent(os, 1); os << ""restat = "" << restat << ""\\n""; } if (generator) { cmGlobalNinjaGenerator::Indent(os, 1); os << ""generator = 1\\n""; } os << ""\\n""; } void cmGlobalNinjaGenerator::WriteVariable(std::ostream& os, const std::string& name, const std::string& value, const std::string& comment, int indent) { // Make sure we have a name. if (name.empty()) { cmSystemTools::Error(""No name given for WriteVariable! called "" ""with comment: "", comment.c_str()); return; } // Do not add a variable if the value is empty. std::string val = cmSystemTools::TrimWhitespace(value); if (val.empty()) { return; } cmGlobalNinjaGenerator::WriteComment(os, comment); cmGlobalNinjaGenerator::Indent(os, indent); os << name << "" = "" << val << ""\\n""; } void cmGlobalNinjaGenerator::WriteInclude(std::ostream& os, const std::string& filename, const std::string& comment) { cmGlobalNinjaGenerator::WriteComment(os, comment); os << ""include "" << filename << ""\\n""; } void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os, const cmNinjaDeps& targets, const std::string& comment) { cmGlobalNinjaGenerator::WriteComment(os, comment); os << ""default""; for (std::string const& target : targets) { os << "" "" << target; } os << ""\\n""; } cmGlobalNinjaGenerator::cmGlobalNinjaGenerator(cmake* cm) : cmGlobalCommonGenerator(cm) , BuildFileStream(nullptr) , RulesFileStream(nullptr) , CompileCommandsStream(nullptr) , Rules() , AllDependencies() , UsingGCCOnWindows(false) , ComputingUnknownDependencies(false) , PolicyCMP0058(cmPolicies::WARN) , NinjaSupportsConsolePool(false) , NinjaSupportsImplicitOuts(false) , NinjaSupportsDyndeps(0) { #ifdef _WIN32 cm->GetState()->SetWindowsShell(true); #endif // // Ninja is not ported to non-Unix OS yet. // this->ForceUnixPaths = true; this->FindMakeProgramFile = ""CMakeNinjaFindMake.cmake""; } // Virtual public methods. cmLocalGenerator* cmGlobalNinjaGenerator::CreateLocalGenerator(cmMakefile* mf) { return new cmLocalNinjaGenerator(this, mf); } codecvt::Encoding cmGlobalNinjaGenerator::GetMakefileEncoding() const { #ifdef _WIN32 // Ninja on Windows does not support non-ANSI characters. // https://github.com/ninja-build/ninja/issues/1195 return codecvt::ANSI; #else // No encoding conversion needed on other platforms. return codecvt::None; #endif } void cmGlobalNinjaGenerator::GetDocumentation(cmDocumentationEntry& entry) { entry.Name = cmGlobalNinjaGenerator::GetActualName(); entry.Brief = ""Generates build.ninja files.""; } // Implemented in all cmGlobaleGenerator sub-classes. // Used in: // Source/cmLocalGenerator.cxx // Source/cmake.cxx void cmGlobalNinjaGenerator::Generate() { // Check minimum Ninja version. if (cmSystemTools::VersionCompare(cmSystemTools::OP_LESS, this->NinjaVersion.c_str(), RequiredNinjaVersion().c_str())) { std::ostringstream msg; msg << ""The detected version of Ninja ("" << this->NinjaVersion; msg << "") is less than the version of Ninja required by CMake (""; msg << this->RequiredNinjaVersion() << "").""; this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, msg.str()); return; } this->OpenBuildFileStream(); this->OpenRulesFileStream(); this->TargetDependsClosures.clear(); this->InitOutputPathPrefix(); this->TargetAll = this->NinjaOutputPath(""all""); this->CMakeCacheFile = this->NinjaOutputPath(""CMakeCache.txt""); this->PolicyCMP0058 = this->LocalGenerators[0]->GetMakefile()->GetPolicyStatus( cmPolicies::CMP0058); this->ComputingUnknownDependencies = (this->PolicyCMP0058 == cmPolicies::OLD || this->PolicyCMP0058 == cmPolicies::WARN); this->cmGlobalGenerator::Generate(); this->WriteAssumedSourceDependencies(); this->WriteTargetAliases(*this->BuildFileStream); this->WriteFolderTargets(*this->BuildFileStream); this->WriteUnknownExplicitDependencies(*this->BuildFileStream); this->WriteBuiltinTargets(*this->BuildFileStream); if (cmSystemTools::GetErrorOccuredFlag()) { this->RulesFileStream->setstate(std::ios::failbit); this->BuildFileStream->setstate(std::ios::failbit); } this->CloseCompileCommandsStream(); this->CloseRulesFileStream(); this->CloseBuildFileStream(); } bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf) { if (!this->cmGlobalGenerator::FindMakeProgram(mf)) { return false; } if (const char* ninjaCommand = mf->GetDefinition(""CMAKE_MAKE_PROGRAM"")) { this->NinjaCommand = ninjaCommand; std::vector command; command.push_back(this->NinjaCommand); command.push_back(""--version""); std::string version; std::string error; if (!cmSystemTools::RunSingleCommand(command, &version, &error, nullptr, nullptr, cmSystemTools::OUTPUT_NONE)) { mf->IssueMessage(cmake::FATAL_ERROR, ""Running\\n '"" + cmJoin(command, ""' '"") + ""'\\n"" ""failed with:\\n "" + error); cmSystemTools::SetFatalErrorOccured(); return false; } this->NinjaVersion = cmSystemTools::TrimWhitespace(version); this->CheckNinjaFeatures(); } return true; } void cmGlobalNinjaGenerator::CheckNinjaFeatures() { this->NinjaSupportsConsolePool = !cmSystemTools::VersionCompare( cmSystemTools::OP_LESS, this->NinjaVersion.c_str(), RequiredNinjaVersionForConsolePool().c_str()); this->NinjaSupportsImplicitOuts = !cmSystemTools::VersionCompare( cmSystemTools::OP_LESS, this->NinjaVersion.c_str(), this->RequiredNinjaVersionForImplicitOuts().c_str()); { // Our ninja branch adds "".dyndep-#"" to its version number, // where '#' is a feature-specific version number. Extract it. static std::string const k_DYNDEP_ = "".dyndep-""; std::string::size_type pos = this->NinjaVersion.find(k_DYNDEP_); if (pos != std::string::npos) { const char* fv = this->NinjaVersion.c_str() + pos + k_DYNDEP_.size(); cmSystemTools::StringToULong(fv, &this->NinjaSupportsDyndeps); } } } bool cmGlobalNinjaGenerator::CheckLanguages( std::vector const& languages, cmMakefile* mf) const { if (std::find(languages.begin(), languages.end(), ""Fortran"") != languages.end()) { return this->CheckFortran(mf); } return true; } bool cmGlobalNinjaGenerator::CheckFortran(cmMakefile* mf) const { if (this->NinjaSupportsDyndeps == 1) { return true; } std::ostringstream e; if (this->NinjaSupportsDyndeps == 0) { /* clang-format off */ e << ""The Ninja generator does not support Fortran using Ninja version\\n"" "" "" + this->NinjaVersion + ""\\n"" ""due to lack of required features. "" ""Kitware has implemented the required features but as of this version "" ""of CMake they have not been integrated to upstream ninja. "" ""Pending integration, Kitware maintains a branch at:\\n"" "" https://github.com/Kitware/ninja/tree/features-for-fortran#readme\\n"" ""with the required features. "" ""One may build ninja from that branch to get support for Fortran."" ; /* clang-format on */ } else { /* clang-format off */ e << ""The Ninja generator in this version of CMake does not support Fortran "" ""using Ninja version\\n"" "" "" + this->NinjaVersion + ""\\n"" ""because its 'dyndep' feature version is "" << this->NinjaSupportsDyndeps << "". "" ""This version of CMake is aware only of 'dyndep' feature version 1."" ; /* clang-format on */ } mf->IssueMessage(cmake::FATAL_ERROR, e.str()); cmSystemTools::SetFatalErrorOccured(); return false; } void cmGlobalNinjaGenerator::EnableLanguage( std::vector const& langs, cmMakefile* mf, bool optional) { this->cmGlobalGenerator::EnableLanguage(langs, mf, optional); for (std::string const& l : langs) { if (l == ""NONE"") { continue; } this->ResolveLanguageCompiler(l, mf, optional); } #ifdef _WIN32 if (strcmp(mf->GetSafeDefinition(""CMAKE_C_SIMULATE_ID""), ""MSVC"") != 0 && strcmp(mf->GetSafeDefinition(""CMAKE_CXX_SIMULATE_ID""), ""MSVC"") != 0 && (mf->IsOn(""CMAKE_COMPILER_IS_MINGW"") || strcmp(mf->GetSafeDefinition(""CMAKE_C_COMPILER_ID""), ""GNU"") == 0 || strcmp(mf->GetSafeDefinition(""CMAKE_CXX_COMPILER_ID""), ""GNU"") == 0 || strcmp(mf->GetSafeDefinition(""CMAKE_C_COMPILER_ID""), ""Clang"") == 0 || strcmp(mf->GetSafeDefinition(""CMAKE_CXX_COMPILER_ID""), ""Clang"") == 0)) { this->UsingGCCOnWindows = true; } #endif } // Implemented by: // cmGlobalUnixMakefileGenerator3 // cmGlobalGhsMultiGenerator // cmGlobalVisualStudio10Generator // cmGlobalVisualStudio7Generator // cmGlobalXCodeGenerator // Called by: // cmGlobalGenerator::Build() void cmGlobalNinjaGenerator::GenerateBuildCommand( std::vector& makeCommand, const std::string& makeProgram, const std::string& /*projectName*/, const std::string& /*projectDir*/, const std::string& targetName, const std::string& /*config*/, bool /*fast*/, bool verbose, std::vector const& makeOptions) { makeCommand.push_back(this->SelectMakeProgram(makeProgram)); if (verbose) { makeCommand.push_back(""-v""); } makeCommand.insert(makeCommand.end(), makeOptions.begin(), makeOptions.end()); if (!targetName.empty()) { if (targetName == ""clean"") { makeCommand.push_back(""-t""); makeCommand.push_back(""clean""); } else { makeCommand.push_back(targetName); } } } // Non-virtual public methods. void cmGlobalNinjaGenerator::AddRule( const std::string& name, const std::string& command, const std::string& description, const std::string& comment, const std::string& depfile, const std::string& deptype, const std::string& rspfile, const std::string& rspcontent, const std::string& restat, bool generator) { // Do not add the same rule twice. if (this->HasRule(name)) { return; } this->Rules.insert(name); cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream, name, command, description, comment, depfile, deptype, rspfile, rspcontent, restat, generator); this->RuleCmdLength[name] = static_cast(command.size()); } bool cmGlobalNinjaGenerator::HasRule(const std::string& name) { RulesSetType::const_iterator rule = this->Rules.find(name); return (rule != this->Rules.end()); } // Private virtual overrides std::string cmGlobalNinjaGenerator::GetEditCacheCommand() const { // Ninja by design does not run interactive tools in the terminal, // so our only choice is cmake-gui. return cmSystemTools::GetCMakeGUICommand(); } void cmGlobalNinjaGenerator::ComputeTargetObjectDirectory( cmGeneratorTarget* gt) const { // Compute full path to object file directory for this target. std::string dir; dir += gt->LocalGenerator->GetCurrentBinaryDirectory(); dir += ""/""; dir += gt->LocalGenerator->GetTargetDirectory(gt); dir += ""/""; gt->ObjectDirectory = dir; } // Private methods void cmGlobalNinjaGenerator::OpenBuildFileStream() { // Compute Ninja's build file path. std::string buildFilePath = this->GetCMakeInstance()->GetHomeOutputDirectory(); buildFilePath += ""/""; buildFilePath += cmGlobalNinjaGenerator::NINJA_BUILD_FILE; // Get a stream where to generate things. if (!this->BuildFileStream) { this->BuildFileStream = new cmGeneratedFileStream( buildFilePath.c_str(), false, this->GetMakefileEncoding()); if (!this->BuildFileStream) { // An error message is generated by the constructor if it cannot // open the file. return; } } // Write the do not edit header. this->WriteDisclaimer(*this->BuildFileStream); // Write a comment about this file. *this->BuildFileStream << ""# This file contains all the build statements describing the\\n"" << ""# compilation DAG.\\n\\n""; } void cmGlobalNinjaGenerator::CloseBuildFileStream() { if (this->BuildFileStream) { delete this->BuildFileStream; this->BuildFileStream = nullptr; } else { cmSystemTools::Error(""Build file stream was not open.""); } } void cmGlobalNinjaGenerator::OpenRulesFileStream() { // Compute Ninja's build file path. std::string rulesFilePath = this->GetCMakeInstance()->GetHomeOutputDirectory(); rulesFilePath += ""/""; rulesFilePath += cmGlobalNinjaGenerator::NINJA_RULES_FILE; // Get a stream where to generate things. if (!this->RulesFileStream) { this->RulesFileStream = new cmGeneratedFileStream( rulesFilePath.c_str(), false, this->GetMakefileEncoding()); if (!this->RulesFileStream) { // An error message is generated by the constructor if it cannot // open the file. return; } } // Write the do not edit header. this->WriteDisclaimer(*this->RulesFileStream); // Write comment about this file. /* clang-format off */ *this->RulesFileStream << ""# This file contains all the rules used to get the outputs files\\n"" << ""# built from the input files.\\n"" << ""# It is included in the main '"" << NINJA_BUILD_FILE << ""'.\\n\\n"" ; /* clang-format on */ } void cmGlobalNinjaGenerator::CloseRulesFileStream() { if (this->RulesFileStream) { delete this->RulesFileStream; this->RulesFileStream = nullptr; } else { cmSystemTools::Error(""Rules file stream was not open.""); } } static void EnsureTrailingSlash(std::string& path) { if (path.empty()) { return; } std::string::value_type last = path[path.size() - 1]; #ifdef _WIN32 if (last != '\\\\') { path += '\\\\'; } #else if (last != '/') { path += '/'; } #endif } std::string const& cmGlobalNinjaGenerator::ConvertToNinjaPath( const std::string& path) const { auto const f = ConvertToNinjaPathCache.find(path); if (f != ConvertToNinjaPathCache.end()) { return f->second; } cmLocalNinjaGenerator* ng = static_cast(this->LocalGenerators[0]); const char* bin_dir = ng->GetState()->GetBinaryDirectory(); std::string convPath = ng->ConvertToRelativePath(bin_dir, path); convPath = this->NinjaOutputPath(convPath); #ifdef _WIN32 std::replace(convPath.begin(), convPath.end(), '/', '\\\\'); #endif return ConvertToNinjaPathCache.emplace(path, std::move(convPath)) .first->second; } void cmGlobalNinjaGenerator::AddCXXCompileCommand( const std::string& commandLine, const std::string& sourceFile) { // Compute Ninja's build file path. std::string buildFileDir = this->GetCMakeInstance()->GetHomeOutputDirectory(); if (!this->CompileCommandsStream) { std::string buildFilePath = buildFileDir + ""/compile_commands.json""; if (this->ComputingUnknownDependencies) { this->CombinedBuildOutputs.insert( this->NinjaOutputPath(""compile_commands.json"")); } // Get a stream where to generate things. this->CompileCommandsStream = new cmGeneratedFileStream(buildFilePath.c_str()); *this->CompileCommandsStream << ""[""; } else { *this->CompileCommandsStream << "","" << std::endl; } std::string sourceFileName = sourceFile; if (!cmSystemTools::FileIsFullPath(sourceFileName.c_str())) { sourceFileName = cmSystemTools::CollapseFullPath( sourceFileName, this->GetCMakeInstance()->GetHomeOutputDirectory()); } /* clang-format off */ *this->CompileCommandsStream << ""\\n{\\n"" << "" \\""directory\\"": \\"""" << cmGlobalGenerator::EscapeJSON(buildFileDir) << ""\\"",\\n"" << "" \\""command\\"": \\"""" << cmGlobalGenerator::EscapeJSON(commandLine) << ""\\"",\\n"" << "" \\""file\\"": \\"""" << cmGlobalGenerator::EscapeJSON(sourceFileName) << ""\\""\\n"" << ""}""; /* clang-format on */ } void cmGlobalNinjaGenerator::CloseCompileCommandsStream() { if (this->CompileCommandsStream) { *this->CompileCommandsStream << ""\\n]""; delete this->CompileCommandsStream; this->CompileCommandsStream = nullptr; } } void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os) { os << ""# CMAKE generated file: DO NOT EDIT!\\n"" << ""# Generated by \\"""" << this->GetName() << ""\\"""" << "" Generator, CMake Version "" << cmVersion::GetMajorVersion() << ""."" << cmVersion::GetMinorVersion() << ""\\n\\n""; } void cmGlobalNinjaGenerator::AddDependencyToAll(cmGeneratorTarget* target) { this->AppendTargetOutputs(target, this->AllDependencies); } void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input) { this->AllDependencies.push_back(input); } void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies() { for (auto const& asd : this->AssumedSourceDependencies) { cmNinjaDeps deps; std::copy(asd.second.begin(), asd.second.end(), std::back_inserter(deps)); WriteCustomCommandBuild(/*command=*/"""", /*description=*/"""", ""Assume dependencies for generated source file."", /*depfile*/ """", /*uses_terminal*/ false, /*restat*/ true, cmNinjaDeps(1, asd.first), deps); } } std::string OrderDependsTargetForTarget(cmGeneratorTarget const* target) { return ""cmake_object_order_depends_target_"" + target->GetName(); } void cmGlobalNinjaGenerator::AppendTargetOutputs( cmGeneratorTarget const* target, cmNinjaDeps& outputs, cmNinjaTargetDepends depends) { std::string configName = target->Target->GetMakefile()->GetSafeDefinition(""CMAKE_BUILD_TYPE""); // for frameworks, we want the real name, not smple name // frameworks always appear versioned, and the build.ninja // will always attempt to manage symbolic links instead // of letting cmOSXBundleGenerator do it. bool realname = target->IsFrameworkOnApple(); switch (target->GetType()) { case cmStateEnums::SHARED_LIBRARY: case cmStateEnums::STATIC_LIBRARY: case cmStateEnums::MODULE_LIBRARY: { if (depends == DependOnTargetOrdering) { outputs.push_back(OrderDependsTargetForTarget(target)); break; } } // FALLTHROUGH case cmStateEnums::EXECUTABLE: { outputs.push_back(this->ConvertToNinjaPath(target->GetFullPath( configName, cmStateEnums::RuntimeBinaryArtifact, realname))); break; } case cmStateEnums::OBJECT_LIBRARY: { if (depends == DependOnTargetOrdering) { outputs.push_back(OrderDependsTargetForTarget(target)); break; } } // FALLTHROUGH case cmStateEnums::GLOBAL_TARGET: case cmStateEnums::UTILITY: { std::string path = target->GetLocalGenerator()->GetCurrentBinaryDirectory() + std::string(""/"") + target->GetName(); outputs.push_back(this->ConvertToNinjaPath(path)); break; } default: return; } } void cmGlobalNinjaGenerator::AppendTargetDepends( cmGeneratorTarget const* target, cmNinjaDeps& outputs, cmNinjaTargetDepends depends) { if (target->GetType() == cmStateEnums::GLOBAL_TARGET) { // These depend only on other CMake-provided targets, e.g. ""all"". std::set const& utils = target->GetUtilities(); for (std::string const& util : utils) { std::string d = target->GetLocalGenerator()->GetCurrentBinaryDirectory() + std::string(""/"") + util; outputs.push_back(this->ConvertToNinjaPath(d)); } } else { cmNinjaDeps outs; cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target); for (cmTargetDepend const& targetDep : targetDeps) { if (targetDep->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } this->AppendTargetOutputs(targetDep, outs, depends); } std::sort(outs.begin(), outs.end()); outputs.insert(outputs.end(), outs.begin(), outs.end()); } } void cmGlobalNinjaGenerator::AppendTargetDependsClosure( cmGeneratorTarget const* target, cmNinjaDeps& outputs) { cmNinjaOuts outs; this->AppendTargetDependsClosure(target, outs, true); outputs.insert(outputs.end(), outs.begin(), outs.end()); } void cmGlobalNinjaGenerator::AppendTargetDependsClosure( cmGeneratorTarget const* target, cmNinjaOuts& outputs, bool omit_self) { // try to locate the target in the cache auto find = this->TargetDependsClosures.lower_bound(target); if (find == this->TargetDependsClosures.end() || find->first != target) { // We now calculate the closure outputs by inspecting the dependent // targets recursively. // For that we have to distinguish between a local result set that is only // relevant for filling the cache entries properly isolated and a global // result set that is relevant for the result of the top level call to // AppendTargetDependsClosure. auto const& targetDeps = this->GetTargetDirectDepends(target); cmNinjaOuts this_outs; // this will be the new cache entry for (auto const& dep_target : targetDeps) { if (dep_target->GetType() == cmStateEnums::INTERFACE_LIBRARY) { continue; } // Collect the dependent targets for _this_ target this->AppendTargetDependsClosure(dep_target, this_outs, false); } find = this->TargetDependsClosures.emplace_hint(find, target, std::move(this_outs)); } // now fill the outputs of the final result from the newly generated cache // entry outputs.insert(find->second.begin(), find->second.end()); // finally generate the outputs of the target itself, if applicable cmNinjaDeps outs; if (!omit_self) { this->AppendTargetOutputs(target, outs); } outputs.insert(outs.begin(), outs.end()); } void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias, cmGeneratorTarget* target) { std::string buildAlias = this->NinjaOutputPath(alias); cmNinjaDeps outputs; this->AppendTargetOutputs(target, outputs); // Mark the target's outputs as ambiguous to ensure that no other target uses // the output as an alias. for (std::string const& output : outputs) { TargetAliases[output] = nullptr; } // Insert the alias into the map. If the alias was already present in the // map and referred to another target, mark it as ambiguous. std::pair newAlias = TargetAliases.insert(std::make_pair(buildAlias, target)); if (newAlias.second && newAlias.first->second != target) { newAlias.first->second = nullptr; } } void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os) { cmGlobalNinjaGenerator::WriteDivider(os); os << ""# Target aliases.\\n\\n""; for (auto const& ta : TargetAliases) { // Don't write ambiguous aliases. if (!ta.second) { continue; } cmNinjaDeps deps; this->AppendTargetOutputs(ta.second, deps); this->WritePhonyBuild(os, """", cmNinjaDeps(1, ta.first), deps); } } void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os) { cmGlobalNinjaGenerator::WriteDivider(os); os << ""# Folder targets.\\n\\n""; std::map targetsPerFolder; for (cmLocalGenerator const* lg : this->LocalGenerators) { const std::string currentBinaryFolder( lg->GetStateSnapshot().GetDirectory().GetCurrentBinary()); // The directory-level rule should depend on the target-level rules // for all targets in the directory. targetsPerFolder[currentBinaryFolder] = cmNinjaDeps(); for (auto gt : lg->GetGeneratorTargets()) { cmStateEnums::TargetType const type = gt->GetType(); if ((type == cmStateEnums::EXECUTABLE || type == cmStateEnums::STATIC_LIBRARY || type == cmStateEnums::SHARED_LIBRARY || type == cmStateEnums::MODULE_LIBRARY || type == cmStateEnums::OBJECT_LIBRARY || type == cmStateEnums::UTILITY) && !gt->GetPropertyAsBool(""EXCLUDE_FROM_ALL"")) { targetsPerFolder[currentBinaryFolder].push_back(gt->GetName()); } } // The directory-level rule should depend on the directory-level // rules of the subdirectories. std::vector const& children = lg->GetStateSnapshot().GetChildren(); for (cmStateSnapshot const& state : children) { std::string const currentBinaryDir = state.GetDirectory().GetCurrentBinary(); targetsPerFolder[currentBinaryFolder].push_back( this->ConvertToNinjaPath(currentBinaryDir + ""/all"")); } } std::string const rootBinaryDir = this->LocalGenerators[0]->GetBinaryDirectory(); for (auto const& it : targetsPerFolder) { cmGlobalNinjaGenerator::WriteDivider(os); std::string const& currentBinaryDir = it.first; // Do not generate a rule for the root binary dir. if (rootBinaryDir.length() >= currentBinaryDir.length()) { continue; } std::string const comment = ""Folder: "" + currentBinaryDir; cmNinjaDeps output(1); output.push_back(this->ConvertToNinjaPath(currentBinaryDir + ""/all"")); this->WritePhonyBuild(os, comment, output, it.second); } } void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os) { if (!this->ComputingUnknownDependencies) { return; } // We need to collect the set of known build outputs. // Start with those generated by WriteBuild calls. // No other method needs this so we can take ownership // of the set locally and throw it out when we are done. std::set knownDependencies; knownDependencies.swap(this->CombinedBuildOutputs); // now write out the unknown explicit dependencies. // union the configured files, evaluations files and the // CombinedBuildOutputs, // and then difference with CombinedExplicitDependencies to find the explicit // dependencies that we have no rule for cmGlobalNinjaGenerator::WriteDivider(os); /* clang-format off */ os << ""# Unknown Build Time Dependencies.\\n"" << ""# Tell Ninja that they may appear as side effects of build rules\\n"" << ""# otherwise ordered by order-only dependencies.\\n\\n""; /* clang-format on */ // get the list of files that cmake itself has generated as a // product of configuration. for (cmLocalGenerator* lg : this->LocalGenerators) { // get the vector of files created by this makefile and convert them // to ninja paths, which are all relative in respect to the build directory const std::vector& files = lg->GetMakefile()->GetOutputFiles(); for (std::string const& file : files) { knownDependencies.insert(this->ConvertToNinjaPath(file)); } // get list files which are implicit dependencies as well and will be phony // for rebuild manifest std::vector const& lf = lg->GetMakefile()->GetListFiles(); for (std::string const& j : lf) { knownDependencies.insert(this->ConvertToNinjaPath(j)); } std::vector const& ef = lg->GetMakefile()->GetEvaluationFiles(); for (cmGeneratorExpressionEvaluationFile* li : ef) { // get all the files created by generator expressions and convert them // to ninja paths std::vector evaluationFiles = li->GetFiles(); for (std::string const& evaluationFile : evaluationFiles) { knownDependencies.insert(this->ConvertToNinjaPath(evaluationFile)); } } } knownDependencies.insert(this->CMakeCacheFile); for (auto const& ta : this->TargetAliases) { knownDependencies.insert(this->ConvertToNinjaPath(ta.first)); } // remove all source files we know will exist. for (auto const& i : this->AssumedSourceDependencies) { knownDependencies.insert(this->ConvertToNinjaPath(i.first)); } // now we difference with CombinedCustomCommandExplicitDependencies to find // the list of items we know nothing about. // We have encoded all the paths in CombinedCustomCommandExplicitDependencies // and knownDependencies so no matter if unix or windows paths they // should all match now. std::vector unknownExplicitDepends; this->CombinedCustomCommandExplicitDependencies.erase(this->TargetAll); std::set_difference(this->CombinedCustomCommandExplicitDependencies.begin(), this->CombinedCustomCommandExplicitDependencies.end(), knownDependencies.begin(), knownDependencies.end(), std::back_inserter(unknownExplicitDepends)); std::string const rootBuildDirectory = this->GetCMakeInstance()->GetHomeOutputDirectory(); bool const inSourceBuild = (rootBuildDirectory == this->GetCMakeInstance()->GetHomeDirectory()); std::vector warnExplicitDepends; for (std::string const& i : unknownExplicitDepends) { // verify the file is in the build directory std::string const absDepPath = cmSystemTools::CollapseFullPath(i, rootBuildDirectory.c_str()); bool const inBuildDir = cmSystemTools::IsSubDirectory(absDepPath, rootBuildDirectory); if (inBuildDir) { cmNinjaDeps deps(1, i); this->WritePhonyBuild(os, """", deps, cmNinjaDeps()); if (this->PolicyCMP0058 == cmPolicies::WARN && !inSourceBuild && warnExplicitDepends.size() < 10) { warnExplicitDepends.push_back(i); } } } if (!warnExplicitDepends.empty()) { std::ostringstream w; /* clang-format off */ w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0058) << ""\\n"" ""This project specifies custom command DEPENDS on files "" ""in the build tree that are not specified as the OUTPUT or "" ""BYPRODUCTS of any add_custom_command or add_custom_target:\\n"" "" "" << cmJoin(warnExplicitDepends, ""\\n "") << ""\\n"" ""For compatibility with versions of CMake that did not have "" ""the BYPRODUCTS option, CMake is generating phony rules for "" ""such files to convince 'ninja' to build."" ""\\n"" ""Project authors should add the missing BYPRODUCTS or OUTPUT "" ""options to the custom commands that produce these files."" ; /* clang-format on */ this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, w.str()); } } void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os) { // Write headers. cmGlobalNinjaGenerator::WriteDivider(os); os << ""# Built-in targets\\n\\n""; this->WriteTargetAll(os); this->WriteTargetRebuildManifest(os); this->WriteTargetClean(os); this->WriteTargetHelp(os); } void cmGlobalNinjaGenerator::WriteTargetAll(std::ostream& os) { cmNinjaDeps outputs; outputs.push_back(this->TargetAll); this->WritePhonyBuild(os, ""The main all target."", outputs, this->AllDependencies); if (!this->HasOutputPathPrefix()) { cmGlobalNinjaGenerator::WriteDefault(os, outputs, ""Make the all target the default.""); } } void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os) { cmLocalGenerator* lg = this->LocalGenerators[0]; std::ostringstream cmd; cmd << lg->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL) << "" -H"" << lg->ConvertToOutputFormat(lg->GetSourceDirectory(), cmOutputConverter::SHELL) << "" -B"" << lg->ConvertToOutputFormat(lg->GetBinaryDirectory(), cmOutputConverter::SHELL); WriteRule(*this->RulesFileStream, ""RERUN_CMAKE"", cmd.str(), ""Re-running CMake..."", ""Rule for re-running cmake."", /*depfile=*/"""", /*deptype=*/"""", /*rspfile=*/"""", /*rspcontent*/ """", /*restat=*/"""", /*generator=*/true); cmNinjaDeps implicitDeps; for (cmLocalGenerator* localGen : this->LocalGenerators) { std::vector const& lf = localGen->GetMakefile()->GetListFiles(); for (std::string const& fi : lf) { implicitDeps.push_back(this->ConvertToNinjaPath(fi)); } } implicitDeps.push_back(this->CMakeCacheFile); std::sort(implicitDeps.begin(), implicitDeps.end()); implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()), implicitDeps.end()); cmNinjaVars variables; // Use 'console' pool to get non buffered output of the CMake re-run call // Available since Ninja 1.5 if (SupportsConsolePool()) { variables[""pool""] = ""console""; } std::string const ninjaBuildFile = this->NinjaOutputPath(NINJA_BUILD_FILE); this->WriteBuild(os, ""Re-run CMake if any of its inputs changed."", ""RERUN_CMAKE"", /*outputs=*/cmNinjaDeps(1, ninjaBuildFile), /*implicitOuts=*/cmNinjaDeps(), /*explicitDeps=*/cmNinjaDeps(), implicitDeps, /*orderOnlyDeps=*/cmNinjaDeps(), variables); this->WritePhonyBuild(os, ""A missing CMake input file is not an error."", implicitDeps, cmNinjaDeps()); } std::string cmGlobalNinjaGenerator::ninjaCmd() const { cmLocalGenerator* lgen = this->LocalGenerators[0]; if (lgen) { return lgen->ConvertToOutputFormat(this->NinjaCommand, cmOutputConverter::SHELL); } return ""ninja""; } bool cmGlobalNinjaGenerator::SupportsConsolePool() const { return this->NinjaSupportsConsolePool; } bool cmGlobalNinjaGenerator::SupportsImplicitOuts() const { return this->NinjaSupportsImplicitOuts; } void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os) { WriteRule(*this->RulesFileStream, ""CLEAN"", ninjaCmd() + "" -t clean"", ""Cleaning all built files..."", ""Rule for cleaning all built files."", /*depfile=*/"""", /*deptype=*/"""", /*rspfile=*/"""", /*rspcontent*/ """", /*restat=*/"""", /*generator=*/false); WriteBuild(os, ""Clean all the built files."", ""CLEAN"", /*outputs=*/cmNinjaDeps(1, this->NinjaOutputPath(""clean"")), /*implicitOuts=*/cmNinjaDeps(), /*explicitDeps=*/cmNinjaDeps(), /*implicitDeps=*/cmNinjaDeps(), /*orderOnlyDeps=*/cmNinjaDeps(), /*variables=*/cmNinjaVars()); } void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os) { WriteRule(*this->RulesFileStream, ""HELP"", ninjaCmd() + "" -t targets"", ""All primary targets available:"", ""Rule for printing all primary targets available."", /*depfile=*/"""", /*deptype=*/"""", /*rspfile=*/"""", /*rspcontent*/ """", /*restat=*/"""", /*generator=*/false); WriteBuild(os, ""Print all primary targets available."", ""HELP"", /*outputs=*/cmNinjaDeps(1, this->NinjaOutputPath(""help"")), /*implicitOuts=*/cmNinjaDeps(), /*explicitDeps=*/cmNinjaDeps(), /*implicitDeps=*/cmNinjaDeps(), /*orderOnlyDeps=*/cmNinjaDeps(), /*variables=*/cmNinjaVars()); } void cmGlobalNinjaGenerator::InitOutputPathPrefix() { this->OutputPathPrefix = this->LocalGenerators[0]->GetMakefile()->GetSafeDefinition( ""CMAKE_NINJA_OUTPUT_PATH_PREFIX""); EnsureTrailingSlash(this->OutputPathPrefix); } std::string cmGlobalNinjaGenerator::NinjaOutputPath( std::string const& path) const { if (!this->HasOutputPathPrefix() || cmSystemTools::FileIsFullPath(path)) { return path; } return this->OutputPathPrefix + path; } void cmGlobalNinjaGenerator::StripNinjaOutputPathPrefixAsSuffix( std::string& path) { if (path.empty()) { return; } EnsureTrailingSlash(path); cmStripSuffixIfExists(path, this->OutputPathPrefix); } /* We use the following approach to support Fortran. Each target already has a .dir/ directory used to hold intermediate files for CMake. For each target, a FortranDependInfo.json file is generated by CMake with information about include directories, module directories, and the locations the per-target directories for target dependencies. Compilation of source files within a target is split into the following steps: 1. Preprocess all sources, scan preprocessed output for module dependencies. This step is done with independent build statements for each source, and can therefore be done in parallel. rule Fortran_PREPROCESS depfile = $DEP_FILE command = gfortran -cpp $DEFINES $INCLUDES $FLAGS -E $in -o $out && cmake -E cmake_ninja_depends \\ --tdi=FortranDependInfo.json --pp=$out --dep=$DEP_FILE \\ --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE build src.f90-pp.f90 | src.f90-pp.f90.ddi: Fortran_PREPROCESS src.f90 OBJ_FILE = src.f90.o DEP_FILE = src.f90-pp.f90.d DYNDEP_INTERMEDIATE_FILE = src.f90-pp.f90.ddi The ``cmake -E cmake_ninja_depends`` tool reads the preprocessed output and generates the ninja depfile for preprocessor dependencies. It also generates a ""ddi"" file (in a format private to CMake) that lists the object file that compilation will produce along with the module names it provides and/or requires. The ""ddi"" file is an implicit output because it should not appear in ""$out"" but is generated by the rule. 2. Consolidate the per-source module dependencies saved in the ""ddi"" files from all sources to produce a ninja ""dyndep"" file, ``Fortran.dd``. rule Fortran_DYNDEP command = cmake -E cmake_ninja_dyndep \\ --tdi=FortranDependInfo.json --dd=$out $in build Fortran.dd: Fortran_DYNDEP src1.f90-pp.f90.ddi src2.f90-pp.f90.ddi The ``cmake -E cmake_ninja_dyndep`` tool reads the ""ddi"" files from all sources in the target and the ``FortranModules.json`` files from targets on which the target depends. It computes dependency edges on compilations that require modules to those that provide the modules. This information is placed in the ``Fortran.dd`` file for ninja to load later. It also writes the expected location of modules provided by this target into ``FortranModules.json`` for use by dependent targets. 3. Compile all sources after loading dynamically discovered dependencies of the compilation build statements from their ``dyndep`` bindings. rule Fortran_COMPILE command = gfortran $INCLUDES $FLAGS -c $in -o $out build src1.f90.o: Fortran_COMPILE src1.f90-pp.f90 || Fortran.dd dyndep = Fortran.dd The ""dyndep"" binding tells ninja to load dynamically discovered dependency information from ``Fortran.dd``. This adds information such as: build src1.f90.o | mod1.mod: dyndep restat = 1 This tells ninja that ``mod1.mod`` is an implicit output of compiling the object file ``src1.f90.o``. The ``restat`` binding tells it that the timestamp of the output may not always change. Additionally: build src2.f90.o: dyndep | mod1.mod This tells ninja that ``mod1.mod`` is a dependency of compiling the object file ``src2.f90.o``. This ensures that ``src1.f90.o`` and ``mod1.mod`` will always be up to date before ``src2.f90.o`` is built (because the latter consumes the module). */ int cmcmd_cmake_ninja_depends(std::vector::const_iterator argBeg, std::vector::const_iterator argEnd) { std::string arg_tdi; std::string arg_pp; std::string arg_dep; std::string arg_obj; std::string arg_ddi; for (std::vector::const_iterator a = argBeg; a != argEnd; ++a) { std::string const& arg = *a; if (cmHasLiteralPrefix(arg, ""--tdi="")) { arg_tdi = arg.substr(6); } else if (cmHasLiteralPrefix(arg, ""--pp="")) { arg_pp = arg.substr(5); } else if (cmHasLiteralPrefix(arg, ""--dep="")) { arg_dep = arg.substr(6); } else if (cmHasLiteralPrefix(arg, ""--obj="")) { arg_obj = arg.substr(6); } else if (cmHasLiteralPrefix(arg, ""--ddi="")) { arg_ddi = arg.substr(6); } else { cmSystemTools::Error(""-E cmake_ninja_depends unknown argument: "", arg.c_str()); return 1; } } if (arg_tdi.empty()) { cmSystemTools::Error(""-E cmake_ninja_depends requires value for --tdi=""); return 1; } if (arg_pp.empty()) { cmSystemTools::Error(""-E cmake_ninja_depends requires value for --pp=""); return 1; } if (arg_dep.empty()) { cmSystemTools::Error(""-E cmake_ninja_depends requires value for --dep=""); return 1; } if (arg_obj.empty()) { cmSystemTools::Error(""-E cmake_ninja_depends requires value for --obj=""); return 1; } if (arg_ddi.empty()) { cmSystemTools::Error(""-E cmake_ninja_depends requires value for --ddi=""); return 1; } std::vector includes; { Json::Value tdio; Json::Value const& tdi = tdio; { cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (!reader.parse(tdif, tdio, false)) { cmSystemTools::Error(""-E cmake_ninja_depends failed to parse "", arg_tdi.c_str(), reader.getFormattedErrorMessages().c_str()); return 1; } } Json::Value const& tdi_include_dirs = tdi[""include-dirs""]; if (tdi_include_dirs.isArray()) { for (auto const& tdi_include_dir : tdi_include_dirs) { includes.push_back(tdi_include_dir.asString()); } } } cmFortranSourceInfo info; std::set defines; cmFortranParser parser(includes, defines, info); if (!cmFortranParser_FilePush(&parser, arg_pp.c_str())) { cmSystemTools::Error(""-E cmake_ninja_depends failed to open "", arg_pp.c_str()); return 1; } if (cmFortran_yyparse(parser.Scanner) != 0) { // Failed to parse the file. return 1; } { cmGeneratedFileStream depfile(arg_dep.c_str()); depfile << cmSystemTools::ConvertToUnixOutputPath(arg_pp) << "":""; for (std::string const& include : info.Includes) { depfile << "" \\\\\\n "" << cmSystemTools::ConvertToUnixOutputPath(include); } depfile << ""\\n""; } Json::Value ddi(Json::objectValue); ddi[""object""] = arg_obj; Json::Value& ddi_provides = ddi[""provides""] = Json::arrayValue; for (std::string const& provide : info.Provides) { ddi_provides.append(provide); } Json::Value& ddi_requires = ddi[""requires""] = Json::arrayValue; for (std::string const& r : info.Requires) { // Require modules not provided in the same source. if (!info.Provides.count(r)) { ddi_requires.append(r); } } cmGeneratedFileStream ddif(arg_ddi.c_str()); ddif << ddi; if (!ddif) { cmSystemTools::Error(""-E cmake_ninja_depends failed to write "", arg_ddi.c_str()); return 1; } return 0; } struct cmFortranObjectInfo { std::string Object; std::vector Provides; std::vector Requires; }; bool cmGlobalNinjaGenerator::WriteDyndepFile( std::string const& dir_top_src, std::string const& dir_top_bld, std::string const& dir_cur_src, std::string const& dir_cur_bld, std::string const& arg_dd, std::vector const& arg_ddis, std::string const& module_dir, std::vector const& linked_target_dirs) { // Setup path conversions. { cmStateSnapshot snapshot = this->GetCMakeInstance()->GetCurrentSnapshot(); snapshot.GetDirectory().SetCurrentSource(dir_cur_src); snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld); snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str()); snapshot.GetDirectory().SetRelativePathTopBinary(dir_top_bld.c_str()); auto mfd = cm::make_unique(this, snapshot); std::unique_ptr lgd( static_cast( this->CreateLocalGenerator(mfd.get()))); this->Makefiles.push_back(mfd.release()); this->LocalGenerators.push_back(lgd.release()); } std::vector objects; for (std::string const& arg_ddi : arg_ddis) { // Load the ddi file and compute the module file paths it provides. Json::Value ddio; Json::Value const& ddi = ddio; cmsys::ifstream ddif(arg_ddi.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (!reader.parse(ddif, ddio, false)) { cmSystemTools::Error(""-E cmake_ninja_dyndep failed to parse "", arg_ddi.c_str(), reader.getFormattedErrorMessages().c_str()); return false; } cmFortranObjectInfo info; info.Object = ddi[""object""].asString(); Json::Value const& ddi_provides = ddi[""provides""]; if (ddi_provides.isArray()) { for (auto const& ddi_provide : ddi_provides) { info.Provides.push_back(ddi_provide.asString()); } } Json::Value const& ddi_requires = ddi[""requires""]; if (ddi_requires.isArray()) { for (auto const& ddi_require : ddi_requires) { info.Requires.push_back(ddi_require.asString()); } } objects.push_back(info); } // Map from module name to module file path, if known. std::map mod_files; // Populate the module map with those provided by linked targets first. for (std::string const& linked_target_dir : linked_target_dirs) { std::string const ltmn = linked_target_dir + ""/FortranModules.json""; Json::Value ltm; cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (ltmf && !reader.parse(ltmf, ltm, false)) { cmSystemTools::Error(""-E cmake_ninja_dyndep failed to parse "", linked_target_dir.c_str(), reader.getFormattedErrorMessages().c_str()); return false; } if (ltm.isObject()) { for (Json::Value::iterator i = ltm.begin(); i != ltm.end(); ++i) { mod_files[i.key().asString()] = i->asString(); } } } // Extend the module map with those provided by this target. // We do this after loading the modules provided by linked targets // in case we have one of the same name that must be preferred. Json::Value tm = Json::objectValue; for (cmFortranObjectInfo const& object : objects) { for (std::string const& p : object.Provides) { std::string const mod = module_dir + p + "".mod""; mod_files[p] = mod; tm[p] = mod; } } cmGeneratedFileStream ddf(arg_dd.c_str()); ddf << ""ninja_dyndep_version = 1.0\\n""; for (cmFortranObjectInfo const& object : objects) { std::string const ddComment; std::string const ddRule = ""dyndep""; cmNinjaDeps ddOutputs; cmNinjaDeps ddImplicitOuts; cmNinjaDeps ddExplicitDeps; cmNinjaDeps ddImplicitDeps; cmNinjaDeps ddOrderOnlyDeps; cmNinjaVars ddVars; ddOutputs.push_back(object.Object); for (std::string const& p : object.Provides) { ddImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[p])); } for (std::string const& r : object.Requires) { std::map::iterator m = mod_files.find(r); if (m != mod_files.end()) { ddImplicitDeps.push_back(this->ConvertToNinjaPath(m->second)); } } if (!object.Provides.empty()) { ddVars[""restat""] = ""1""; } this->WriteBuild(ddf, ddComment, ddRule, ddOutputs, ddImplicitOuts, ddExplicitDeps, ddImplicitDeps, ddOrderOnlyDeps, ddVars); } // Store the map of modules provided by this target in a file for // use by dependents that reference this target in linked-target-dirs. std::string const target_mods_file = cmSystemTools::GetFilenamePath(arg_dd) + ""/FortranModules.json""; cmGeneratedFileStream tmf(target_mods_file.c_str()); tmf << tm; return true; } int cmcmd_cmake_ninja_dyndep(std::vector::const_iterator argBeg, std::vector::const_iterator argEnd) { std::vector arg_full = cmSystemTools::HandleResponseFile(argBeg, argEnd); std::string arg_dd; std::string arg_tdi; std::vector arg_ddis; for (std::string const& arg : arg_full) { if (cmHasLiteralPrefix(arg, ""--tdi="")) { arg_tdi = arg.substr(6); } else if (cmHasLiteralPrefix(arg, ""--dd="")) { arg_dd = arg.substr(5); } else if (!cmHasLiteralPrefix(arg, ""--"") && cmHasLiteralSuffix(arg, "".ddi"")) { arg_ddis.push_back(arg); } else { cmSystemTools::Error(""-E cmake_ninja_dyndep unknown argument: "", arg.c_str()); return 1; } } if (arg_tdi.empty()) { cmSystemTools::Error(""-E cmake_ninja_dyndep requires value for --tdi=""); return 1; } if (arg_dd.empty()) { cmSystemTools::Error(""-E cmake_ninja_dyndep requires value for --dd=""); return 1; } Json::Value tdio; Json::Value const& tdi = tdio; { cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary); Json::Reader reader; if (!reader.parse(tdif, tdio, false)) { cmSystemTools::Error(""-E cmake_ninja_dyndep failed to parse "", arg_tdi.c_str(), reader.getFormattedErrorMessages().c_str()); return 1; } } std::string const dir_cur_bld = tdi[""dir-cur-bld""].asString(); std::string const dir_cur_src = tdi[""dir-cur-src""].asString(); std::string const dir_top_bld = tdi[""dir-top-bld""].asString(); std::string const dir_top_src = tdi[""dir-top-src""].asString(); std::string module_dir = tdi[""module-dir""].asString(); if (!module_dir.empty()) { module_dir += ""/""; } std::vector linked_target_dirs; Json::Value const& tdi_linked_target_dirs = tdi[""linked-target-dirs""]; if (tdi_linked_target_dirs.isArray()) { for (auto const& tdi_linked_target_dir : tdi_linked_target_dirs) { linked_target_dirs.push_back(tdi_linked_target_dir.asString()); } } cmake cm(cmake::RoleInternal); cm.SetHomeDirectory(dir_top_src); cm.SetHomeOutputDirectory(dir_top_bld); std::unique_ptr ggd( static_cast(cm.CreateGlobalGenerator(""Ninja""))); if (!ggd.get() || !ggd->WriteDyndepFile(dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld, arg_dd, arg_ddis, module_dir, linked_target_dirs)) { return 1; } return 0; } ",16210,True,2742.5612396809083,median "= Asciidoctor PDF: A native PDF converter for AsciiDoc Dan Allen ; Sarah White // Settings: :experimental: :idprefix: :idseparator: - ifndef::env-github[:icons: font] ifdef::env-github,env-browser[] :toc: macro :toclevels: 1 endif::[] ifdef::env-github[] :status: :!toc-title: :caution-caption: :fire: :important-caption: :exclamation: :note-caption: :paperclip: :tip-caption: :bulb: :warning-caption: :warning: endif::[] // Aliases: :project-name: Asciidoctor PDF :project-handle: asciidoctor-pdf // Variables: :release-version: 1.5.0 // URIs: :url-asciidoctor: http://asciidoctor.org :url-gem: http://rubygems.org/gems/asciidoctor-pdf :url-project: https://github.com/asciidoctor/asciidoctor-pdf :url-project-repo: {url-project} :url-project-issues: {url-project-repo}/issues :url-project-list: http://discuss.asciidoctor.org :url-prawn: http://prawnpdf.org :url-prawn-gmagick: https://github.com/packetmonkey/prawn-gmagick :url-prawn-svg: https://github.com/mogest/prawn-svg :url-asciidoctor-mathematical: https://github.com/asciidoctor/asciidoctor-mathematical :url-rvm: http://rvm.io :url-graphicsmagick: http://www.graphicsmagick.org ifdef::status[] image:https://img.shields.io/travis/asciidoctor/asciidoctor-pdf/master.svg[Build Status (Travis CI),link=https://travis-ci.org/asciidoctor/asciidoctor-pdf] image:https://github.com/asciidoctor/asciidoctor-pdf/workflows/CI/badge.svg[Build Status (GitHub Actions),link=https://github.com/asciidoctor/asciidoctor-pdf/actions?query=workflow%3ACI] image:https://img.shields.io/gem/v/asciidoctor-pdf.svg[Latest Release, link={url-gem}] image:https://img.shields.io/badge/license-MIT-blue.svg[MIT License, link=#copyright] endif::[] Asciidoctor PDF is a native PDF converter for AsciiDoc. It bypasses the requirement to generate an intermediary format such as DocBook, Apache FO, or LaTeX. Instead, you can use this extension to convert your documents directly from AsciiDoc to PDF. Its aim is to take the pain out of creating PDF documents from AsciiDoc. toc::[] == Overview {project-name} is an Asciidoctor extension that converts an AsciiDoc document directly to a PDF document. The style and layout of the PDF is controlled by a dedicated theme file. To the degree possible, this converter supports all the features of AsciiDoc that are supported by the built-in converters. However, there are <> imposed by the PDF format and the PDF library this extension uses. Under the covers, {project-name} uses the Prawn gem and its extensions (e.g., prawn-svg and prawn-table) to generate the PDF document. {url-prawn}[Prawn] is a general purpose PDF generator for Ruby that features high-level APIs for common needs like setting up the page and inserting images and low-level APIs for positioning and rendering text and graphics. Prawn takes the pain out of creating (basic) PDF documents. Likewise, {project-name} takes the pain out of creating PDF documents _directly from AsciiDoc_. Skip ahead to <> to start putting {project-name} use. But don't miss the <> to get a preview of what's possible. == Highlights * Direct AsciiDoc to PDF conversion * <> * Custom (TTF) fonts * Full SVG support (thanks to https://github.com/mogest/prawn-svg[prawn-svg]) * PDF document outline (i.e., bookmarks) * Title page * Table of contents page(s) * Document metadata (title, authors, subject, keywords, etc.) * Configurable page size (e.g., A4, Letter, Legal, etc) * Internal cross reference links * Syntax highlighting with Rouge (preferred), Pygments, or CodeRay * Cover pages * Page background color or page background image with named scaling * Page numbering * Double-sided (aka prepress) printing mode (i.e., margins alternate on recto and verso pages) * Customizable running content (header and footer) * “Keep together” blocks (i.e., page breaks avoided in certain block content) * Orphaned section titles avoided * Autofit verbatim blocks (as permitted by base_font_size_min setting) * Table border settings honored * Font-based icons * Auto-generated index * Automatic hyphenation (when enabled) * Permissive line breaking for CJK languages * Compression / optimization of output file == Known Limitations * Footnotes are always rendered as endnotes (at end of chapter for books; at end of document for all other doctypes). * Table cells that exceed height of a single page will be truncated (see https://github.com/prawnpdf/prawn-table/issues/41[prawn-table#41]). * Inline images in table cells must fit within available column width or a Prawn::Errors::CannotFit error will be thrown (see https://github.com/asciidoctor/asciidoctor-pdf/issues/1608 for workarounds). * Columns cannot be assigned a 0% width (or a width less than the width of a single character); in the same vein, a column cannot be set to autowidth if width of all other columns meets or exceeds 100%; the result is that the converter with throw a Prawn::Errors::CannotFit error. * An inline image in a table cell will not force the column wider if the width of the image exceeds the width of the column; either reduce the image width using `pdfwidth` or increase the width of the column using `cols`; another solution is to convert the cell to an AsciiDoc table cell (see https://github.com/asciidoctor/asciidoctor-pdf/issues/830). * Must use development version of prawn-table for autowidth to work on table head row. * Must use development version of prawn for error to include font name when requested font style is missing. * Must use Ruby >= 2.4 for natural cross references to work with non-ASCII titles. * AsciiDoc table cell leaves padding below last block (due to lack of margin collapsing). * Prawn does not support double-wide box drawing glyphs correctly, so box drawings aren't aligned properly in verbatim blocks (see https://github.com/prawnpdf/prawn/issues/1002[prawn#1002]. * Orphan / widow support is limited; a page break can occur between a section title and its section content, a table caption and the caption, etc.; use a manual page break to avoid. * If a no-break hyphen is surrounded by formatted text on both sides (or is formatted individually), it will not prevent a line break. * Images cannot float. * Verse blocks do not use a fixed-width font by default, but you can control this setting using the theme. == Prerequisites All that's needed is Ruby 2.3 or better and a few Ruby gems (including at least Asciidoctor 2.0.0), which we explain how to install in the next section. To check if you have Ruby available, use the `ruby` command to query the version installed: $ ruby --version Make sure this command reports a Ruby version that's at least 2.3. If so, you may proceed. === System Encoding Asciidoctor assumes you're using UTF-8 encoding. To minimize encoding problems, make sure the default encoding of your system is set to UTF-8. If you're using a non-English Windows environment, the default encoding of your system may not be UTF-8. As a result, you may get an `Encoding::UndefinedConversionError` or other encoding issues when invoking Asciidoctor. To solve these problems, we recommend at least changing the active code page in your console to UTF-8. chcp 65001 Once you make this change, all your Unicode headaches will be behind you. == Getting Started You can get {project-name} by <>. ifndef::env-site[You can also <> if you want to use a development version or participate in development.] === Install the Published Gem To install {project-name}, first make sure you have satisfied the <>. Then, install the gem from RubyGems.org using the following command: $ gem install asciidoctor-pdf ==== Installation Troubleshooting If you get a permission error while installing the gem, such as the one below, it's likely you're attempting to install the gem directly into your system. Installing gems for tech writing directly into your system is not recommended. .Permission error when attempting to install as a system gem .... ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions for the /Library/Ruby/Gems/2.x.x directory. .... A better practice (and one that will ensure your sanity) is to ignore any version of Ruby installed on your system and use {url-rvm}[RVM] to manage the Ruby installation instead. The benefit of this approach is that a) Ruby is guaranteed to be set up correctly, b) installing gems will in no way interfere with the operation of your system, and c) any bin scripts provided by the installed gems will be available on your PATH. All files are managed in user space (aka your home or user directory). If something gets messed up, you can simply remove the [.path]_$HOME/.rvm_ folder and start over. To learn how to install RVM, follow the https://asciidoctor.org/docs/install-asciidoctor-macos/#rvm-procedure-recommended[RVM installation procedure] covered in the Asciidoctor documentation. Once you have installed RVM and used it to install Ruby, make sure to activate the Ruby managed by RVM using `rvm use default` or a specific Ruby version like `rvm use 2.6`. (You'll need to do this each time you open a new terminal). After installing the gem, you can see where it was installed using the following command: $ gem which asciidoctor-pdf To see where the bin script is located, use this command: $ command -v asciidoctor-pdf Both paths should be underneath the [.path]_$HOME/.rvm_ directory. If not, check your RVM setup. ==== Install a Syntax Highlighter (optional) If you want to syntax highlight source listings, you'll also want to install Rouge, Pygments, or CodeRay. Choose one (or more) of the following: .Rouge (preferred, minimum version: 2.0.0) $ gem install rouge .Pygments $ gem install pygments.rb .CodeRay $ gem install coderay You then activate syntax highlighting for a given document by adding the `source-highlighter` attribute to the document header (Rouge shown): [source,asciidoc] ---- :source-highlighter: rouge ---- ==== Upgrade Prawn and Extensions (optional) {project-name} uses Prawn to handle the PDF generation, which has a different release cycle. At times, there may are development features in Prawn and its extensions you need to use which haven't yet been released. No problem. You can still gain access to these features by installing the unreleased gems directly from GitHub. To get started, first create a [.path]_Gemfile_ in the root of your project. In that file, declare the gem soruce, the {project-handle} gem, and the prawn gem and/or one of its extension gems. In this example, we'll install both the prawn and prawn-table gems from GitHub. .Gemfile [source,ruby] ---- source 'https://rubygems.org' gem 'asciidoctor-pdf' gem 'prawn', github: 'prawnpdf/prawn' gem 'prawn-table', github: 'prawnpdf/prawn-table' ---- You can then install the gems into your project using the `bundle` command: $ bundle config set --local path .bundle/gems && bundle Since you're using Bundler to manage the gems, you'll need to prefix all commands with `bundle exec`. For example: $ bundle exec asciidoctor-pdf -v Thus, to any command present in the following sections, be sure to include this prefix. === Run the Application Assuming all the required gems install properly, verify you can run the `asciidoctor-pdf` script: $ asciidoctor-pdf -v If you see the version of {project-name} printed, you're ready to use {project-name}! Let's grab an AsciiDoc document to distill and start putting {project-name} to use. === An Example AsciiDoc Document If you don't already have an AsciiDoc document, you can use the <> file found in the examples directory of this project. ifeval::[{safe-mode-level} >= 20] See <>. endif::[] ifeval::[{safe-mode-level} < 20] .basic-example.adoc [source,asciidoc] .... include::examples/basic-example.adoc[] .... endif::[] It's time to convert the AsciiDoc document directly to PDF. === Convert AsciiDoc to PDF IMPORTANT: You'll need the `rouge` gem installed to run this example since it uses the `source-highlighter` attribute with the value of `rouge`. Converting to PDF is a simple as running the `asciidoctor-pdf` script using Ruby and passing our AsciiDoc document as the first argument. $ asciidoctor-pdf basic-example.adoc This command is just a shorthand way of running: $ asciidoctor -r asciidoctor-pdf -b pdf basic-example.adoc The `asciidoctor-pdf` command just saves you from having to remember all those flags. That's why we created it. When the script completes, you should see the file [.path]_basic-example.pdf_ in the same directory. Open the [.path]_basic-example.pdf_ file with a PDF viewer to see the result. .Example PDF document rendered in a PDF viewer image::examples/example-pdf-screenshot.png[Screenshot of PDF document,width=850,467,scaledwidth=100%] ifndef::env-site[] You're also encouraged to try converting this <> as well as the documents in the examples directory to see more of what {project-name} can do. endif::[] The pain of the DocBook toolchain should be melting away about now. == Themes The layout and styling of the PDF is driven by a YAML configuration file. To learn how the theming system works and how to create and apply custom themes, refer to the <>. You can use the built-in theme files, which you can find in the [.path]_data/themes_ directory, as examples. If you've enabled a source highlighter, you can control the style (aka theme) it applies to source blocks using the `coderay-style`, `pygments-style`, and `rouge-style` attributes, respectively. For example, to configure Rouge to use the built-in monokai theme, run Asciidoctor PDF as follows: $ asciidoctor-pdf -a rouge-style=monokai basic-example.adoc It's possible to develop your own theme for Rouge. Refer to the <> for details. == Support for Non-Latin Languages Asciidoctor can process the full range of characters in the UTF-8 character set. That means you can write your document in any language, save the file with UTF-8 encoding (_that's important!_), and expect Asciidoctor to convert the text properly. But you still need a font that provides the glyphs for those characters. When converting a document with Asciidoctor PDF, you may notice that some of the glyphs for certain languages, such as Chinese, are missing from the PDF. PDF is a ""`bring your own font`"" kind of system. In other words, the font you provide must provide glyphs for all the characters used. There's no one font that supports all the world's languages (though some, like Noto Serif, certainly come close). Even if there were such a font, bundling that font with the main gem would make it enormous. It would also severely limit the style choices in the default theme, which targets Latin-based languages. Therefore, we're taking the strategy of creating separate dedicated theme gems that target each language family, such as CJK. Read on to find out how to use these themes. Asciidoctor PDF provides a built-in theme that provides a broad range of characters in the CJK charsets, so you can start with that theme: $ asciidoctor-pdf -a scripts=cjk -a pdf-theme=default-with-fallback-font document.adoc Notice the `-a scripts=cjk` option. That's important. It tells the converter to insert break opportunities between CJK characters so that the line wraps properly when mixing English and a CJK language like Japanese. If the built-in theme with the fallback font doesn't go far enough, you'll need to use a theme that is optimized for CJK text. You can get such a theme by installing the `asciidoctor-pdf-cjk-kai_gen_gothic` gem. The https://github.com/chloerei/asciidoctor-pdf-cjk-kai_gen_gothic[asciidoctor-pdf-cjk-kai_gen_gothic] project provides themes optimized for CJK languages based on the kai_gen_gothic font. See the https://github.com/chloerei/asciidoctor-pdf-cjk-kai_gen_gothic[asciidoctor-pdf-cjk-kai_gen_gothic] project README for detailed setup instructions. Once you have that gem installed (and the fonts), you need to tell Asciidoctor PDF to use one of the themes. If you're converting a document that is primarily written in Japanese, you'd run Asciidoctor PDF as follows: asciidoctor-pdf -r asciidoctor-pdf-cjk-kai_gen_gothic -a pdf-theme=KaiGenGothicJP document.adoc You also have to option of creating your own theme gem that uses fonts of your choice. For example, if you want to use the `asciidoctor-pdf-cjk-kai_gen_gothic` gem to fetch fonts, but then use them in your own theme, here's how you'd do it. . Install the `asciidoctor-pdf-cjk-kai_gen_gothic` gem: $ gem install asciidoctor-pdf-cjk-kai_gen_gothic . Download / install the fonts: $ asciidoctor-pdf-cjk-kai_gen_gothic-install . Create a theme that extends the default theme: + [source,yml] ---- extends: default font: catalog: KaiGen Gothic JP: normal: KaiGenGothicJP-Regular.ttf bold: KaiGenGothicJP-Bold.ttf italic: KaiGenGothicJP-Regular-Italic.ttf bold_italic: KaiGenGothicJP-Bold-Italic.ttf M+ 1mn: normal: GEM_FONTS_DIR/mplus1mn-regular-subset.ttf bold: GEM_FONTS_DIR/mplus1mn-bold-subset.ttf italic: GEM_FONTS_DIR/mplus1mn-italic-subset.ttf bold_italic: GEM_FONTS_DIR/mplus1mn-bold_italic-subset.ttf fallbacks: - KaiGen Gothic JP base: font-family: KaiGen Gothic JP heading: font-family: $base-font-family abstract: title: font-family: $heading-font-family sidebar: title: font-family: $heading-font-family ---- . Load your theme when running Asciidoctor PDF: $ asciidoctor-pdf -a scripts=cjk -a pdf-theme=./jp-theme.yml -a pdf-fontsdir=`ruby -r asciidoctor-pdf-cjk-kai_gen_gothic -e ""print File.expand_path '../fonts', (Gem.datadir 'asciidoctor-pdf-cjk-kai_gen_gothic')""` document.adoc The `-a pdf-fontsdir` option is important to tell Asciidoctor PDF where to find your custom fonts. Rather than using the installer from the `asciidoctor-pdf-cjk-kai_gen_gothic` gem, you can download fonts whatever way you choose. When using your own fonts, be sure to consult the <> section of the theming guide to find recommended modifications. == Font-Based Icons You can use icons in your PDF document using any of the following icon sets: * *fa* - https://fontawesome.com/v4.7.0/icons (default) * *fas* - https://fontawesome.com/icons?d=gallery&s=solid[Font Awesome - Solid^] * *fab* - https://fontawesome.com/icons?d=gallery&s=brands[Font Awesome - Brands^] * *far* - https://fontawesome.com/icons?d=gallery&s=regular[Font Awesome - Regular^] * *fi* - http://zurb.com/playground/foundation-icon-fonts-3[Foundation Icons^] * *pf* - https://paymentfont.com/[Payment font^] The fa icon set is deprecated. Please use one of the other three FontAwesome icon sets. You can enable font-based icons by setting the following attribute in the header of your document: [source,asciidoc] ---- :icons: font ---- If you want to override the font set globally, also set the `icon-set` attribute: [source,asciidoc] ---- :icons: font :icon-set: pf ---- Here's an example that shows how to use the Amazon icon from the payment font (pf) icon set in a sentence (assuming the `icon-set` is set to `pf): [source,asciidoc] ---- Available now at icon:amazon[]. ---- You can use the `set` attribute on the icon macro to override the icon set for a given icon. [source,asciidoc] ---- Available now at icon:amazon[set=pf]. ---- You can also specify the font set using the following shorthand. [source,asciidoc] ---- Available now at icon:amazon@pf[]. ---- In addition to the sizes supported in the HTML backend (lg, 1x, 2x, etc), you can enter any relative value in the size attribute (e.g., 1.5em, 150%, etc). [source,asciidoc] ---- icon:android[size=40em] ---- You can enable use of fonts during PDF generation (instead of in the document header) by passing the `icons` attribute to the `asciidoctor-pdf` command. $ asciidoctor-pdf -a icons=font -a icon-set=pf sample.adoc Icon-based fonts are handled by the `prawn-icon` gem. To find a complete list of available icons, consult the https://github.com/jessedoyle/prawn-icon/tree/master/data/fonts[prawn-icon] repository. == Image Paths Images are resolved at the time the converter runs. That means they need to be located where the converter can find them. Relative images paths in the document are resolved relative to the value of the `imagesdir` attribute. This is effectively the same as how the built-in HTML converter works when the `data-uri` attribute is set. The `imagesdir` is blank by default, which means relative images paths are resolved relative to the input document. Relative images paths in the theme are resolved relative to the value of the `pdf-themesdir` attribute (which defaults to the directory of the theme file). The `imagesdir` attribute is not used when resolving an image path in the theme file. Absolute image paths are used as is. If the image is an SVG, and the SVG includes a nested raster image (PNG or JPG) with a relative path, that path is resolved relative to the directory that contains the SVG. The converter will refuse to embed an image if the target is a URI (including image references in an SVG) unless the `allow-uri-read` attribute is enabled via the CLI or API. If you use a linked image in an SVG, the width and height of that image must be specified. Otherwise, the SVG library will fail to process it. === Asciidoctor Diagram Integration As of Asciidoctor PDF 1.5.0.alpha.17 running on Asciidoctor 2 or better, Asciidoctor PDF provides better integration with Asciidoctor Diagram by setting the `data-uri` attribute by default. When the `data-uri` attribute is set, Asciidoctor Diagram returns the absolute path to the generated image, which Asciidoctor PDF can then locate. (This makes sense since technically, Asciidoctor Diagram must embed the image in the document, similar in spirit to the `data-uri` feature for HTML). This means the input directory and the output directory (and thus the imagesoutdir) can differ and Asciidoctor PDF will still be able to locate the generate image. Prior to Asciidoctor PDF 1.5.0.alpha.17 (or prior to Asciidoctor 2), the way to solve this problem is to set the `imagesdir` attribute to an absolute path. That way, it won't matter where the generated image is written. Asciidoctor PDF will still be able to find it. Keep in mind that this strategy may introduce other side effects you'll have to work around. == Image Scaling Since PDF is a fixed-width canvas, you almost always need to specify a width to get the image to fit properly on the page. There are five ways to specify the width of an image, listed here in order of precedence: [cols=""1s,3""] |=== |Attribute{nbsp}Name | Description |pdfwidth |The display width of the image as an absolute size (e.g., 2in), percentage of the content area width (e.g., 75%), or percentage of the page width (e.g., 100vw). If a unit of measurement is not specified (or not recognized), pt (points) is assumed. _Intended to be used for the PDF converter only._ |scaledwidth |The display width of the image as an absolute size (e.g., 2in) or percentage of the content area width (e.g., 75%). If a unit of measurement is not specified, % (percentage) is assumed. If a unit of measurement is recognized, pt (points) is assumed. _Intended to be used for print output such as PDF._ |image_width key from theme |Accepts the same values as pdfwidth. _Only applies to block images._ |width |The unitless display width of the image (assumed to be pixels), typically matching the intrinsic width of the image. If the value ends in % (not recommended), it's assumed to be the percentage of the available content area width. If the width exceeds the content area width, the image is scaled down to the content area width. |_unspecified_ |If you don't specify one of the aforementioned width settings, the intrinsic width of the image is used (the px value is multiplied by 75% to convert to pt, assuming canvas is 96 dpi) unless the width exceeds the content area width, in which case the image is scaled down to the content area width. |=== The image is always sized according to the explicit or intrinsic width, then its height is scaled proportionally. The height of the image is ignored by the PDF converter unless the height of the image exceeds the content height of the page. In this case, the image is scaled down to fit on a single page. If you want a block image to align to the boundaries of the page (not the content margin), specify the `align-to-page` option (e.g., `opts=""align-to-page""`). This is most useful when using vw units because you can make the image cover the entire width of the page. Images in running content and page background images also support the `fit` attribute (when specified using the image macro). See <> for details. === Using the pdfwidth Attribute The pdfwidth attribute is the recommended way to set the image size for the PDF output. This attribute is provided for two reasons. First, the fixed-width canvas often calls for a width that is distinct from other output formats, such as HTML. Second, this attribute allows the width to be expressed using a variety of units. The pdfwidth attribute supports the following units: * pt (default) * in * cm * mm * px * pc * vw (percentage of page width) * % (percentage of content area width) In all cases, the width is converted to pt. === Specifying a default width If you want to scale all block images that don't have a pdfwidth or scaledwidth attribute specified, assign a value to the image_width key in your theme. [source,yaml] ---- image: width: 100% ---- === Inline Image Sizing Inline images can be sized in much the same way as block images (using the pdfwidth, scaledwidth or width attributes), with the following exceptions: * The viewport width unit (i.e., vw) is not recognized in this context. * The image will be scaled down, if necessary, to fit the width and height of the content area. * Inline images do not currently support a default width controlled from the theme. To confine the inline image to the height of the line while preserving the aspect ratio, use the attribute `fit=line`. If the resolved height of the image is less than or equal to 1.5 times the line height, the image won't disrupt the line height and is centered vertically in the line. This is done to maximize the use of available space. Once the resolved height exceeds this amount, the height of the line is increased (by increasing the font size of the invisible placeholder text) to accommodate the image. In this case, the surrounding text will be aligned to the bottom of the image. If the image height exceeds the height of the page, the image will be scaled down to fit on a single page (this may cause the image to advance to the subsequent page). === Background Image Sizing In addition to the width-related attributes previously covered, cover and background images can be sized relative to the page using the `fit` attribute of the image macro. The `fit` attribute works similarly to the `object-fit` property in CSS. It's value must be specified as a single keyword, chosen from the table below. The starting size of the image is determined by the explicit width, if specified, or the implicit width. The height is always derived from the width while respecting the implicit aspect ratio of the image. The available space for a background image (i.e., the canvas) is the page. If the `fit` attribute is not specified, it defaults to `contain` (i.e., the image is automatically scaled to fit the bounds of the page). [cols=""1s,3""] |=== | Value | Purpose | contain | The image is scaled up or down while retaining its aspect ratio to fit within the available space. (default) | cover | The image is scaled up or down while retaining its aspect ratio so the image completely covers the available space, even if it means the image must be clipped in one direction. | scale-down | The image is scaled down while retaining its aspect ratio to fit within the available space. If the image already fits, it is not scaled. | fill | The image is scaled to fit the available space even if it means modifying the aspect ratio of the image. Does not apply to SVG images. | none | The image is not scaled. |=== The `fit` attribute is often combined with the `position` attribute, covered next, to control the placement of the image on the canvas. == Background Image Positioning In addition to scaling, background images for cover pages, content pages, and the title page support positioning via the `position` attribute. The `position` attribute accepts a syntax similar to the `background-position` property in CSS, except only the keyword positions are supported. The position consists of two values, the vertical position and the horizontal position (e.g., `top center`). If only one value is specified (e.g., `top`), the other value is assumed to be `center`. If the `position` attribute is not specified, the value is assumed to be `center center` (i.e., the image is centered on the page). The following table provides a list of the vertical and horizontal positioning keywords that are supported. You can use any combination of these keywords to position the image. |=== | Vertical Positions | Horizontal Positions | top + center + bottom | left + center + right |=== Here's an example of how to place a background image at the top center of every page: ---- :page-background-image: image:bg.png[fit=none,pdfwidth=50%,position=top] ---- Here's how to move it to the bottom right: ---- :page-background-image: image:bg.png[fit=none,pdfwidth=50%,position=bottom right] ---- If an image dimension matches the height or width of the page, the positioning keyword for that axis has no effect. == Fonts in SVG Images Asciidoctor PDF uses {url-prawn-svg}[prawn-svg] to embed SVGs in the PDF document, including SVGs generated by Asciidoctor Diagram. Actually, it's not accurate to say that prawn-svg embeds the SVG. Rather, prawn-svg is an SVG _renderer_. prawn-svg translates an SVG into native PDF text and graphic objects. You can think of the SVG as a sequence of drawing commands. The result becomes indistinguishable from other PDF objects. What that means for text is that any font family used for text in the SVG _must_ be registered in the Asciidoctor PDF theme file (and thus with Prawn). Otherwise, Prawn will fallback to using the closest matching built-in (afm) font from PDF (e.g., sans-serif becomes Helvetica). Recall that afm fonts only support basic Latin. As we like to say, PDF is <>. If you're using Asciidoctor Diagram to generate SVGs to embed in the PDF, you likely need to specify the default font the diagramming tool uses. Let's assume you are making a plantuml diagram. To set the font used in the diagram, first create a file named [.path]_plantuml.cfg_ and populate it with the following content: ---- skinparam defaultFontName Noto Serif ---- TIP: You can choose any font name that is registered in your Asciidoctor PDF theme file. When using the default theme, your options are ""Noto Serif"", ""M+ 1mn"", and ""M+ 1p Fallback"". Next, pass that path to the `plantumlconfig` attribute in your AsciiDoc document (or set the attribute via the CLI or API): ---- :plantumlconfig: plantuml.cfg ---- Clear the cache of your diagrams and run Asciidoctor PDF with Asciidoctor Diagram enabled. The diagrams will be generated using Noto Serif as the default font, and Asciidoctor PDF will know what to do. The bottom line is this: If you're using fonts in your SVG, and you want those fonts to be preserved, those fonts must be defined in the Asciidoctor PDF theme file. == Supporting Additional Image File Formats In order to embed an image into a PDF, Asciidoctor PDF must understand how to read it. To perform this work, Asciidoctor delegates to the underlying libraries. {url-prawn}[Prawn] provides support for reading JPG and PNG images. {url-prawn-svg}[prawn-svg] brings support for SVG images. Without any additional libraries, those are the only supported image file formats. If you need support for additional image formats, such as GIF, TIFF, or interlaced PNG--and you don't want to convert those images to a supported format--you must install the {url-prawn-gmagick}[prawn-gmagick] (>= 0.0.9) Ruby gem. prawn-gmagick is an extension for Prawn based on {url-graphicsmagick}[GraphicsMagick] that adds support for all the image formats recognized by that library. prawn-gmagick has the added benefit of significantly reducing the time it takes to generate a PDF containing a lot of images. The prawn-gmagick gem uses native extensions to compile against GraphicsMagick. This system prerequisite limits installation to Linux and OSX. Please refer to the {url-prawn-gmagick}[README for prawn-gmagick] to learn how to install it. Once this gem is installed, Asciidoctor automatically loads it, then delegates to it to handle all image embedding. In addition to support for additional image file formats, this gem also speeds up image processing considerably. We highly recommend using this gem if you're able to install it. == Importing PDF Pages In addition to using a PDF page for the front or back cover, you can also insert a PDF page at an arbitrary location. This technique is useful to include pages that have complex layouts and graphics prepared in a specialized design program (such as Inkscape), which would otherwise not be achievable using this converter. One such example is an insert such as an advertisement or visual interlude. To import the first page from a PDF file, use the block image macro with the PDF filename as the image target. [source,asciidoc] ---- image::custom-page.pdf[] ---- The converter will insert the page from the PDF as a dedicated page that matches the size and layout of the page being imported (no matter where the block image occurs). Therefore, there's no need to put a manual page break (i.e., `<<<`) around the image macro. By default, this macro will import the first page of the PDF. To import a different page, specify it as a 1-based index using the `page` attribute. [source,asciidoc] ---- image::custom-pages.pdf[page=2] ---- You can import multiple pages either using multiple image macros or using the `pages` attribute. The `pages` attribute accepts individual page numbers or page number ranges (two page numbers separated by `..`). The values can be separated either by commas or semi-colons. (The syntax is similar to the syntax uses for the `lines` attribute of the AsciiDoc include directive). [source,asciidoc] ---- image::custom-pages.pdf[pages=3;1..2] ---- Pages are imported in the order listed. To see a practical example of how to use this feature, refer to the blog post https://fromplantoprototype.com/blog/2019/08/07/importing-pdf-pages-in-asciidoctor-pdf/[Importing PDF Pages in asciidoctor-pdf]. CAUTION: An image macro used to imports PDF pages should never be nested inside a delimited block or table cell. It should be a direct descendant of the document or a section. That's because what it imports are entire pages. If it's used inside a delimited block or table cell, the behavior is unspecified. == Crafting Interdocument Xrefs This converter produces a single PDF file, which means content from multiple source documents get colocated into the same output file. That means references between documents must necessarily become internal references. These interdocument cross references (i.e., xrefs) will only successfully make that transition if you structure your document in accordance with the rules. Those rules are as follows: . The path segment of the interdocument xref must match the project-relative path of the included document . The reference must include the ID of the target element For instance, if your primary document contains the following include: [source,asciidoc] ---- \\include::chapters/chapter-1.adoc[] ---- Then an interdocument xref to an anchor in that chapter must be expressed as: [source,asciidoc] ---- <> ---- This rule holds regardless of which document the xref is located in. To resolve the interdocument xref, the converter first checks if the target matches the `docname` attribute. It then looks to see if the target matches one of the included files. (In both cases, it ignores the file extension). If Asciidoctor cannot resolve the target of an interdocument xref, it simply makes a link (like the HTML converter). Let's consider a complete example. Assume you are converting the following book document at the root of the project: [source,asciidoc] ---- = Book Title :doctype: book \\include::chapters/chapter-1.adoc[] \\include::chapters/chapter-2.adoc[] ---- Where the contents of chapter 1 is as follows: [source,asciidoc] ---- == Chapter 1 We cover a little bit here. The rest you can find in <>. ---- And the contents of chapter 2 is as follows: [source,asciidoc] ---- == Chapter 2 Prepare to be educated. This chapter has it all! To begin, jump to <>. <<< \\include::chapter-2/first-steps.adoc[] ---- And, finally, the contents of the nested include is as follows: [source,asciidoc] ---- === First Steps Let's start small. ---- You'll find when you run this example that all the interdocument xrefs become internal references in the PDF. The reason both the path and anchor are required (even when linking to the top of a chapter) is so the interdocument xref works independent of the converter. In other words, it encodes the complete information about the reference so the converter can sort out where the target is in all circumstances. == STEM Support Unlike the built-in HTML converter, Asciidoctor PDF does not provide native support for STEM blocks and inline macros (i.e., asciimath and latexmath). That's because Asciidoctor core doesn't process the STEM content itself. It just passes it through to the converter. In the HTML output, Asciidoctor relies on the JavaScript-based MathJax library to parse and render the equations in the browser when the page is loaded. The HTML converter simply wraps the equations in special markup so MathJax can find them. In order to insert a rendered equation into the PDF, the toolchain has to parse the equations and convert them to a format the PDF writer (Prawn) can understand. That typically means converting to an image. The recommended solution is an extension named Asciidoctor Mathematical, which we'll cover in this document. Another solution, which is still under development, uses Mathoid to convert STEM equations to images. Mathoid is a library that invokes MathJax using a headless browser, so it supports both asciimath and latexmath equations. That prototype can be found in the https://github.com/asciidoctor/asciidoctor-extensions-lab#extension-catalog[Asciidoctor extensions lab]. === Asciidoctor Mathematical {url-asciidoctor-mathematical}[Asciidoctor Mathematical] is an extension for Asciidoctor that provides alternate processing of STEM blocks and inline macros (currently only latexmath). After the document has been parsed, the extension locates all the latexmath blocks and inline macros, converts the equations to images using Mathematical, then replaces them with image nodes. Conversion then proceeds as normal. Asciidoctor Mathematical is a Ruby gem that uses native extensions. It has a few system prerequisites which limit installation to Linux and OSX. Please refer to the {url-asciidoctor-mathematical}#installation[installation section] in the Asciidoctor Mathematical README to learn how to install it. Once Asciidoctor Mathematical is installed, you just need to enable it when invoking Asciidoctor PDF using the `-r` flag: $ asciidoctor-pdf -r asciidoctor-mathematical sample.adoc If you're invoking Asciidoctor via the API, all you need to do is require the gem before invoking Asciidoctor: [source,ruby] ---- require 'asciidoctor-mathematical' Asciidoctor.convert_file 'sample.adoc', safe: :safe ---- To get the best quality equations, and the maximize speed of conversion, we recommend configuring Asciidoctor Mathematical to convert equations to SVG. You control this setting using the `mathematical-format` AsciiDoc attribute: $ asciidoctor-pdf -r asciidoctor-mathematical -a mathematical-format=svg sample.adoc Refer to the {url-asciidoctor-mathematical}#readme[README] for Asciidoctor Mathematical to learn about additional settings and options. == Skipping Passthrough Content Asciidoctor PDF does not support arbitrary passthrough content. While the basebackend for the PDF converter is html, it only recognizes a limited subset of inline HTML elements that can be mapped to PDF (e.g., a, strong, em, code, ). Therefore, if your content contains passthrough blocks or inlines, you most likely have to use a conditional preprocessor to skip them (and make other arrangements). Here's an example of how to skip a passthrough block when converting to PDF: [source,asciidoc] ---- \\ifndef::backend-pdf[] \\endif::[] ---- Here's an example of how to only enable a passthrough block when convertering to HTML5: [source,asciidoc] ---- \\ifdef::backend-html5[] \\endif::[] ---- == Shaded Blocks and Performance Certain blocks are rendered with a shaded background, such as verbatim (listing, literal, and source), sidebar, and example blocks. In order to calculate the dimensions of the shaded region, Asciidoctor PDF has to ""`dry run`"" the block to determine how many pages it consumes. While this strategy has a low impact when processing shorter blocks, it can drastically deteriorate performance when processing a block that spans dozens of pages. As a general rule of thumb, you should avoid using shaded blocks which span more than a handful of pages. == Autofitting Text Verbatim blocks often have long lines that don't fit within the fixed width of the PDF canvas. And unlike on the web, the PDF reader cannot scroll horizontally to reveal the overflow text. Therefore, the long lines are forced to wrap. Wrapped lines can make the verbatim blocks hard to read or even cause confusion. To help address this problem, Asciidoctor PDF provides the `autofit` option on all verbatim (i.e., literal, listing and source) blocks to attempt to fit the text within the available width. When the `autofit` option is enabled, Asciidoctor PDF will decrease the font size (as much as it can) until the longest line fits without wrapping. CAUTION: The converter will not shrink the font size beyond the value of the `base_font_size_min` key specified in the PDF theme. If that threshold is reached, lines may still wrap. To allow `autofit` to handle all cases, set `base_font_size_min` to `0` in your theme. Here's an example of the autofit option enabled on a source block: [source,asciidoc] .... [source%autofit,java] ---- @SessionScoped public class WidgetRepository { @GET @Produces(""application/json"") public List listAll(@QueryParam(""start"") Integer start, @QueryParam(""max"") Integer max) { ... } } ---- .... If you want to enable the autofit option globally, set the `autofit-option` document attribute in the document header (or somewhere before the relevant blocks): [source,asciidoc] ---- :autofit-option: ---- == Autowidth Tables Asciidoctor PDF does support autowidth tables. However, the behavior differs from HTML when the content forces the table to the page boundary. The behavior, which is handled by the prawn-table library, is explained in this section. If the natural width of all columns (based on the width of the cell content) is less than the width of the page, it behaves as you'd expect. Each column is assigned the width it needs to prevent the content from wrapping. However, when the natural width of all columns exceeds the width of the page, the behavior may not be what you expect. What prawn-table does is compute how to arrange the table on an infinite canvas, where each column can have a width no greater than the width of the page. Then, it reduces the width of the table by reducing the width of each column proportionally. As a result, columns which reported the width necessary to render without wrapping now no longer do. The reason this compression is not performed like in HTML is because prawn-table has no awareness of words. Thus, it doesn't know how to redistribute with width intelligently. To protected against truncation or insufficient width errors, prawn-table wraps text by character. That's why the last character in the cell can end up getting wrapped. (There's a small amount of tolerance built in to prawn-table to address some edge cases, but it's not sufficient to handle all of them). For the reason just explained, you should be extremely careful with relying on autowidth tables in Asciidoctor PDF, especially when the natural content of the cells forces the table to page boundary. Let experience be your guide. == Printing Page Ranges The print dialog doesn't understand the page numbers labels (which appear in the running content). Instead, it only considers physical pages. Therefore, to print a range of pages as they are labeled in the document, you need to add the number of front matter pages (i.e., the non-numbered pages) to the page number range in the print dialog. For example, if you only want to print the first 5 pages labeled with a page number (e.g., 1-5), and there are 2 pages before the page labeled as page 1, you need to add 2 to both numbers in the range, giving you a physical page range of 3-7. That's the range you need to enter into the print dialog. == Title Page Unlike other converters, the PDF converter introduces a dedicated title page at the start of the document. The title page contains the doctitle, author, date, and revision info. If a front cover image is specified, the title page comes after the front cover. The title page can be styled using the theme and/or reserved page attributes. The title page is enabled if either of these conditions are met: * The document has the `book` doctype. * The `title-page` attribute is set (with an empty value) in the document header. When the title page is enabled, the table of contents (aka TOC) also gets is own page (or pages, if necessary). == Table of Contents The table of contents (TOC) is not included by default. The TOC is only included if the `toc` attribute is set on the document. The placement of the table of contents is fixed, and thus the value of the `toc` attribute is effectively ignored in this backend. For documents that have the book doctype, the TOC is inserted using discrete pages between the title page and the first page of content. For all other doctypes (unless the `title-page` attribute is set), the TOC is inserted in the flow of text in between the document title and the first block of content. While the table of contents is not included by default, the PDF outline is always included. The `toclevels` attribute controls the depth of both the TOC and the PDF outline (regardless of whether the TOC is enabled). NOTE: If a document that has the book doctype includes a preface, an entry for the preface is only included in the TOC if the `preface-title` is assigned a value (e.g., `preface-title=Preface`). This value is used as the heading of the preface and as the text of the entry in the TOC. == Index Catalog Asciidoctor PDF supports generating an index catalog that itemizes all index terms defined in the document, allowing the reader to navigate the document by keyword. To get Asciidoctor PDF to generate an index, simply add an level-1 section flagged with the `index` style near the end of your document. The converter will automatically populate the catalog with the list of index terms in the document, organized by first letter. [source,asciidoc] ---- [index] = Index ---- You can use any text you want for the title of the section. The only restriction is that no index terms may be defined below this section. NOTE: Although the catalog is generated automatically, you have to mark the index terms manually. However, you could use an extension, such as a TreeProcessor, to automatically mark index terms. == Optimizing the Generated PDF By default, Asciidoctor PDF does not optimize the output document or even compress the streams. The simplest way to reduce the size of the file is to enable stream compression (using the FlateDecode method). You can enable this feature by setting the `compress` attribute on the document: $ asciidoctor-pdf -a compress document.adoc For more thorough optimzation, you can use either the built-in `asciidoctor-pdf-optimize` script or hexapdf. Read on to learn how. === asciidoctor-pdf-optimize {project-name} also provides a bin script that uses GhostScript to optimize and compress the generated PDF (with minimal impact on quality). You must have Ghostscript (command: `gs`) and the `rghost` gem installed to use it. Here's an example usage: $ asciidoctor-pdf-optimize basic-example.pdf The command will overwrite the PDF file with an optimized version. If a file is found with the extension `.pdfmark` and the same rootname as the input file, it is used to add metadata to the generated PDF document. This file is necessary to preserve the document metadata since Ghostscript will otherwise drop it. That's why {project-name} always creates this file in addition to the PDF. IMPORTANT: The `asciidoctor-pdf-optimize` is not guaranteed to reduce the size of the PDF file. It may actually make the PDF larger. You should probably only consider using it if the file size of the original PDF is several megabytes. You can also try reducing the quality of the output file using the `--quality` flag (e.g., `--quality screen`). The `--quality` flag accepts the following keywords: `default` (default), `screen`, `ebook`, `printer`, and `prepress`. === hexapdf Another option to optimize the PDF is https://hexapdf.gettalong.org/[hexapdf] (gem: hexapdf, command: hexapdf). Before introducing it, though, it's important to point out that its license is AGPL. If that's okay with you, read on to learn how to use it. First, install the hexapdf gem using the following command: $ gem install hexapdf You can then use it to optimize your PDF as follows: $ hexapdf optimize --compress-pages --force basic-example.pdf basic-example-optimized.pdf This command does not manipulate the images in any way. It merely compresses the objects in the PDF and prunes any unreachable references. But given how much waste Prawn leaves behind, this turns out to reduce the file size significantly. To see more options, run: $ hexapdf help optimize For example, to make the source of the PDF a bit more readable, set the stream-related options to `preserve`. hexapdf also allows you to add password protection to your PDF, if that's something you're interested in doing. ifndef::env-site[] == Contributing See the <>. To help develop {project-name}, or to simply use the development version, refer to the <>. [[resources,Links]] == Resources * https://groups.google.com/forum/#!msg/prawn-ruby/MbMsCx862iY/6ImCsvLGfVcJ[Discussion about image quality in PDFs] == Authors {project-name} was written by https://github.com/mojavelinux[Dan Allen] and https://github.com/graphitefriction[Sarah White] of OpenDevise Inc. on behalf of the Asciidoctor Project. == Copyright Copyright (C) 2014-2020 OpenDevise Inc. and the Asciidoctor Project. Free use of this software is granted under the terms of the MIT License. For the full text of the license, see the <> file. Refer to the <> file for information about third-party Open Source software in use. ",12411,False,2065.3082315250804,median "CLASS ltcl_from_hex DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: test01 FOR TESTING, test02 FOR TESTING. METHODS: test IMPORTING iv_exp TYPE string iv_hex TYPE xstring. ENDCLASS. CLASS ltcl_from_hex IMPLEMENTATION. METHOD test. DATA: lo_int TYPE REF TO zcl_abappgp_integer. lo_int = zcl_abappgp_integer=>from_hex( iv_hex ). cl_abap_unit_assert=>assert_equals( act = lo_int->to_string( ) exp = iv_exp ). ENDMETHOD. METHOD test01. test( iv_exp = '65537' iv_hex = '010001' ). ENDMETHOD. METHOD test02. test( iv_exp = '8070450532247928831' iv_hex = '6FFFFFFFFFFFFFFF' ). ENDMETHOD. ENDCLASS. CLASS ltcl_to_hex DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: test01 FOR TESTING, test02 FOR TESTING. METHODS: test IMPORTING iv_int TYPE string iv_exp TYPE xstring. ENDCLASS. CLASS ltcl_to_hex IMPLEMENTATION. METHOD test. DATA: lv_hex TYPE xstring, lo_int TYPE REF TO zcl_abappgp_integer. lo_int = zcl_abappgp_integer=>from_string( iv_int ). lv_hex = lo_int->to_hex( ). cl_abap_unit_assert=>assert_equals( act = lv_hex exp = iv_exp ). ENDMETHOD. METHOD test01. test( iv_int = '65537' iv_exp = '010001' ). ENDMETHOD. METHOD test02. test( iv_int = '8070450532247928831' iv_exp = '6FFFFFFFFFFFFFFF' ). ENDMETHOD. ENDCLASS. CLASS ltcl_extended_gcd DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: test1 FOR TESTING, test2 FOR TESTING. METHODS: test IMPORTING iv_a TYPE string iv_b TYPE string iv_coeff1 TYPE string iv_coeff2 TYPE string iv_gcd TYPE string iv_quo1 TYPE string iv_quo2 TYPE string. ENDCLASS. CLASS ltcl_extended_gcd IMPLEMENTATION. METHOD test. DATA: lo_a TYPE REF TO zcl_abappgp_integer, lo_b TYPE REF TO zcl_abappgp_integer, lo_coeff1 TYPE REF TO zcl_abappgp_integer, lo_coeff2 TYPE REF TO zcl_abappgp_integer, lo_gcd TYPE REF TO zcl_abappgp_integer, lo_quo1 TYPE REF TO zcl_abappgp_integer, lo_quo2 TYPE REF TO zcl_abappgp_integer. lo_a = zcl_abappgp_integer=>from_string( iv_a ). lo_b = zcl_abappgp_integer=>from_string( iv_b ). zcl_abappgp_integer=>extended_gcd( EXPORTING io_a = lo_a io_b = lo_b IMPORTING eo_coeff1 = lo_coeff1 eo_coeff2 = lo_coeff2 eo_gcd = lo_gcd eo_quo1 = lo_quo1 eo_quo2 = lo_quo2 ). cl_abap_unit_assert=>assert_equals( act = lo_coeff1->to_string( ) exp = iv_coeff1 ). cl_abap_unit_assert=>assert_equals( act = lo_coeff2->to_string( ) exp = iv_coeff2 ). cl_abap_unit_assert=>assert_equals( act = lo_gcd->to_string( ) exp = iv_gcd ). cl_abap_unit_assert=>assert_equals( act = lo_quo1->to_string( ) exp = iv_quo1 ). cl_abap_unit_assert=>assert_equals( act = lo_quo2->to_string( ) exp = iv_quo2 ). ENDMETHOD. METHOD test1. test( iv_a = '240' iv_b = '46' iv_coeff1 = '-9' iv_coeff2 = '47' iv_gcd = '2' iv_quo1 = '-120' iv_quo2 = '23' ). ENDMETHOD. METHOD test2. test( iv_a = '17' iv_b = '3120' iv_coeff1 = '-367' iv_coeff2 = '2' iv_gcd = '1' iv_quo1 = '-17' iv_quo2 = '3120' ). ENDMETHOD. ENDCLASS. CLASS ltcl_gcd DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: gcd1 FOR TESTING, gcd2 FOR TESTING, gcd3 FOR TESTING, gcd4 FOR TESTING. METHODS: test IMPORTING iv_a TYPE string iv_b TYPE string iv_exp TYPE string. ENDCLASS. CLASS ltcl_gcd IMPLEMENTATION. METHOD test. DATA: lo_a TYPE REF TO zcl_abappgp_integer, lo_b TYPE REF TO zcl_abappgp_integer. lo_a = zcl_abappgp_integer=>from_string( iv_a ). lo_b = zcl_abappgp_integer=>from_string( iv_b ). lo_a = lo_a->gcd( lo_b ). cl_abap_unit_assert=>assert_equals( act = lo_a->to_string( ) exp = iv_exp ). ENDMETHOD. METHOD gcd1. test( iv_a = '5' iv_b = '108' iv_exp = '1' ). ENDMETHOD. METHOD gcd2. test( iv_a = '4' iv_b = '108' iv_exp = '4' ). ENDMETHOD. METHOD gcd3. test( iv_a = '17' iv_b = '3120' iv_exp = '1' ). ENDMETHOD. METHOD gcd4. test( iv_a = '1' iv_b = '1' iv_exp = '1' ). ENDMETHOD. ENDCLASS. CLASS ltcl_mod_inverse DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: mod_inverse1 FOR TESTING, mod_inverse2 FOR TESTING, mod_inverse3 FOR TESTING. METHODS: test IMPORTING iv_value TYPE string iv_mod TYPE string RETURNING VALUE(rv_result) TYPE string. ENDCLASS. CLASS ltcl_mod_inverse IMPLEMENTATION. METHOD test. DATA: lo_value TYPE REF TO zcl_abappgp_integer, lo_mod TYPE REF TO zcl_abappgp_integer. lo_value = zcl_abappgp_integer=>from_string( iv_value ). lo_mod = zcl_abappgp_integer=>from_string( iv_mod ). rv_result = lo_value->mod_inverse( lo_mod )->to_string( ). ENDMETHOD. METHOD mod_inverse1. DATA: lv_result TYPE string. lv_result = test( iv_value = '42' iv_mod = '2017' ). cl_abap_unit_assert=>assert_equals( act = lv_result exp = '1969' ). ENDMETHOD. METHOD mod_inverse2. DATA: lv_result TYPE string. lv_result = test( iv_value = '40' iv_mod = '1' ). cl_abap_unit_assert=>assert_equals( act = lv_result exp = '0' ). ENDMETHOD. METHOD mod_inverse3. DATA: lv_result TYPE string. lv_result = test( iv_value = '256' iv_mod = '25' ). cl_abap_unit_assert=>assert_equals( act = lv_result exp = '21' ). ENDMETHOD. ENDCLASS. CLASS ltcl_divide_by_2 DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: divide1 FOR TESTING, divide2 FOR TESTING, divide3 FOR TESTING, divide4 FOR TESTING. METHODS: test IMPORTING iv_value TYPE string RETURNING VALUE(ro_int) TYPE REF TO zcl_abappgp_integer. ENDCLASS. CLASS ltcl_divide_by_2 IMPLEMENTATION. METHOD test. ro_int = zcl_abappgp_integer=>from_string( iv_value ). ro_int->divide_by_2( ). ENDMETHOD. METHOD divide1. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '0' ). ENDMETHOD. METHOD divide2. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( '2' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. METHOD divide3. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( '22' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '11' ). ENDMETHOD. METHOD divide4. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( '111222333' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '55611166' ). ENDMETHOD. ENDCLASS. CLASS ltcl_modular_pow DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: modular_pow1 FOR TESTING, modular_pow2 FOR TESTING, modular_pow3 FOR TESTING, modular_pow4 FOR TESTING. METHODS: test IMPORTING iv_base TYPE string iv_exp TYPE string iv_mod TYPE string RETURNING VALUE(ro_int) TYPE REF TO zcl_abappgp_integer. ENDCLASS. CLASS ltcl_modular_pow IMPLEMENTATION. METHOD test. DATA: lo_mod TYPE REF TO zcl_abappgp_integer, lo_check TYPE REF TO zcl_abappgp_integer, lo_exp TYPE REF TO zcl_abappgp_integer. ro_int = zcl_abappgp_integer=>from_string( iv_base ). lo_exp = zcl_abappgp_integer=>from_string( iv_exp ). lo_mod = zcl_abappgp_integer=>from_string( iv_mod ). ro_int->modular_pow( io_exponent = lo_exp io_modulus = lo_mod ). IF lo_mod->is_even( ) = abap_false. lo_check = zcl_abappgp_integer=>from_string( iv_base ). lo_check = lo_check->modular_pow_montgomery( io_exponent = lo_exp io_modulus = lo_mod ). cl_abap_unit_assert=>assert_equals( act = ro_int->to_string( ) exp = lo_check->to_string( ) ). ENDIF. ENDMETHOD. METHOD modular_pow1. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_base = '1' iv_exp = '1' iv_mod = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '0' ). ENDMETHOD. METHOD modular_pow2. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_base = '4' iv_exp = '13' iv_mod = '497' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '445' ). ENDMETHOD. METHOD modular_pow3. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_base = '3' iv_exp = '7' iv_mod = '4' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '3' ). ENDMETHOD. METHOD modular_pow4. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_base = '4578' iv_exp = '100' iv_mod = '25' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. ENDCLASS. CLASS ltcl_mod DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: mod1 FOR TESTING, mod2 FOR TESTING, mod3 FOR TESTING, mod4 FOR TESTING, mod5 FOR TESTING, mod6 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string RETURNING VALUE(ro_int) TYPE REF TO zcl_abappgp_integer. ENDCLASS. CLASS ltcl_mod IMPLEMENTATION. METHOD test. DATA: lo_var2 TYPE REF TO zcl_abappgp_integer. ro_int = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). ro_int->mod( lo_var2 ). ENDMETHOD. METHOD mod1. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '0' ). ENDMETHOD. METHOD mod2. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '5' iv_op2 = '2' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. METHOD mod3. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '9999' iv_op2 = '9999' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '0' ). ENDMETHOD. METHOD mod4. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '10009' iv_op2 = '10' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '9' ). ENDMETHOD. METHOD mod5. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '10' iv_op2 = '100000' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '10' ). ENDMETHOD. METHOD mod6. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '30558784' iv_op2 = '44449' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '22321' ). ENDMETHOD. ENDCLASS. CLASS ltcl_divide DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: divide1 FOR TESTING, divide2 FOR TESTING, divide3 FOR TESTING, divide4 FOR TESTING, divide5 FOR TESTING, divide6 FOR TESTING, divide7 FOR TESTING, divide8 FOR TESTING, divide9 FOR TESTING, divide10 FOR TESTING, divide11 FOR TESTING, divide12 FOR TESTING, divide13 FOR TESTING, divide14 FOR TESTING, divide_generic FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string RETURNING VALUE(ro_int) TYPE REF TO zcl_abappgp_integer. ENDCLASS. CLASS ltcl_divide IMPLEMENTATION. METHOD test. DATA: lo_var2 TYPE REF TO zcl_abappgp_integer. ro_int = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). ro_int->divide( lo_var2 ). ENDMETHOD. METHOD divide1. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. METHOD divide2. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '123456' iv_op2 = '123456' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. METHOD divide3. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '5' iv_op2 = '2' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '2' ). ENDMETHOD. METHOD divide4. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '555555' iv_op2 = '111111' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '5' ). ENDMETHOD. METHOD divide5. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '5' iv_op2 = '2' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '2' ). ENDMETHOD. METHOD divide6. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1' iv_op2 = '100' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '0' ). ENDMETHOD. METHOD divide7. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '30558784' iv_op2 = '44449' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '687' ). ENDMETHOD. METHOD divide8. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '30558784' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '30558784' ). ENDMETHOD. METHOD divide9. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1000' iv_op2 = '7' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '142' ). ENDMETHOD. METHOD divide10. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '5827800983498960781124740512078744256512' iv_op2 = '48112959837082048697' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '121127467593613023351' ). ENDMETHOD. METHOD divide11. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '7382888' iv_op2 = '9' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '820320' ). ENDMETHOD. METHOD divide12. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '91' iv_op2 = '10' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '9' ). ENDMETHOD. METHOD divide13. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1000' iv_op2 = '1000' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. METHOD divide14. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1000000' iv_op2 = '1000' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1000' ). ENDMETHOD. METHOD divide_generic. DATA: lo_res TYPE REF TO zcl_abappgp_integer, lv_op1 TYPE string, lv_op2 TYPE string, lv_expected TYPE i. DO 100 TIMES. lv_op1 = sy-index. DO 100 TIMES. lv_op2 = sy-index. lv_expected = lv_op1 DIV lv_op2. lo_res = test( iv_op1 = condense( lv_op1 ) iv_op2 = condense( lv_op2 ) ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = lv_expected msg = |{ lv_op1 } DIV { lv_op2 }| ). ENDDO. ENDDO. ENDMETHOD. ENDCLASS. CLASS ltcl_eq DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: eq1 FOR TESTING, eq2 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string RETURNING VALUE(rv_bool) TYPE abap_bool. ENDCLASS. CLASS ltcl_eq IMPLEMENTATION. METHOD test. DATA: lo_var1 TYPE REF TO zcl_abappgp_integer, lo_var2 TYPE REF TO zcl_abappgp_integer. lo_var1 = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). rv_bool = lo_var1->is_eq( lo_var2 ). ENDMETHOD. METHOD eq1. DATA: lv_eq TYPE bool. lv_eq = test( iv_op1 = '7382888' iv_op2 = '4152888' ). cl_abap_unit_assert=>assert_equals( act = lv_eq exp = abap_false ). ENDMETHOD. METHOD eq2. DATA: lv_eq TYPE bool. lv_eq = test( iv_op1 = '1112888' iv_op2 = '1112888' ). cl_abap_unit_assert=>assert_equals( act = lv_eq exp = abap_true ). ENDMETHOD. ENDCLASS. CLASS ltcl_ge DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: ge1 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string RETURNING VALUE(rv_bool) TYPE abap_bool. ENDCLASS. CLASS ltcl_ge IMPLEMENTATION. METHOD test. DATA: lo_var1 TYPE REF TO zcl_abappgp_integer, lo_var2 TYPE REF TO zcl_abappgp_integer. lo_var1 = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). rv_bool = lo_var1->is_ge( lo_var2 ). ENDMETHOD. METHOD ge1. DATA: lv_ge TYPE bool. lv_ge = test( iv_op1 = '7382888' iv_op2 = '4152888' ). cl_abap_unit_assert=>assert_equals( act = lv_ge exp = abap_true ). ENDMETHOD. ENDCLASS. CLASS ltcl_gt DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: gt1 FOR TESTING, gt2 FOR TESTING, gt3 FOR TESTING, gt4 FOR TESTING, gt5 FOR TESTING, gt6 FOR TESTING, gt7 FOR TESTING, gt8 FOR TESTING, gt9 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string RETURNING VALUE(rv_bool) TYPE abap_bool. ENDCLASS. CLASS ltcl_gt IMPLEMENTATION. METHOD test. DATA: lo_var1 TYPE REF TO zcl_abappgp_integer, lo_var2 TYPE REF TO zcl_abappgp_integer. lo_var1 = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). rv_bool = lo_var1->is_gt( lo_var2 ). ENDMETHOD. METHOD gt1. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '0' iv_op2 = '0' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_false ). ENDMETHOD. METHOD gt2. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '1' iv_op2 = '0' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_true ). ENDMETHOD. METHOD gt3. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '10000' iv_op2 = '9999' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_true ). ENDMETHOD. METHOD gt4. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '10000' iv_op2 = '10000' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_false ). ENDMETHOD. METHOD gt5. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '30514335' iv_op2 = '44449' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_true ). ENDMETHOD. METHOD gt6. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '-30514335' iv_op2 = '44449' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_false ). ENDMETHOD. METHOD gt7. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '-44449' iv_op2 = '-30514335' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_true ). ENDMETHOD. METHOD gt8. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '-30514335' iv_op2 = '-44449' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_false ). ENDMETHOD. METHOD gt9. DATA: lv_gt TYPE bool. lv_gt = test( iv_op1 = '7382888' iv_op2 = '4152888' ). cl_abap_unit_assert=>assert_equals( act = lv_gt exp = abap_true ). ENDMETHOD. ENDCLASS. CLASS ltcl_power DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: power1 FOR TESTING, power2 FOR TESTING, power3 FOR TESTING, power4 FOR TESTING, power5 FOR TESTING, power6 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string RETURNING VALUE(ro_int) TYPE REF TO zcl_abappgp_integer. ENDCLASS. CLASS ltcl_power IMPLEMENTATION. METHOD test. DATA: lo_var2 TYPE REF TO zcl_abappgp_integer. ro_int = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). ro_int->power( lo_var2 ). ENDMETHOD. METHOD power1. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '0' iv_op2 = '0' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. METHOD power2. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1' iv_op2 = '0' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. METHOD power3. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '100' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '100' ). ENDMETHOD. METHOD power4. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '100' iv_op2 = '2' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '10000' ). ENDMETHOD. METHOD power5. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '99' iv_op2 = '3' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '970299' ). ENDMETHOD. METHOD power6. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '99' iv_op2 = '9' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '913517247483640899' ). ENDMETHOD. ENDCLASS. CLASS ltcl_multiply_10 DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: multiply_10_1 FOR TESTING, multiply_10_2 FOR TESTING, multiply_10_3 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE i iv_exp TYPE string. ENDCLASS. CLASS ltcl_multiply_10 IMPLEMENTATION. METHOD test. DATA: lo_var1 TYPE REF TO zcl_abappgp_integer. lo_var1 = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var1->multiply_10( iv_op2 ). cl_abap_unit_assert=>assert_equals( act = lo_var1->to_string( ) exp = iv_exp ). ENDMETHOD. METHOD multiply_10_1. test( iv_op1 = '1' iv_op2 = 1 iv_exp = '10' ). ENDMETHOD. METHOD multiply_10_2. test( iv_op1 = '1' iv_op2 = 4 iv_exp = '10000' ). ENDMETHOD. METHOD multiply_10_3. test( iv_op1 = '10' iv_op2 = 4 iv_exp = '100000' ). ENDMETHOD. ENDCLASS. CLASS ltcl_divide_knuth DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: knuth1 FOR TESTING, knuth2 FOR TESTING, knuth3 FOR TESTING, knuth4 FOR TESTING, knuth5 FOR TESTING, knuth6 FOR TESTING, knuth7 FOR TESTING, knuth8 FOR TESTING, knuth9 FOR TESTING, knuth10 FOR TESTING, knuth11 FOR TESTING, knuth12 FOR TESTING, knuth13 FOR TESTING, knuth14 FOR TESTING, knuth15 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string iv_exp TYPE string. ENDCLASS. CLASS ltcl_divide_knuth IMPLEMENTATION. METHOD test. DATA: lo_var1 TYPE REF TO zcl_abappgp_integer, lo_var2 TYPE REF TO zcl_abappgp_integer. lo_var1 = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). lo_var1->divide_knuth( lo_var2 ). cl_abap_unit_assert=>assert_equals( act = lo_var1->to_string( ) exp = iv_exp ). ENDMETHOD. METHOD knuth1. test( iv_op1 = '333344445555' iv_op2 = '66667777' iv_exp = '5000' ). ENDMETHOD. METHOD knuth2. test( iv_op1 = '333344445555' iv_op2 = '11117777' iv_exp = '29983' ). ENDMETHOD. METHOD knuth3. test( iv_op1 = '111111111111' iv_op2 = '99999999' iv_exp = '1111' ). ENDMETHOD. METHOD knuth4. test( iv_op1 = '3333444455558888' iv_op2 = '66667777' iv_exp = '50000834' ). ENDMETHOD. METHOD knuth5. test( iv_op1 = '3333444455557777' iv_op2 = '11117777' iv_exp = '299830123' ). ENDMETHOD. METHOD knuth6. test( iv_op1 = '900000000000' iv_op2 = '200000000000' iv_exp = '4' ). ENDMETHOD. METHOD knuth7. test( iv_op1 = '600000000000' iv_op2 = '500000000000' iv_exp = '1' ). ENDMETHOD. METHOD knuth8. test( iv_op1 = '35695639049' iv_op2 = '35277131919' iv_exp = '1' ). ENDMETHOD. METHOD knuth9. test( iv_op1 = '977887108912' iv_op2 = '977814152357' iv_exp = '1' ). ENDMETHOD. METHOD knuth10. test( iv_op1 = '890697079374' iv_op2 = '594432114521' iv_exp = '1' ). ENDMETHOD. METHOD knuth11. test( iv_op1 = '68570083720345' iv_op2 = '80670690' iv_exp = '849999' ). ENDMETHOD. METHOD knuth12. test( iv_op1 = '5060488832657916' iv_op2 = '3804878826' iv_exp = '1329999' ). ENDMETHOD. METHOD knuth13. test( iv_op1 = '63396481633550' iv_op2 = '55127363' iv_exp = '1150000' ). ENDMETHOD. METHOD knuth14. test( iv_op1 = '62555604' iv_op2 = '57421151' iv_exp = '1' ). ENDMETHOD. METHOD knuth15. test( iv_op1 = '58567883112735' iv_op2 = '33659729' iv_exp = '1739998' ). ENDMETHOD. ENDCLASS. CLASS ltcl_multiply_karatsuba DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: karatsuba1 FOR TESTING, karatsuba2 FOR TESTING, karatsuba3 FOR TESTING, karatsuba4 FOR TESTING, karatsuba5 FOR TESTING, karatsuba6 FOR TESTING, karatsuba7 FOR TESTING, karatsuba8 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string iv_exp TYPE string. ENDCLASS. CLASS ltcl_multiply_karatsuba IMPLEMENTATION. METHOD test. DATA: lo_var1 TYPE REF TO zcl_abappgp_integer, lo_var2 TYPE REF TO zcl_abappgp_integer. lo_var1 = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). lo_var1->multiply_karatsuba( lo_var2 ). cl_abap_unit_assert=>assert_equals( act = lo_var1->to_string( ) exp = iv_exp ). ENDMETHOD. METHOD karatsuba1. test( iv_op1 = '1' iv_op2 = '1' iv_exp = '1' ). ENDMETHOD. METHOD karatsuba2. test( iv_op1 = '11112222' iv_op2 = '33334444' iv_exp = '370419741974568' ). ENDMETHOD. METHOD karatsuba3. test( iv_op1 = '1111' iv_op2 = '1111' iv_exp = '1234321' ). ENDMETHOD. METHOD karatsuba4. test( iv_op1 = '9999' iv_op2 = '9999' iv_exp = '99980001' ). ENDMETHOD. METHOD karatsuba5. test( iv_op1 = '500' iv_op2 = '50000' iv_exp = '25000000' ). ENDMETHOD. METHOD karatsuba6. test( iv_op1 = '30558784' iv_op2 = '44449' iv_exp = '1358307390016' ). ENDMETHOD. METHOD karatsuba7. test( iv_op1 = '100000' iv_op2 = '0' iv_exp = '0' ). ENDMETHOD. METHOD karatsuba8. test( iv_op1 = '7777777777' iv_op2 = '6666666666' iv_exp = '51851851841481481482' ). ENDMETHOD. ENDCLASS. CLASS ltcl_multiply DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: multiply1 FOR TESTING, multiply2 FOR TESTING, multiply3 FOR TESTING, multiply4 FOR TESTING, multiply5 FOR TESTING, multiply6 FOR TESTING, multiply7 FOR TESTING, multiply8 FOR TESTING, multiply9 FOR TESTING, multiply10 FOR TESTING, multiply11 FOR TESTING, multiply12 FOR TESTING, multiply13 FOR TESTING, multiply14 FOR TESTING, multiply15 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string iv_exp TYPE string. ENDCLASS. CLASS ltcl_multiply IMPLEMENTATION. METHOD test. DATA: lo_var1 TYPE REF TO zcl_abappgp_integer, lo_var2 TYPE REF TO zcl_abappgp_integer. lo_var1 = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). lo_var1->multiply( lo_var2 ). cl_abap_unit_assert=>assert_equals( act = lo_var1->to_string( ) exp = iv_exp ). ENDMETHOD. METHOD multiply1. test( iv_op1 = '1' iv_op2 = '1' iv_exp = '1' ). ENDMETHOD. METHOD multiply2. test( iv_op1 = '1' iv_op2 = '0' iv_exp = '0' ). ENDMETHOD. METHOD multiply3. test( iv_op1 = '0' iv_op2 = '0' iv_exp = '0' ). ENDMETHOD. METHOD multiply4. test( iv_op1 = '2' iv_op2 = '3' iv_exp = '6' ). ENDMETHOD. METHOD multiply5. test( iv_op1 = '1111' iv_op2 = '1111' iv_exp = '1234321' ). ENDMETHOD. METHOD multiply6. test( iv_op1 = '9999' iv_op2 = '9999' iv_exp = '99980001' ). ENDMETHOD. METHOD multiply7. test( iv_op1 = '500' iv_op2 = '50000' iv_exp = '25000000' ). ENDMETHOD. METHOD multiply8. test( iv_op1 = '30558784' iv_op2 = '44449' iv_exp = '1358307390016' ). ENDMETHOD. METHOD multiply9. test( iv_op1 = '100000' iv_op2 = '0' iv_exp = '0' ). ENDMETHOD. METHOD multiply10. test( iv_op1 = '7777777777' iv_op2 = '6666666666' iv_exp = '51851851841481481482' ). ENDMETHOD. METHOD multiply11. test( iv_op1 = '-77' iv_op2 = '66' iv_exp = '-5082' ). ENDMETHOD. METHOD multiply12. test( iv_op1 = '-77' iv_op2 = '-66' iv_exp = '5082' ). ENDMETHOD. METHOD multiply13. test( iv_op1 = '77' iv_op2 = '-66' iv_exp = '-5082' ). ENDMETHOD. METHOD multiply14. test( iv_op1 = '999999999999999' iv_op2 = '999999999999999' iv_exp = '999999999999998000000000000001' ). ENDMETHOD. METHOD multiply15. test( iv_op1 = '9999999999999990' iv_op2 = '9999999999999990' iv_exp = '99999999999999800000000000000100' ). ENDMETHOD. ENDCLASS. CLASS ltcl_subtract DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: subtract1 FOR TESTING, subtract2 FOR TESTING, subtract3 FOR TESTING, subtract4 FOR TESTING, subtract5 FOR TESTING, subtract6 FOR TESTING, subtract7 FOR TESTING, subtract8 FOR TESTING, subtract9 FOR TESTING, subtract10 FOR TESTING, subtract11 FOR TESTING, subtract12 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string RETURNING VALUE(ro_int) TYPE REF TO zcl_abappgp_integer. ENDCLASS. CLASS ltcl_subtract IMPLEMENTATION. METHOD test. DATA: lo_var2 TYPE REF TO zcl_abappgp_integer. ro_int = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). ro_int = ro_int->subtract( lo_var2 ). ENDMETHOD. METHOD subtract1. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '0' ). ENDMETHOD. METHOD subtract2. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '0' iv_op2 = '0' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '0' ). ENDMETHOD. METHOD subtract3. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '10' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '9' ). ENDMETHOD. METHOD subtract4. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '10000' iv_op2 = '10000' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '0' ). ENDMETHOD. METHOD subtract5. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '10000' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '9999' ). ENDMETHOD. METHOD subtract6. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '5' iv_op2 = '10' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '-5' ). ENDMETHOD. METHOD subtract7. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '-5' iv_op2 = '-10' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '5' ). ENDMETHOD. METHOD subtract8. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '5' iv_op2 = '999999' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '-999994' ). ENDMETHOD. METHOD subtract9. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '-5' iv_op2 = '5' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '-10' ). ENDMETHOD. METHOD subtract10. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '5' iv_op2 = '-5' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '10' ). ENDMETHOD. METHOD subtract11. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '-3' iv_op2 = '7' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '-10' ). ENDMETHOD. METHOD subtract12. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '3' iv_op2 = '-7' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '10' ). ENDMETHOD. ENDCLASS. CLASS ltcl_add DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: add1 FOR TESTING, add2 FOR TESTING, add3 FOR TESTING, add4 FOR TESTING, add5 FOR TESTING, add6 FOR TESTING, add7 FOR TESTING, add8 FOR TESTING, add9 FOR TESTING, add10 FOR TESTING. METHODS: test IMPORTING iv_op1 TYPE string iv_op2 TYPE string RETURNING VALUE(ro_int) TYPE REF TO zcl_abappgp_integer. ENDCLASS. ""ltcl_Add CLASS ltcl_add IMPLEMENTATION. METHOD test. DATA: lo_var2 TYPE REF TO zcl_abappgp_integer. ro_int = zcl_abappgp_integer=>from_string( iv_op1 ). lo_var2 = zcl_abappgp_integer=>from_string( iv_op2 ). ro_int = ro_int->add( lo_var2 ). ENDMETHOD. METHOD add1. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '2' ). ENDMETHOD. METHOD add2. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1' iv_op2 = '0' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '1' ). ENDMETHOD. METHOD add3. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1111' iv_op2 = '1111' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '2222' ). ENDMETHOD. METHOD add4. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '111111' iv_op2 = '1111' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '112222' ). ENDMETHOD. METHOD add5. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1111' iv_op2 = '111111' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '112222' ). ENDMETHOD. METHOD add6. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '1' iv_op2 = '9999' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '10000' ). ENDMETHOD. METHOD add7. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '99980001' iv_op2 = '1' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '99980002' ). ENDMETHOD. METHOD add8. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '-5' iv_op2 = '-5' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '-10' ). ENDMETHOD. METHOD add9. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '-5' iv_op2 = '10' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '5' ). ENDMETHOD. METHOD add10. DATA: lo_res TYPE REF TO zcl_abappgp_integer. lo_res = test( iv_op1 = '10' iv_op2 = '-5' ). cl_abap_unit_assert=>assert_equals( act = lo_res->to_string( ) exp = '5' ). ENDMETHOD. ENDCLASS. CLASS ltcl_identity DEFINITION FOR TESTING DURATION SHORT RISK LEVEL HARMLESS FINAL. PRIVATE SECTION. METHODS: id1 FOR TESTING, id2 FOR TESTING, id3 FOR TESTING, id4 FOR TESTING, id5 FOR TESTING, id6 FOR TESTING, id7 FOR TESTING. METHODS: test IMPORTING iv_string TYPE string. ENDCLASS. ""ltcl_Add CLASS ltcl_identity IMPLEMENTATION. METHOD test. DATA: lo_var1 TYPE REF TO zcl_abappgp_integer, lv_result TYPE string. lo_var1 = zcl_abappgp_integer=>from_string( iv_string ). lv_result = lo_var1->to_string( ). cl_abap_unit_assert=>assert_equals( act = lv_result exp = iv_string ). ENDMETHOD. METHOD id1. test( '1' ). ENDMETHOD. METHOD id2. test( '0' ). ENDMETHOD. METHOD id3. test( '123456789123456789' ). ENDMETHOD. METHOD id4. test( '1000000000000000000000000009' ). ENDMETHOD. METHOD id5. test( '10000000000000000000000000009' ). ENDMETHOD. METHOD id6. test( '12345678' ). ENDMETHOD. METHOD id7. test( '-100' ). ENDMETHOD. ENDCLASS. ",13008,True,3751.9240819981637,median "/** * @file SparkFun_APDS-9960.cpp * @brief Library for the SparkFun APDS-9960 breakout board * @author Shawn Hymel (SparkFun Electronics) * * @copyright This code is public domain but you buy me a beer if you use * this and we meet someday (Beerware license). * * This library interfaces the Avago APDS-9960 to Arduino over I2C. The library * relies on the Arduino Wire (I2C) library. to use the library, instantiate an * APDS9960 object, call init(), and call the appropriate functions. * * APDS-9960 current draw tests (default parameters): * Off: 1mA * Waiting for gesture: 14mA * Gesture in progress: 35mA */ #include #include #include ""SparkFun_APDS9960.h"" /** * @brief Constructor - Instantiates SparkFun_APDS9960 object */ SparkFun_APDS9960::SparkFun_APDS9960() { gesture_ud_delta_ = 0; gesture_lr_delta_ = 0; gesture_ud_count_ = 0; gesture_lr_count_ = 0; gesture_near_count_ = 0; gesture_far_count_ = 0; gesture_state_ = 0; gesture_motion_ = DIR_NONE; } /** * @brief Destructor */ SparkFun_APDS9960::~SparkFun_APDS9960() { } /** * @brief Configures I2C communications and initializes registers to defaults * * @return True if initialized successfully. False otherwise. */ bool SparkFun_APDS9960::init(void) { uint8_t id; /* Initialize I2C */ //Wire.begin(); //Wire.begin(D3,D1); /* Read ID register and check against known values for APDS-9960 */ if( !wireReadDataByte(APDS9960_ID, id) ) { return false; } if( !(id == APDS9960_ID_1 || id == APDS9960_ID_2) ) { return false; } /* Set ENABLE register to 0 (disable all features) */ if( !setMode(APDS9960_ALL, APDS9960_OFF) ) { return false; } /* Set default values for ambient light and proximity registers */ if( !wireWriteDataByte(APDS9960_ATIME, DEFAULT_ATIME) ) { return false; } if( !wireWriteDataByte(APDS9960_WTIME, DEFAULT_WTIME) ) { return false; } if( !wireWriteDataByte(APDS9960_PPULSE, DEFAULT_PROX_PPULSE) ) { return false; } if( !wireWriteDataByte(APDS9960_POFFSET_UR, DEFAULT_POFFSET_UR) ) { return false; } if( !wireWriteDataByte(APDS9960_POFFSET_DL, DEFAULT_POFFSET_DL) ) { return false; } if( !wireWriteDataByte(APDS9960_CONFIG1, DEFAULT_CONFIG1) ) { return false; } if( !setLEDDrive(DEFAULT_LDRIVE) ) { return false; } if( !setProximityGain(DEFAULT_PGAIN) ) { return false; } if( !setAmbientLightGain(DEFAULT_AGAIN) ) { return false; } if( !setProxIntLowThresh(DEFAULT_PILT) ) { return false; } if( !setProxIntHighThresh(DEFAULT_PIHT) ) { return false; } if( !setLightIntLowThreshold(DEFAULT_AILT) ) { return false; } if( !setLightIntHighThreshold(DEFAULT_AIHT) ) { return false; } if( !wireWriteDataByte(APDS9960_PERS, DEFAULT_PERS) ) { return false; } if( !wireWriteDataByte(APDS9960_CONFIG2, DEFAULT_CONFIG2) ) { return false; } if( !wireWriteDataByte(APDS9960_CONFIG3, DEFAULT_CONFIG3) ) { return false; } /* Set default values for gesture sense registers */ if( !setGestureEnterThresh(DEFAULT_GPENTH) ) { return false; } if( !setGestureExitThresh(DEFAULT_GEXTH) ) { return false; } if( !wireWriteDataByte(APDS9960_GCONF1, DEFAULT_GCONF1) ) { return false; } if( !setGestureGain(DEFAULT_GGAIN) ) { return false; } if( !setGestureLEDDrive(DEFAULT_GLDRIVE) ) { return false; } if( !setGestureWaitTime(DEFAULT_GWTIME) ) { return false; } if( !wireWriteDataByte(APDS9960_GOFFSET_U, DEFAULT_GOFFSET_U) ) { return false; } if( !wireWriteDataByte(APDS9960_GOFFSET_D, DEFAULT_GOFFSET_D) ) { return false; } if( !wireWriteDataByte(APDS9960_GOFFSET_L, DEFAULT_GOFFSET_L) ) { return false; } if( !wireWriteDataByte(APDS9960_GOFFSET_R, DEFAULT_GOFFSET_R) ) { return false; } if( !wireWriteDataByte(APDS9960_GPULSE, DEFAULT_GPULSE) ) { return false; } if( !wireWriteDataByte(APDS9960_GCONF3, DEFAULT_GCONF3) ) { return false; } if( !setGestureIntEnable(DEFAULT_GIEN) ) { return false; } #if 0 /* Gesture config register dump */ uint8_t reg; uint8_t val; for(reg = 0x80; reg <= 0xAF; reg++) { if( (reg != 0x82) && \\ (reg != 0x8A) && \\ (reg != 0x91) && \\ (reg != 0xA8) && \\ (reg != 0xAC) && \\ (reg != 0xAD) ) { wireReadDataByte(reg, val); Serial.print(reg, HEX); Serial.print("": 0x""); Serial.println(val, HEX); } } for(reg = 0xE4; reg <= 0xE7; reg++) { wireReadDataByte(reg, val); Serial.print(reg, HEX); Serial.print("": 0x""); Serial.println(val, HEX); } #endif return true; } /******************************************************************************* * Public methods for controlling the APDS-9960 ******************************************************************************/ /** * @brief Reads and returns the contents of the ENABLE register * * @return Contents of the ENABLE register. 0xFF if error. */ uint8_t SparkFun_APDS9960::getMode() { uint8_t enable_value; /* Read current ENABLE register */ if( !wireReadDataByte(APDS9960_ENABLE, enable_value) ) { return APDS9960_ERROR; } return enable_value; } // Enables or disables a feature in the APDS-9960 // Accesses the Enable Register (0x80) // @param[in] mode which feature to enable // @param[in] enable APDS9960_ON (1) or APDS9960_OFF (0) // @return True if operation success. False otherwise. bool SparkFun_APDS9960::setMode(uint8_t mode, uint8_t enable) { uint8_t reg_val; /* Read current ENABLE register */ reg_val = getMode(); if( reg_val == APDS9960_ERROR ) { return false; } /* Change bit(s) in ENABLE register */ enable &= 0x01; if(mode <= 6) { if (enable) { reg_val |= (1 << mode); } else { reg_val &= ~(1 << mode); } } else if( mode == APDS9960_ALL ) { if (enable) { reg_val = 0x7F; } else { reg_val = 0x00; } } else return false; /* Write value back to ENABLE register */ if( !wireWriteDataByte(APDS9960_ENABLE, reg_val) ) { return false; } return true; } /** * @brief Starts the light (R/G/B/Ambient) sensor on the APDS-9960 * * @param[in] interrupts true to enable hardware interrupt on high or low light * @return True if sensor enabled correctly. False on error. */ bool SparkFun_APDS9960::enableLightSensor(bool interrupts) { /* Set default gain, interrupts, enable power, and enable sensor */ if( !setAmbientLightGain(DEFAULT_AGAIN) ) { return false; } if( interrupts ) { if( !setAmbientLightIntEnable(1) ) { return false; } } else { if( !setAmbientLightIntEnable(0) ) { return false; } } if( !enablePower() ){ return false; } if( !setMode(AMBIENT_LIGHT, 1) ) { return false; } return true; } /** * @brief Ends the light sensor on the APDS-9960 * * @return True if sensor disabled correctly. False on error. */ bool SparkFun_APDS9960::disableLightSensor() { if( !setAmbientLightIntEnable(0) ) { return false; } if( !setMode(AMBIENT_LIGHT, 0) ) { return false; } return true; } /** * @brief Starts the proximity sensor on the APDS-9960 * * @param[in] interrupts true to enable hardware external interrupt on proximity * @return True if sensor enabled correctly. False on error. */ bool SparkFun_APDS9960::enableProximitySensor(bool interrupts) { /* Set default gain, LED, interrupts, enable power, and enable sensor */ if( !setProximityGain(DEFAULT_PGAIN) ) { return false; } if( !setLEDDrive(DEFAULT_LDRIVE) ) { return false; } if( interrupts ) { if( !setProximityIntEnable(1) ) { return false; } } else { if( !setProximityIntEnable(0) ) { return false; } } if( !enablePower() ){ return false; } if( !setMode(APDS9960_PROXIMITY, 1) ) { return false; } return true; } /** * @brief Ends the proximity sensor on the APDS-9960 * * @return True if sensor disabled correctly. False on error. */ bool SparkFun_APDS9960::disableProximitySensor() { if( !setProximityIntEnable(0) ) { return false; } if( !setMode(APDS9960_PROXIMITY, 0) ) { return false; } return true; } /** * @brief Starts the gesture recognition engine on the APDS-9960 * * @param[in] interrupts true to enable hardware external interrupt on gesture * @return True if engine enabled correctly. False on error. */ bool SparkFun_APDS9960::enableGestureSensor(bool interrupts) { /* Enable gesture mode Set ENABLE to 0 (power off) Set WTIME to 0xFF Set AUX to LED_BOOST_300 Enable PON, WEN, PEN, GEN in ENABLE */ resetGestureParameters(); if( !wireWriteDataByte(APDS9960_WTIME, 0xFF) ) { // 2.78mS return false; } if( !wireWriteDataByte(APDS9960_PPULSE, DEFAULT_GESTURE_PPULSE) ) { // 16us, 10 pulses return false; } //Jon if( !setLEDBoost(LED_BOOST_300) ) { //Ulno confirmed, does not even work on 300 with capacitor if( !setLEDBoost(LED_BOOST_100) ) { return false; } if( interrupts ) { if( !setGestureIntEnable(1) ) { return false; } } else { if( !setGestureIntEnable(0) ) { return false; } } if( !setGestureMode(1) ) { return false; } if( !enablePower() ){ return false; } if( !setMode(WAITING_TIME, 1) ) { return false; } if( !setMode(APDS9960_PROXIMITY, 1) ) { return false; } if( !setMode(APDS9960_GESTURE, 1) ) { return false; } return true; } /** * @brief Ends the gesture recognition engine on the APDS-9960 * * @return True if engine disabled correctly. False on error. */ bool SparkFun_APDS9960::disableGestureSensor() { resetGestureParameters(); if( !setGestureIntEnable(0) ) { return false; } if( !setGestureMode(0) ) { return false; } if( !setMode(APDS9960_GESTURE, 0) ) { return false; } return true; } /** * @brief Determines if there is a gesture available for reading * * @return True if gesture available. False otherwise. */ bool SparkFun_APDS9960::isGestureAvailable() { uint8_t val; /* Read value from GSTATUS register */ if( !wireReadDataByte(APDS9960_GSTATUS, val) ) { return APDS9960_ERROR; } /* Shift and mask out GVALID bit */ val &= APDS9960_GVALID; /* Return true/false based on GVALID bit */ if( val == 1) { return true; } else { return false; } } /** * @brief Processes a gesture event and returns best guessed gesture * * @return Number corresponding to gesture. -1 on error. */ //Jon int SparkFun_APDS9960::readGesture() int16_t SparkFun_APDS9960::readGesture() { uint8_t fifo_level = 0; uint8_t bytes_read = 0; uint8_t fifo_data[128]; uint8_t gstatus; //Jon int motion; //Jon int i; uint16_t motion; uint16_t i; /* Make sure that data is valid, power is on and gesture has been enabled */ if( !isGestureAvailable() || !(getMode() & (APDS9960_PON | APDS9960_GEN)) ) { return DIR_NONE; } /* Keep looping as long as gesture data is valid */ while(1) { /* Wait some time to collect next batch of FIFO data */ delay(FIFO_PAUSE_TIME); /* Get the contents of the STATUS register. Is data still valid? */ if( !wireReadDataByte(APDS9960_GSTATUS, gstatus) ) { return APDS9960_ERROR; } /* If we have valid data, read in FIFO */ if( (gstatus & APDS9960_GVALID) == APDS9960_GVALID ) { /* Read the current FIFO level */ if( !wireReadDataByte(APDS9960_GFLVL, fifo_level) ) { return APDS9960_ERROR; } #ifdef GDEBUG Serial.print(""FIFO Level: ""); Serial.println(fifo_level); #endif /* If there's stuff in the FIFO, read it into our data block */ if( fifo_level > 0) { bytes_read = wireReadDataBlock( APDS9960_GFIFO_U, (uint8_t*)fifo_data, (fifo_level * 4) ); if( bytes_read == -1 ) { return APDS9960_ERROR; } #ifdef GDEBUG Serial.print(""FIFO Dump: ""); for ( i = 0; i < bytes_read; i++ ) { Serial.print(fifo_data[i]); Serial.print("" ""); } Serial.println(); #endif /* If at least 1 set of data, sort the data into U/D/L/R */ if( bytes_read >= 4 ) { for( i = 0; i < bytes_read; i += 4 ) { gesture_data_.u_data[gesture_data_.index] = \\ fifo_data[i + 0]; gesture_data_.d_data[gesture_data_.index] = \\ fifo_data[i + 1]; gesture_data_.l_data[gesture_data_.index] = \\ fifo_data[i + 2]; gesture_data_.r_data[gesture_data_.index] = \\ fifo_data[i + 3]; gesture_data_.index++; gesture_data_.total_gestures++; } #ifdef GDEBUG Serial.print(""Up Data: ""); for ( i = 0; i < gesture_data_.total_gestures; i++ ) { Serial.print(gesture_data_.u_data[i]); Serial.print("" ""); } Serial.println(); Serial.print(""Dn Data: ""); for ( i = 0; i < gesture_data_.total_gestures; i++ ) { Serial.print(gesture_data_.d_data[i]); Serial.print("" ""); } Serial.println(); Serial.print(""L Data: ""); for ( i = 0; i < gesture_data_.total_gestures; i++ ) { Serial.print(gesture_data_.l_data[i]); Serial.print("" ""); } Serial.println(); Serial.print(""R Data: ""); for ( i = 0; i < gesture_data_.total_gestures; i++ ) { Serial.print(gesture_data_.r_data[i]); Serial.print("" ""); } Serial.println(); #endif /* Filter and process gesture data. Decode near/far state */ if( processGestureData() ) { if( decodeGesture() ) { //***TODO: U-Turn Gestures #ifdef GDEBUG //Serial.println(gesture_motion_); #endif } } /* Reset data */ gesture_data_.index = 0; gesture_data_.total_gestures = 0; } } } else { /* Determine best guessed gesture and clean up */ delay(FIFO_PAUSE_TIME); decodeGesture(); motion = gesture_motion_; #ifdef GDEBUG Serial.print(""END: ""); Serial.println(gesture_motion_); #endif resetGestureParameters(); return motion; } } } /** * Turn the APDS-9960 on * * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::enablePower() { if( !setMode(APDS9960_POWER, APDS9960_ON) ) { return false; } return true; } /** * Turn the APDS-9960 off * * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::disablePower() { if( !setMode(APDS9960_POWER, APDS9960_OFF) ) { return false; } return true; } /******************************************************************************* * Ambient light and color sensor controls ******************************************************************************/ /** * @brief Reads the ambient (clear) light level as a 16-bit value * * @param[out] val value of the light sensor. * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::readAmbientLight(uint16_t &val) { uint8_t val_byte; val = 0; /* Read value from clear channel, low byte register */ if( !wireReadDataByte(APDS9960_CDATAL, val_byte) ) { return false; } val = val_byte; /* Read value from clear channel, high byte register */ if( !wireReadDataByte(APDS9960_CDATAH, val_byte) ) { return false; } val = val + ((uint16_t)val_byte << 8); return true; } /** * @brief Reads the red light level as a 16-bit value * * @param[out] val value of the light sensor. * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::readRedLight(uint16_t &val) { uint8_t val_byte; val = 0; /* Read value from clear channel, low byte register */ if( !wireReadDataByte(APDS9960_RDATAL, val_byte) ) { return false; } val = val_byte; /* Read value from clear channel, high byte register */ if( !wireReadDataByte(APDS9960_RDATAH, val_byte) ) { return false; } val = val + ((uint16_t)val_byte << 8); return true; } /** * @brief Reads the green light level as a 16-bit value * * @param[out] val value of the light sensor. * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::readGreenLight(uint16_t &val) { uint8_t val_byte; val = 0; /* Read value from clear channel, low byte register */ if( !wireReadDataByte(APDS9960_GDATAL, val_byte) ) { return false; } val = val_byte; /* Read value from clear channel, high byte register */ if( !wireReadDataByte(APDS9960_GDATAH, val_byte) ) { return false; } val = val + ((uint16_t)val_byte << 8); return true; } /** * @brief Reads the red light level as a 16-bit value * * @param[out] val value of the light sensor. * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::readBlueLight(uint16_t &val) { uint8_t val_byte; val = 0; /* Read value from clear channel, low byte register */ if( !wireReadDataByte(APDS9960_BDATAL, val_byte) ) { return false; } val = val_byte; /* Read value from clear channel, high byte register */ if( !wireReadDataByte(APDS9960_BDATAH, val_byte) ) { return false; } val = val + ((uint16_t)val_byte << 8); return true; } /******************************************************************************* * Proximity sensor controls ******************************************************************************/ /** * @brief Reads the proximity level as an 8-bit value * * @param[out] val value of the proximity sensor. * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::readProximity(uint8_t &val) { val = 0; /* Read value from proximity data register */ if( !wireReadDataByte(APDS9960_PDATA, val) ) { return false; } return true; } /******************************************************************************* * High-level gesture controls ******************************************************************************/ /** * @brief Resets all the parameters in the gesture data member */ void SparkFun_APDS9960::resetGestureParameters() { gesture_data_.index = 0; gesture_data_.total_gestures = 0; gesture_ud_delta_ = 0; gesture_lr_delta_ = 0; gesture_ud_count_ = 0; gesture_lr_count_ = 0; gesture_near_count_ = 0; gesture_far_count_ = 0; gesture_state_ = 0; gesture_motion_ = DIR_NONE; } /** * @brief Processes the raw gesture data to determine swipe direction * * @return True if near or far state seen. False otherwise. */ bool SparkFun_APDS9960::processGestureData() { uint8_t u_first = 0; uint8_t d_first = 0; uint8_t l_first = 0; uint8_t r_first = 0; uint8_t u_last = 0; uint8_t d_last = 0; uint8_t l_last = 0; uint8_t r_last = 0; /* Jon int ud_ratio_first; int lr_ratio_first; int ud_ratio_last; int lr_ratio_last; int ud_delta; int lr_delta; int i; */ int16_t ud_ratio_first; int16_t lr_ratio_first; int16_t ud_ratio_last; int16_t lr_ratio_last; int16_t ud_delta; int16_t lr_delta; int16_t i; /* If we have less than 4 total gestures, that's not enough */ if( gesture_data_.total_gestures <= 4 ) { return false; } /* Check to make sure our data isn't out of bounds */ if( (gesture_data_.total_gestures <= 32) && \\ (gesture_data_.total_gestures > 0) ) { /* Find the first value in U/D/L/R above the threshold */ for( i = 0; i < gesture_data_.total_gestures; i++ ) { if( (gesture_data_.u_data[i] > GESTURE_THRESHOLD_OUT) && (gesture_data_.d_data[i] > GESTURE_THRESHOLD_OUT) && (gesture_data_.l_data[i] > GESTURE_THRESHOLD_OUT) && (gesture_data_.r_data[i] > GESTURE_THRESHOLD_OUT) ) { u_first = gesture_data_.u_data[i]; d_first = gesture_data_.d_data[i]; l_first = gesture_data_.l_data[i]; r_first = gesture_data_.r_data[i]; break; } } /* If one of the _first values is 0, then there is no good data */ if( (u_first == 0) || (d_first == 0) || \\ (l_first == 0) || (r_first == 0) ) { return false; } /* Find the last value in U/D/L/R above the threshold */ for( i = gesture_data_.total_gestures - 1; i >= 0; i-- ) { #ifdef DEBUG Serial.print(F(""Finding last: "")); Serial.print(F(""U:"")); Serial.print(gesture_data_.u_data[i]); Serial.print(F("" D:"")); Serial.print(gesture_data_.d_data[i]); Serial.print(F("" L:"")); Serial.print(gesture_data_.l_data[i]); Serial.print(F("" R:"")); Serial.println(gesture_data_.r_data[i]); #endif if( (gesture_data_.u_data[i] > GESTURE_THRESHOLD_OUT) && (gesture_data_.d_data[i] > GESTURE_THRESHOLD_OUT) && (gesture_data_.l_data[i] > GESTURE_THRESHOLD_OUT) && (gesture_data_.r_data[i] > GESTURE_THRESHOLD_OUT) ) { u_last = gesture_data_.u_data[i]; d_last = gesture_data_.d_data[i]; l_last = gesture_data_.l_data[i]; r_last = gesture_data_.r_data[i]; break; } } } /* Catch to make sure we don't divide by 0 */ if( ((u_first + d_first) == 0) || ((l_first + r_first) == 0) || ((u_last + d_last) == 0) || ((l_last + r_last) == 0) ) { return false; } /* Calculate the first vs. last ratio of up/down and left/right */ ud_ratio_first = ((u_first - d_first) * 100) / (u_first + d_first); lr_ratio_first = ((l_first - r_first) * 100) / (l_first + r_first); ud_ratio_last = ((u_last - d_last) * 100) / (u_last + d_last); lr_ratio_last = ((l_last - r_last) * 100) / (l_last + r_last); #ifdef DEBUG Serial.print(F(""Last Values: "")); Serial.print(F(""U:"")); Serial.print(u_last); Serial.print(F("" D:"")); Serial.print(d_last); Serial.print(F("" L:"")); Serial.print(l_last); Serial.print(F("" R:"")); Serial.println(r_last); Serial.print(F(""Ratios: "")); Serial.print(F(""UD Fi: "")); Serial.print(ud_ratio_first); Serial.print(F("" UD La: "")); Serial.print(ud_ratio_last); Serial.print(F("" LR Fi: "")); Serial.print(lr_ratio_first); Serial.print(F("" LR La: "")); Serial.println(lr_ratio_last); #endif /* Determine the difference between the first and last ratios */ ud_delta = ud_ratio_last - ud_ratio_first; lr_delta = lr_ratio_last - lr_ratio_first; #ifdef DEBUG Serial.print(""Deltas: ""); Serial.print(""UD: ""); Serial.print(ud_delta); Serial.print("" LR: ""); Serial.println(lr_delta); #endif /* Accumulate the UD and LR delta values */ gesture_ud_delta_ += ud_delta; gesture_lr_delta_ += lr_delta; #ifdef DEBUG Serial.print(""Accumulations: ""); Serial.print(""UD: ""); Serial.print(gesture_ud_delta_); Serial.print("" LR: ""); Serial.println(gesture_lr_delta_); #endif /* Determine U/D gesture */ if( gesture_ud_delta_ >= GESTURE_SENSITIVITY_1 ) { gesture_ud_count_ = 1; } else if( gesture_ud_delta_ <= -GESTURE_SENSITIVITY_1 ) { gesture_ud_count_ = -1; } else { gesture_ud_count_ = 0; } /* Determine L/R gesture */ if( gesture_lr_delta_ >= GESTURE_SENSITIVITY_1 ) { gesture_lr_count_ = 1; } else if( gesture_lr_delta_ <= -GESTURE_SENSITIVITY_1 ) { gesture_lr_count_ = -1; } else { gesture_lr_count_ = 0; } /* Determine Near/Far gesture */ if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == 0) ) { if( (abs(ud_delta) < GESTURE_SENSITIVITY_2) && \\ (abs(lr_delta) < GESTURE_SENSITIVITY_2) ) { if( (ud_delta == 0) && (lr_delta == 0) ) { gesture_near_count_++; } else if( (ud_delta != 0) || (lr_delta != 0) ) { gesture_far_count_++; } if( (gesture_near_count_ >= 10) && (gesture_far_count_ >= 2) ) { if( (ud_delta == 0) && (lr_delta == 0) ) { gesture_state_ = NEAR_STATE; } else if( (ud_delta != 0) && (lr_delta != 0) ) { gesture_state_ = FAR_STATE; } return true; } } } else { if( (abs(ud_delta) < GESTURE_SENSITIVITY_2) && \\ (abs(lr_delta) < GESTURE_SENSITIVITY_2) ) { if( (ud_delta == 0) && (lr_delta == 0) ) { gesture_near_count_++; } if( gesture_near_count_ >= 10 ) { gesture_ud_count_ = 0; gesture_lr_count_ = 0; gesture_ud_delta_ = 0; gesture_lr_delta_ = 0; } } } #ifdef DEBUG Serial.print(""UD_CT: ""); Serial.print(gesture_ud_count_); Serial.print("" LR_CT: ""); Serial.print(gesture_lr_count_); Serial.print("" NEAR_CT: ""); Serial.print(gesture_near_count_); Serial.print("" FAR_CT: ""); Serial.println(gesture_far_count_); Serial.println(""----------""); #endif return false; } /** * @brief Determines swipe direction or near/far state * * @return True if near/far event. False otherwise. */ bool SparkFun_APDS9960::decodeGesture() { /* Return if near or far event is detected */ if( gesture_state_ == NEAR_STATE ) { gesture_motion_ = DIR_NEAR; return true; } else if ( gesture_state_ == FAR_STATE ) { gesture_motion_ = DIR_FAR; return true; } /* Determine swipe direction */ if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == 0) ) { gesture_motion_ = DIR_UP; } else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == 0) ) { gesture_motion_ = DIR_DOWN; } else if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == 1) ) { gesture_motion_ = DIR_RIGHT; } else if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == -1) ) { gesture_motion_ = DIR_LEFT; } else if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == 1) ) { if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) { gesture_motion_ = DIR_UP; } else { gesture_motion_ = DIR_RIGHT; } } else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == -1) ) { if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) { gesture_motion_ = DIR_DOWN; } else { gesture_motion_ = DIR_LEFT; } } else if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == -1) ) { if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) { gesture_motion_ = DIR_UP; } else { gesture_motion_ = DIR_LEFT; } } else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == 1) ) { if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) { gesture_motion_ = DIR_DOWN; } else { gesture_motion_ = DIR_RIGHT; } } else { return false; } return true; } /******************************************************************************* * Getters and setters for register values ******************************************************************************/ /** * @brief Returns the lower threshold for proximity detection * * @return lower threshold */ uint8_t SparkFun_APDS9960::getProxIntLowThresh() { uint8_t val; /* Read value from PILT register */ if( !wireReadDataByte(APDS9960_PILT, val) ) { val = 0; } return val; } /** * @brief Sets the lower threshold for proximity detection * * @param[in] threshold the lower proximity threshold * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setProxIntLowThresh(uint8_t threshold) { if( !wireWriteDataByte(APDS9960_PILT, threshold) ) { return false; } return true; } /** * @brief Returns the high threshold for proximity detection * * @return high threshold */ uint8_t SparkFun_APDS9960::getProxIntHighThresh() { uint8_t val; /* Read value from PIHT register */ if( !wireReadDataByte(APDS9960_PIHT, val) ) { val = 0; } return val; } /** * @brief Sets the high threshold for proximity detection * * @param[in] threshold the high proximity threshold * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setProxIntHighThresh(uint8_t threshold) { if( !wireWriteDataByte(APDS9960_PIHT, threshold) ) { return false; } return true; } /** * @brief Returns LED drive strength for proximity and ALS * * Value LED Current * 0 100 mA * 1 50 mA * 2 25 mA * 3 12.5 mA * * @return the value of the LED drive strength. 0xFF on failure. */ uint8_t SparkFun_APDS9960::getLEDDrive() { uint8_t val; /* Read value from CONTROL register */ if( !wireReadDataByte(APDS9960_CONTROL, val) ) { return APDS9960_ERROR; } /* Shift and mask out LED drive bits */ val = (val >> 6) & 0b00000011; return val; } /** * @brief Sets the LED drive strength for proximity and ALS * * Value LED Current * 0 100 mA * 1 50 mA * 2 25 mA * 3 12.5 mA * * @param[in] drive the value (0-3) for the LED drive strength * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setLEDDrive(uint8_t drive) { uint8_t val; /* Read value from CONTROL register */ if( !wireReadDataByte(APDS9960_CONTROL, val) ) { return false; } /* Set bits in register to given value */ drive &= 0b00000011; drive = drive << 6; val &= 0b00111111; val |= drive; /* Write register value back into CONTROL register */ if( !wireWriteDataByte(APDS9960_CONTROL, val) ) { return false; } return true; } /** * @brief Returns receiver gain for proximity detection * * Value Gain * 0 1x * 1 2x * 2 4x * 3 8x * * @return the value of the proximity gain. 0xFF on failure. */ uint8_t SparkFun_APDS9960::getProximityGain() { uint8_t val; /* Read value from CONTROL register */ if( !wireReadDataByte(APDS9960_CONTROL, val) ) { return APDS9960_ERROR; } /* Shift and mask out PDRIVE bits */ val = (val >> 2) & 0b00000011; return val; } /** * @brief Sets the receiver gain for proximity detection * * Value Gain * 0 1x * 1 2x * 2 4x * 3 8x * * @param[in] drive the value (0-3) for the gain * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setProximityGain(uint8_t drive) { uint8_t val; /* Read value from CONTROL register */ if( !wireReadDataByte(APDS9960_CONTROL, val) ) { return false; } /* Set bits in register to given value */ drive &= 0b00000011; drive = drive << 2; val &= 0b11110011; val |= drive; /* Write register value back into CONTROL register */ if( !wireWriteDataByte(APDS9960_CONTROL, val) ) { return false; } return true; } /** * @brief Returns receiver gain for the ambient light sensor (ALS) * * Value Gain * 0 1x * 1 4x * 2 16x * 3 64x * * @return the value of the ALS gain. 0xFF on failure. */ uint8_t SparkFun_APDS9960::getAmbientLightGain() { uint8_t val; /* Read value from CONTROL register */ if( !wireReadDataByte(APDS9960_CONTROL, val) ) { return APDS9960_ERROR; } /* Shift and mask out ADRIVE bits */ val &= 0b00000011; return val; } /** * @brief Sets the receiver gain for the ambient light sensor (ALS) * * Value Gain * 0 1x * 1 4x * 2 16x * 3 64x * * @param[in] drive the value (0-3) for the gain * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setAmbientLightGain(uint8_t drive) { uint8_t val; /* Read value from CONTROL register */ if( !wireReadDataByte(APDS9960_CONTROL, val) ) { return false; } /* Set bits in register to given value */ drive &= 0b00000011; val &= 0b11111100; val |= drive; /* Write register value back into CONTROL register */ if( !wireWriteDataByte(APDS9960_CONTROL, val) ) { return false; } return true; } /** * @brief Get the current LED boost value * * Value Boost Current * 0 100% * 1 150% * 2 200% * 3 300% * * @return The LED boost value. 0xFF on failure. */ uint8_t SparkFun_APDS9960::getLEDBoost() { uint8_t val; /* Read value from CONFIG2 register */ if( !wireReadDataByte(APDS9960_CONFIG2, val) ) { return APDS9960_ERROR; } /* Shift and mask out LED_BOOST bits */ val = (val >> 4) & 0b00000011; return val; } /** * @brief Sets the LED current boost value * * Value Boost Current * 0 100% * 1 150% * 2 200% * 3 300% * * @param[in] drive the value (0-3) for current boost (100-300%) * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setLEDBoost(uint8_t boost) { uint8_t val; /* Read value from CONFIG2 register */ if( !wireReadDataByte(APDS9960_CONFIG2, val) ) { return false; } /* Set bits in register to given value */ boost &= 0b00000011; boost = boost << 4; val &= 0b11001111; val |= boost; /* Write register value back into CONFIG2 register */ if( !wireWriteDataByte(APDS9960_CONFIG2, val) ) { return false; } return true; } /** * @brief Gets proximity gain compensation enable * * @return 1 if compensation is enabled. 0 if not. 0xFF on error. */ uint8_t SparkFun_APDS9960::getProxGainCompEnable() { uint8_t val; /* Read value from CONFIG3 register */ if( !wireReadDataByte(APDS9960_CONFIG3, val) ) { return APDS9960_ERROR; } /* Shift and mask out PCMP bits */ val = (val >> 5) & 0b00000001; return val; } /** * @brief Sets the proximity gain compensation enable * * @param[in] enable 1 to enable compensation. 0 to disable compensation. * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setProxGainCompEnable(uint8_t enable) { uint8_t val; /* Read value from CONFIG3 register */ if( !wireReadDataByte(APDS9960_CONFIG3, val) ) { return false; } /* Set bits in register to given value */ enable &= 0b00000001; enable = enable << 5; val &= 0b11011111; val |= enable; /* Write register value back into CONFIG3 register */ if( !wireWriteDataByte(APDS9960_CONFIG3, val) ) { return false; } return true; } /** * @brief Gets the current mask for enabled/disabled proximity photodiodes * * 1 = disabled, 0 = enabled * Bit Photodiode * 3 UP * 2 DOWN * 1 LEFT * 0 RIGHT * * @return Current proximity mask for photodiodes. 0xFF on error. */ uint8_t SparkFun_APDS9960::getProxPhotoMask() { uint8_t val; /* Read value from CONFIG3 register */ if( !wireReadDataByte(APDS9960_CONFIG3, val) ) { return APDS9960_ERROR; } /* Mask out photodiode enable mask bits */ val &= 0b00001111; return val; } /** * @brief Sets the mask for enabling/disabling proximity photodiodes * * 1 = disabled, 0 = enabled * Bit Photodiode * 3 UP * 2 DOWN * 1 LEFT * 0 RIGHT * * @param[in] mask 4-bit mask value * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setProxPhotoMask(uint8_t mask) { uint8_t val; /* Read value from CONFIG3 register */ if( !wireReadDataByte(APDS9960_CONFIG3, val) ) { return false; } /* Set bits in register to given value */ mask &= 0b00001111; val &= 0b11110000; val |= mask; /* Write register value back into CONFIG3 register */ if( !wireWriteDataByte(APDS9960_CONFIG3, val) ) { return false; } return true; } /** * @brief Gets the entry proximity threshold for gesture sensing * * @return Current entry proximity threshold. */ uint8_t SparkFun_APDS9960::getGestureEnterThresh() { uint8_t val; /* Read value from GPENTH register */ if( !wireReadDataByte(APDS9960_GPENTH, val) ) { val = 0; } return val; } /** * @brief Sets the entry proximity threshold for gesture sensing * * @param[in] threshold proximity value needed to start gesture mode * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setGestureEnterThresh(uint8_t threshold) { if( !wireWriteDataByte(APDS9960_GPENTH, threshold) ) { return false; } return true; } /** * @brief Gets the exit proximity threshold for gesture sensing * * @return Current exit proximity threshold. */ uint8_t SparkFun_APDS9960::getGestureExitThresh() { uint8_t val; /* Read value from GEXTH register */ if( !wireReadDataByte(APDS9960_GEXTH, val) ) { val = 0; } return val; } /** * @brief Sets the exit proximity threshold for gesture sensing * * @param[in] threshold proximity value needed to end gesture mode * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setGestureExitThresh(uint8_t threshold) { if( !wireWriteDataByte(APDS9960_GEXTH, threshold) ) { return false; } return true; } /** * @brief Gets the gain of the photodiode during gesture mode * * Value Gain * 0 1x * 1 2x * 2 4x * 3 8x * * @return the current photodiode gain. 0xFF on error. */ uint8_t SparkFun_APDS9960::getGestureGain() { uint8_t val; /* Read value from GCONF2 register */ if( !wireReadDataByte(APDS9960_GCONF2, val) ) { return APDS9960_ERROR; } /* Shift and mask out GGAIN bits */ val = (val >> 5) & 0b00000011; return val; } /** * @brief Sets the gain of the photodiode during gesture mode * * Value Gain * 0 1x * 1 2x * 2 4x * 3 8x * * @param[in] gain the value for the photodiode gain * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setGestureGain(uint8_t gain) { uint8_t val; /* Read value from GCONF2 register */ if( !wireReadDataByte(APDS9960_GCONF2, val) ) { return false; } /* Set bits in register to given value */ gain &= 0b00000011; gain = gain << 5; val &= 0b10011111; val |= gain; /* Write register value back into GCONF2 register */ if( !wireWriteDataByte(APDS9960_GCONF2, val) ) { return false; } return true; } /** * @brief Gets the drive current of the LED during gesture mode * * Value LED Current * 0 100 mA * 1 50 mA * 2 25 mA * 3 12.5 mA * * @return the LED drive current value. 0xFF on error. */ uint8_t SparkFun_APDS9960::getGestureLEDDrive() { uint8_t val; /* Read value from GCONF2 register */ if( !wireReadDataByte(APDS9960_GCONF2, val) ) { return APDS9960_ERROR; } /* Shift and mask out GLDRIVE bits */ val = (val >> 3) & 0b00000011; return val; } /** * @brief Sets the LED drive current during gesture mode * * Value LED Current * 0 100 mA * 1 50 mA * 2 25 mA * 3 12.5 mA * * @param[in] drive the value for the LED drive current * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setGestureLEDDrive(uint8_t drive) { uint8_t val; /* Read value from GCONF2 register */ if( !wireReadDataByte(APDS9960_GCONF2, val) ) { return false; } /* Set bits in register to given value */ drive &= 0b00000011; drive = drive << 3; val &= 0b11100111; val |= drive; /* Write register value back into GCONF2 register */ if( !wireWriteDataByte(APDS9960_GCONF2, val) ) { return false; } return true; } /** * @brief Gets the time in low power mode between gesture detections * * Value Wait time * 0 0 ms * 1 2.8 ms * 2 5.6 ms * 3 8.4 ms * 4 14.0 ms * 5 22.4 ms * 6 30.8 ms * 7 39.2 ms * * @return the current wait time between gestures. 0xFF on error. */ uint8_t SparkFun_APDS9960::getGestureWaitTime() { uint8_t val; /* Read value from GCONF2 register */ if( !wireReadDataByte(APDS9960_GCONF2, val) ) { return APDS9960_ERROR; } /* Mask out GWTIME bits */ val &= 0b00000111; return val; } /** * @brief Sets the time in low power mode between gesture detections * * Value Wait time * 0 0 ms * 1 2.8 ms * 2 5.6 ms * 3 8.4 ms * 4 14.0 ms * 5 22.4 ms * 6 30.8 ms * 7 39.2 ms * * @param[in] the value for the wait time * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setGestureWaitTime(uint8_t time) { uint8_t val; /* Read value from GCONF2 register */ if( !wireReadDataByte(APDS9960_GCONF2, val) ) { return false; } /* Set bits in register to given value */ time &= 0b00000111; val &= 0b11111000; val |= time; /* Write register value back into GCONF2 register */ if( !wireWriteDataByte(APDS9960_GCONF2, val) ) { return false; } return true; } /** * @brief Gets the low threshold for ambient light interrupts * * @param[out] threshold current low threshold stored on the APDS-9960 * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::getLightIntLowThreshold(uint16_t &threshold) { uint8_t val_byte; threshold = 0; /* Read value from ambient light low threshold, low byte register */ if( !wireReadDataByte(APDS9960_AILTL, val_byte) ) { return false; } threshold = val_byte; /* Read value from ambient light low threshold, high byte register */ if( !wireReadDataByte(APDS9960_AILTH, val_byte) ) { return false; } threshold = threshold + ((uint16_t)val_byte << 8); return true; } /** * @brief Sets the low threshold for ambient light interrupts * * @param[in] threshold low threshold value for interrupt to trigger * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setLightIntLowThreshold(uint16_t threshold) { uint8_t val_low; uint8_t val_high; /* Break 16-bit threshold into 2 8-bit values */ val_low = threshold & 0x00FF; val_high = (threshold & 0xFF00) >> 8; /* Write low byte */ if( !wireWriteDataByte(APDS9960_AILTL, val_low) ) { return false; } /* Write high byte */ if( !wireWriteDataByte(APDS9960_AILTH, val_high) ) { return false; } return true; } /** * @brief Gets the high threshold for ambient light interrupts * * @param[out] threshold current low threshold stored on the APDS-9960 * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::getLightIntHighThreshold(uint16_t &threshold) { uint8_t val_byte; threshold = 0; /* Read value from ambient light high threshold, low byte register */ if( !wireReadDataByte(APDS9960_AIHTL, val_byte) ) { return false; } threshold = val_byte; /* Read value from ambient light high threshold, high byte register */ if( !wireReadDataByte(APDS9960_AIHTH, val_byte) ) { return false; } threshold = threshold + ((uint16_t)val_byte << 8); return true; } /** * @brief Sets the high threshold for ambient light interrupts * * @param[in] threshold high threshold value for interrupt to trigger * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setLightIntHighThreshold(uint16_t threshold) { uint8_t val_low; uint8_t val_high; /* Break 16-bit threshold into 2 8-bit values */ val_low = threshold & 0x00FF; val_high = (threshold & 0xFF00) >> 8; /* Write low byte */ if( !wireWriteDataByte(APDS9960_AIHTL, val_low) ) { return false; } /* Write high byte */ if( !wireWriteDataByte(APDS9960_AIHTH, val_high) ) { return false; } return true; } /** * @brief Gets the low threshold for proximity interrupts * * @param[out] threshold current low threshold stored on the APDS-9960 * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::getProximityIntLowThreshold(uint8_t &threshold) { threshold = 0; /* Read value from proximity low threshold register */ if( !wireReadDataByte(APDS9960_PILT, threshold) ) { return false; } return true; } /** * @brief Sets the low threshold for proximity interrupts * * @param[in] threshold low threshold value for interrupt to trigger * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setProximityIntLowThreshold(uint8_t threshold) { /* Write threshold value to register */ if( !wireWriteDataByte(APDS9960_PILT, threshold) ) { return false; } return true; } /** * @brief Gets the high threshold for proximity interrupts * * @param[out] threshold current low threshold stored on the APDS-9960 * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::getProximityIntHighThreshold(uint8_t &threshold) { threshold = 0; /* Read value from proximity low threshold register */ if( !wireReadDataByte(APDS9960_PIHT, threshold) ) { return false; } return true; } /** * @brief Sets the high threshold for proximity interrupts * * @param[in] threshold high threshold value for interrupt to trigger * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setProximityIntHighThreshold(uint8_t threshold) { /* Write threshold value to register */ if( !wireWriteDataByte(APDS9960_PIHT, threshold) ) { return false; } return true; } /** * @brief Gets if ambient light interrupts are enabled or not * * @return 1 if interrupts are enabled, 0 if not. 0xFF on error. */ uint8_t SparkFun_APDS9960::getAmbientLightIntEnable() { uint8_t val; /* Read value from ENABLE register */ if( !wireReadDataByte(APDS9960_ENABLE, val) ) { return APDS9960_ERROR; } /* Shift and mask out AIEN bit */ val = (val >> 4) & 0b00000001; return val; } /** * @brief Turns ambient light interrupts on or off * * @param[in] enable 1 to enable interrupts, 0 to turn them off * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setAmbientLightIntEnable(uint8_t enable) { uint8_t val; /* Read value from ENABLE register */ if( !wireReadDataByte(APDS9960_ENABLE, val) ) { return false; } /* Set bits in register to given value */ enable &= 0b00000001; enable = enable << 4; val &= 0b11101111; val |= enable; /* Write register value back into ENABLE register */ if( !wireWriteDataByte(APDS9960_ENABLE, val) ) { return false; } return true; } /** * @brief Gets if proximity interrupts are enabled or not * * @return 1 if interrupts are enabled, 0 if not. 0xFF on error. */ uint8_t SparkFun_APDS9960::getProximityIntEnable() { uint8_t val; /* Read value from ENABLE register */ if( !wireReadDataByte(APDS9960_ENABLE, val) ) { return APDS9960_ERROR; } /* Shift and mask out PIEN bit */ val = (val >> 5) & 0b00000001; return val; } /** * @brief Turns proximity interrupts on or off * * @param[in] enable 1 to enable interrupts, 0 to turn them off * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setProximityIntEnable(uint8_t enable) { uint8_t val; /* Read value from ENABLE register */ if( !wireReadDataByte(APDS9960_ENABLE, val) ) { return false; } /* Set bits in register to given value */ enable &= 0b00000001; enable = enable << 5; val &= 0b11011111; val |= enable; /* Write register value back into ENABLE register */ if( !wireWriteDataByte(APDS9960_ENABLE, val) ) { return false; } return true; } /** * @brief Gets if gesture interrupts are enabled or not * * @return 1 if interrupts are enabled, 0 if not. 0xFF on error. */ uint8_t SparkFun_APDS9960::getGestureIntEnable() { uint8_t val; /* Read value from GCONF4 register */ if( !wireReadDataByte(APDS9960_GCONF4, val) ) { return APDS9960_ERROR; } /* Shift and mask out GIEN bit */ val = (val >> 1) & 0b00000001; return val; } /** * @brief Turns gesture-related interrupts on or off * * @param[in] enable 1 to enable interrupts, 0 to turn them off * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setGestureIntEnable(uint8_t enable) { uint8_t val; /* Read value from GCONF4 register */ if( !wireReadDataByte(APDS9960_GCONF4, val) ) { return false; } /* Set bits in register to given value */ enable &= 0b00000001; enable = enable << 1; val &= 0b11111101; val |= enable; /* Write register value back into GCONF4 register */ if( !wireWriteDataByte(APDS9960_GCONF4, val) ) { return false; } return true; } /** * @brief Clears the ambient light interrupt * * @return True if operation completed successfully. False otherwise. */ bool SparkFun_APDS9960::clearAmbientLightInt() { uint8_t throwaway; if( !wireReadDataByte(APDS9960_AICLEAR, throwaway) ) { return false; } return true; } /** * @brief Clears the proximity interrupt * * @return True if operation completed successfully. False otherwise. */ bool SparkFun_APDS9960::clearProximityInt() { uint8_t throwaway; if( !wireReadDataByte(APDS9960_PICLEAR, throwaway) ) { return false; } return true; } /** * @brief Tells if the gesture state machine is currently running * * @return 1 if gesture state machine is running, 0 if not. 0xFF on error. */ uint8_t SparkFun_APDS9960::getGestureMode() { uint8_t val; /* Read value from GCONF4 register */ if( !wireReadDataByte(APDS9960_GCONF4, val) ) { return APDS9960_ERROR; } /* Mask out GMODE bit */ val &= 0b00000001; return val; } /** * @brief Tells the state machine to either enter or exit gesture state machine * * @param[in] mode 1 to enter gesture state machine, 0 to exit. * @return True if operation successful. False otherwise. */ bool SparkFun_APDS9960::setGestureMode(uint8_t mode) { uint8_t val; /* Read value from GCONF4 register */ if( !wireReadDataByte(APDS9960_GCONF4, val) ) { return false; } /* Set bits in register to given value */ mode &= 0b00000001; val &= 0b11111110; val |= mode; /* Write register value back into GCONF4 register */ if( !wireWriteDataByte(APDS9960_GCONF4, val) ) { return false; } return true; } /** * @brief clears GFIFO, GINT, GVALID, GFIFO_OV and GFIFO_LVL. * ADDED BY SQ */ bool SparkFun_APDS9960::clearGFIFO() { uint8_t val; /* Read value from GCONF4 register */ if( !wireReadDataByte(APDS9960_GCONF4, val) ) { return false; } /* Set bit in register to given value */ val |= 0b00000100; /* Write register value back into GCONF4 register */ if( !wireWriteDataByte(APDS9960_GCONF4, val) ) { return false; } return true; } /******************************************************************************* * Raw I2C Reads and Writes ******************************************************************************/ /** * @brief Writes a single byte to the I2C device (no register) * * @param[in] val the 1-byte value to write to the I2C device * @return True if successful write operation. False otherwise. */ bool SparkFun_APDS9960::wireWriteByte(uint8_t val) { Wire.beginTransmission(APDS9960_I2C_ADDR); Wire.write(val); if( Wire.endTransmission() != 0 ) { return false; } return true; } /** * @brief Writes a single byte to the I2C device and specified register * * @param[in] reg the register in the I2C device to write to * @param[in] val the 1-byte value to write to the I2C device * @return True if successful write operation. False otherwise. */ bool SparkFun_APDS9960::wireWriteDataByte(uint8_t reg, uint8_t val) { Wire.beginTransmission(APDS9960_I2C_ADDR); Wire.write(reg); Wire.write(val); if( Wire.endTransmission() != 0 ) { return false; } return true; } /** * @brief Writes a block (array) of bytes to the I2C device and register * * @param[in] reg the register in the I2C device to write to * @param[in] val pointer to the beginning of the data byte array * @param[in] len the length (in bytes) of the data to write * @return True if successful write operation. False otherwise. */ bool SparkFun_APDS9960::wireWriteDataBlock( uint8_t reg, uint8_t *val, //Jon unsigned int len) uint16_t len) { //Jon unsigned int i; uint16_t i; Wire.beginTransmission(APDS9960_I2C_ADDR); Wire.write(reg); for(i = 0; i < len; i++) { Wire.beginTransmission(val[i]); } if( Wire.endTransmission() != 0 ) { return false; } return true; } /** * @brief Reads a single byte from the I2C device and specified register * * @param[in] reg the register to read from * @param[out] the value returned from the register * @return True if successful read operation. False otherwise. */ bool SparkFun_APDS9960::wireReadDataByte(uint8_t reg, uint8_t &val) { /* Indicate which register we want to read from */ if (!wireWriteByte(reg)) { return false; } // Jon SH: Short delay to improve stability of read from the APDS9960 // without this Wire.requestFrom appears to not return. delayMicroseconds(100); /* Read from register */ Wire.requestFrom(APDS9960_I2C_ADDR, 1); while (Wire.available()) { #ifdef DEBUG_LITE Serial.println("".""); // SQ TODO #endif val = Wire.read(); } return true; } /** * @brief Reads a block (array) of bytes from the I2C device and register * * @param[in] reg the register to read from * @param[out] val pointer to the beginning of the data * @param[in] len number of bytes to read * @return Number of bytes read. -1 on read error. */ //Jon int SparkFun_APDS9960::wireReadDataBlock( uint8_t reg, int16_t SparkFun_APDS9960::wireReadDataBlock( uint8_t reg, uint8_t *val, //Jon unsigned int len) uint16_t len) { unsigned char i = 0; /* Indicate which register we want to read from */ if (!wireWriteByte(reg)) { return -1; } /* Read block data */ Wire.requestFrom(APDS9960_I2C_ADDR, len); while (Wire.available()) { if (i >= len) { return -1; } val[i] = Wire.read(); i++; #ifdef DEBUG_LITE Serial.println("".""); // SQ TODO #endif } #ifdef DEBUG_LITE Serial.println(""\\n""); // SQ TODO #endif return i; } ",16333,True,3749.801348656098,median "/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include ""config.h"" #if ENABLE(SVG) #include ""JSSVGElementInstance.h"" #include ""Event.h"" #include ""EventListener.h"" #include ""ExceptionCode.h"" #include ""JSDOMBinding.h"" #include ""JSEvent.h"" #include ""JSEventListener.h"" #include ""JSSVGElement.h"" #include ""JSSVGElementInstance.h"" #include ""JSSVGElementInstanceList.h"" #include ""JSSVGUseElement.h"" #include ""SVGElement.h"" #include ""SVGElementInstance.h"" #include ""SVGElementInstanceList.h"" #include ""SVGUseElement.h"" #include #include using namespace JSC; namespace WebCore { ASSERT_CLASS_FITS_IN_CELL(JSSVGElementInstance); /* Hash table */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSSVGElementInstanceTableValues[50] = { { ""correspondingElement"", DontDelete | ReadOnly, (intptr_t)static_cast(jsSVGElementInstanceCorrespondingElement), (intptr_t)0 THUNK_GENERATOR(0) }, { ""correspondingUseElement"", DontDelete | ReadOnly, (intptr_t)static_cast(jsSVGElementInstanceCorrespondingUseElement), (intptr_t)0 THUNK_GENERATOR(0) }, { ""parentNode"", DontDelete | ReadOnly, (intptr_t)static_cast(jsSVGElementInstanceParentNode), (intptr_t)0 THUNK_GENERATOR(0) }, { ""childNodes"", DontDelete | ReadOnly, (intptr_t)static_cast(jsSVGElementInstanceChildNodes), (intptr_t)0 THUNK_GENERATOR(0) }, { ""firstChild"", DontDelete | ReadOnly, (intptr_t)static_cast(jsSVGElementInstanceFirstChild), (intptr_t)0 THUNK_GENERATOR(0) }, { ""lastChild"", DontDelete | ReadOnly, (intptr_t)static_cast(jsSVGElementInstanceLastChild), (intptr_t)0 THUNK_GENERATOR(0) }, { ""previousSibling"", DontDelete | ReadOnly, (intptr_t)static_cast(jsSVGElementInstancePreviousSibling), (intptr_t)0 THUNK_GENERATOR(0) }, { ""nextSibling"", DontDelete | ReadOnly, (intptr_t)static_cast(jsSVGElementInstanceNextSibling), (intptr_t)0 THUNK_GENERATOR(0) }, { ""onabort"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnabort), (intptr_t)setJSSVGElementInstanceOnabort THUNK_GENERATOR(0) }, { ""onblur"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnblur), (intptr_t)setJSSVGElementInstanceOnblur THUNK_GENERATOR(0) }, { ""onchange"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnchange), (intptr_t)setJSSVGElementInstanceOnchange THUNK_GENERATOR(0) }, { ""onclick"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnclick), (intptr_t)setJSSVGElementInstanceOnclick THUNK_GENERATOR(0) }, { ""oncontextmenu"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOncontextmenu), (intptr_t)setJSSVGElementInstanceOncontextmenu THUNK_GENERATOR(0) }, { ""ondblclick"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOndblclick), (intptr_t)setJSSVGElementInstanceOndblclick THUNK_GENERATOR(0) }, { ""onerror"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnerror), (intptr_t)setJSSVGElementInstanceOnerror THUNK_GENERATOR(0) }, { ""onfocus"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnfocus), (intptr_t)setJSSVGElementInstanceOnfocus THUNK_GENERATOR(0) }, { ""oninput"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOninput), (intptr_t)setJSSVGElementInstanceOninput THUNK_GENERATOR(0) }, { ""onkeydown"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnkeydown), (intptr_t)setJSSVGElementInstanceOnkeydown THUNK_GENERATOR(0) }, { ""onkeypress"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnkeypress), (intptr_t)setJSSVGElementInstanceOnkeypress THUNK_GENERATOR(0) }, { ""onkeyup"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnkeyup), (intptr_t)setJSSVGElementInstanceOnkeyup THUNK_GENERATOR(0) }, { ""onload"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnload), (intptr_t)setJSSVGElementInstanceOnload THUNK_GENERATOR(0) }, { ""onmousedown"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnmousedown), (intptr_t)setJSSVGElementInstanceOnmousedown THUNK_GENERATOR(0) }, { ""onmousemove"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnmousemove), (intptr_t)setJSSVGElementInstanceOnmousemove THUNK_GENERATOR(0) }, { ""onmouseout"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnmouseout), (intptr_t)setJSSVGElementInstanceOnmouseout THUNK_GENERATOR(0) }, { ""onmouseover"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnmouseover), (intptr_t)setJSSVGElementInstanceOnmouseover THUNK_GENERATOR(0) }, { ""onmouseup"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnmouseup), (intptr_t)setJSSVGElementInstanceOnmouseup THUNK_GENERATOR(0) }, { ""onmousewheel"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnmousewheel), (intptr_t)setJSSVGElementInstanceOnmousewheel THUNK_GENERATOR(0) }, { ""onbeforecut"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnbeforecut), (intptr_t)setJSSVGElementInstanceOnbeforecut THUNK_GENERATOR(0) }, { ""oncut"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOncut), (intptr_t)setJSSVGElementInstanceOncut THUNK_GENERATOR(0) }, { ""onbeforecopy"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnbeforecopy), (intptr_t)setJSSVGElementInstanceOnbeforecopy THUNK_GENERATOR(0) }, { ""oncopy"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOncopy), (intptr_t)setJSSVGElementInstanceOncopy THUNK_GENERATOR(0) }, { ""onbeforepaste"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnbeforepaste), (intptr_t)setJSSVGElementInstanceOnbeforepaste THUNK_GENERATOR(0) }, { ""onpaste"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnpaste), (intptr_t)setJSSVGElementInstanceOnpaste THUNK_GENERATOR(0) }, { ""ondragenter"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOndragenter), (intptr_t)setJSSVGElementInstanceOndragenter THUNK_GENERATOR(0) }, { ""ondragover"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOndragover), (intptr_t)setJSSVGElementInstanceOndragover THUNK_GENERATOR(0) }, { ""ondragleave"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOndragleave), (intptr_t)setJSSVGElementInstanceOndragleave THUNK_GENERATOR(0) }, { ""ondrop"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOndrop), (intptr_t)setJSSVGElementInstanceOndrop THUNK_GENERATOR(0) }, { ""ondragstart"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOndragstart), (intptr_t)setJSSVGElementInstanceOndragstart THUNK_GENERATOR(0) }, { ""ondrag"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOndrag), (intptr_t)setJSSVGElementInstanceOndrag THUNK_GENERATOR(0) }, { ""ondragend"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOndragend), (intptr_t)setJSSVGElementInstanceOndragend THUNK_GENERATOR(0) }, { ""onreset"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnreset), (intptr_t)setJSSVGElementInstanceOnreset THUNK_GENERATOR(0) }, { ""onresize"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnresize), (intptr_t)setJSSVGElementInstanceOnresize THUNK_GENERATOR(0) }, { ""onscroll"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnscroll), (intptr_t)setJSSVGElementInstanceOnscroll THUNK_GENERATOR(0) }, { ""onsearch"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnsearch), (intptr_t)setJSSVGElementInstanceOnsearch THUNK_GENERATOR(0) }, { ""onselect"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnselect), (intptr_t)setJSSVGElementInstanceOnselect THUNK_GENERATOR(0) }, { ""onselectstart"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnselectstart), (intptr_t)setJSSVGElementInstanceOnselectstart THUNK_GENERATOR(0) }, { ""onsubmit"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnsubmit), (intptr_t)setJSSVGElementInstanceOnsubmit THUNK_GENERATOR(0) }, { ""onunload"", DontDelete | DontEnum, (intptr_t)static_cast(jsSVGElementInstanceOnunload), (intptr_t)setJSSVGElementInstanceOnunload THUNK_GENERATOR(0) }, { ""constructor"", DontEnum | ReadOnly, (intptr_t)static_cast(jsSVGElementInstanceConstructor), (intptr_t)0 THUNK_GENERATOR(0) }, { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSSVGElementInstanceTable = { 137, 127, JSSVGElementInstanceTableValues, 0 }; /* Hash table for constructor */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSSVGElementInstanceConstructorTableValues[1] = { { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSSVGElementInstanceConstructorTable = { 1, 0, JSSVGElementInstanceConstructorTableValues, 0 }; class JSSVGElementInstanceConstructor : public DOMConstructorObject { public: JSSVGElementInstanceConstructor(JSC::ExecState*, JSDOMGlobalObject*); virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&); virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&); static const JSC::ClassInfo s_info; static PassRefPtr createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype) { return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info); } protected: static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags; }; const ClassInfo JSSVGElementInstanceConstructor::s_info = { ""SVGElementInstanceConstructor"", &DOMConstructorObject::s_info, &JSSVGElementInstanceConstructorTable, 0 }; JSSVGElementInstanceConstructor::JSSVGElementInstanceConstructor(ExecState* exec, JSDOMGlobalObject* globalObject) : DOMConstructorObject(JSSVGElementInstanceConstructor::createStructure(globalObject->globalData(), globalObject->objectPrototype()), globalObject) { ASSERT(inherits(&s_info)); putDirect(exec->globalData(), exec->propertyNames().prototype, JSSVGElementInstancePrototype::self(exec, globalObject), DontDelete | ReadOnly); } bool JSSVGElementInstanceConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot(exec, &JSSVGElementInstanceConstructorTable, this, propertyName, slot); } bool JSSVGElementInstanceConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor(exec, &JSSVGElementInstanceConstructorTable, this, propertyName, descriptor); } /* Hash table for prototype */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSSVGElementInstancePrototypeTableValues[4] = { { ""addEventListener"", DontDelete | Function, (intptr_t)static_cast(jsSVGElementInstancePrototypeFunctionAddEventListener), (intptr_t)3 THUNK_GENERATOR(0) }, { ""removeEventListener"", DontDelete | Function, (intptr_t)static_cast(jsSVGElementInstancePrototypeFunctionRemoveEventListener), (intptr_t)3 THUNK_GENERATOR(0) }, { ""dispatchEvent"", DontDelete | Function, (intptr_t)static_cast(jsSVGElementInstancePrototypeFunctionDispatchEvent), (intptr_t)1 THUNK_GENERATOR(0) }, { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSSVGElementInstancePrototypeTable = { 8, 7, JSSVGElementInstancePrototypeTableValues, 0 }; const ClassInfo JSSVGElementInstancePrototype::s_info = { ""SVGElementInstancePrototype"", &JSC::JSObjectWithGlobalObject::s_info, &JSSVGElementInstancePrototypeTable, 0 }; JSObject* JSSVGElementInstancePrototype::self(ExecState* exec, JSGlobalObject* globalObject) { return getDOMPrototype(exec, globalObject); } bool JSSVGElementInstancePrototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticFunctionSlot(exec, &JSSVGElementInstancePrototypeTable, this, propertyName, slot); } bool JSSVGElementInstancePrototype::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticFunctionDescriptor(exec, &JSSVGElementInstancePrototypeTable, this, propertyName, descriptor); } const ClassInfo JSSVGElementInstance::s_info = { ""SVGElementInstance"", &DOMObjectWithGlobalPointer::s_info, &JSSVGElementInstanceTable, 0 }; JSSVGElementInstance::JSSVGElementInstance(NonNullPassRefPtr structure, JSDOMGlobalObject* globalObject, PassRefPtr impl) : DOMObjectWithGlobalPointer(structure, globalObject) , m_impl(impl) { ASSERT(inherits(&s_info)); } JSObject* JSSVGElementInstance::createPrototype(ExecState* exec, JSGlobalObject* globalObject) { return new (exec) JSSVGElementInstancePrototype(globalObject, JSSVGElementInstancePrototype::createStructure(globalObject->globalData(), globalObject->objectPrototype())); } bool JSSVGElementInstance::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot(exec, &JSSVGElementInstanceTable, this, propertyName, slot); } bool JSSVGElementInstance::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor(exec, &JSSVGElementInstanceTable, this, propertyName, descriptor); } JSValue jsSVGElementInstanceCorrespondingElement(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->correspondingElement())); return result; } JSValue jsSVGElementInstanceCorrespondingUseElement(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->correspondingUseElement())); return result; } JSValue jsSVGElementInstanceParentNode(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->parentNode())); return result; } JSValue jsSVGElementInstanceChildNodes(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->childNodes())); return result; } JSValue jsSVGElementInstanceFirstChild(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->firstChild())); return result; } JSValue jsSVGElementInstanceLastChild(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->lastChild())); return result; } JSValue jsSVGElementInstancePreviousSibling(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->previousSibling())); return result; } JSValue jsSVGElementInstanceNextSibling(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->nextSibling())); return result; } JSValue jsSVGElementInstanceOnabort(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onabort()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnblur(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onblur()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnchange(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onchange()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnclick(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onclick()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOncontextmenu(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->oncontextmenu()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOndblclick(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->ondblclick()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnerror(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onerror()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnfocus(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onfocus()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOninput(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->oninput()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnkeydown(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onkeydown()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnkeypress(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onkeypress()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnkeyup(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onkeyup()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnload(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onload()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnmousedown(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onmousedown()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnmousemove(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onmousemove()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnmouseout(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onmouseout()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnmouseover(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onmouseover()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnmouseup(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onmouseup()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnmousewheel(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onmousewheel()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnbeforecut(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onbeforecut()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOncut(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->oncut()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnbeforecopy(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onbeforecopy()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOncopy(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->oncopy()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnbeforepaste(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onbeforepaste()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnpaste(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onpaste()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOndragenter(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->ondragenter()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOndragover(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->ondragover()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOndragleave(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->ondragleave()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOndrop(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->ondrop()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOndragstart(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->ondragstart()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOndrag(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->ondrag()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOndragend(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->ondragend()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnreset(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onreset()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnresize(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onresize()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnscroll(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onscroll()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnsearch(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onsearch()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnselect(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onselect()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnselectstart(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onselectstart()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnsubmit(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onsubmit()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceOnunload(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* castedThis = static_cast(asObject(slotBase)); UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(castedThis->impl()); if (EventListener* listener = imp->onunload()) { if (const JSEventListener* jsListener = JSEventListener::cast(listener)) { if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext())) return jsFunction; } } return jsNull(); } JSValue jsSVGElementInstanceConstructor(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGElementInstance* domObject = static_cast(asObject(slotBase)); return JSSVGElementInstance::getConstructor(exec, domObject->globalObject()); } void JSSVGElementInstance::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot) { lookupPut(exec, propertyName, value, &JSSVGElementInstanceTable, this, slot); } void setJSSVGElementInstanceOnabort(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnabort(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnblur(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnblur(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnchange(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnchange(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnclick(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnclick(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOncontextmenu(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOncontextmenu(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOndblclick(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOndblclick(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnerror(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnerror(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnfocus(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnfocus(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOninput(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOninput(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnkeydown(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnkeydown(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnkeypress(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnkeypress(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnkeyup(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnkeyup(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnload(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnload(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnmousedown(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnmousedown(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnmousemove(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnmousemove(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnmouseout(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnmouseout(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnmouseover(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnmouseover(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnmouseup(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnmouseup(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnmousewheel(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnmousewheel(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnbeforecut(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnbeforecut(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOncut(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOncut(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnbeforecopy(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnbeforecopy(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOncopy(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOncopy(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnbeforepaste(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnbeforepaste(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnpaste(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnpaste(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOndragenter(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOndragenter(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOndragover(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOndragover(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOndragleave(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOndragleave(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOndrop(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOndrop(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOndragstart(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOndragstart(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOndrag(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOndrag(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOndragend(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOndragend(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnreset(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnreset(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnresize(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnresize(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnscroll(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnscroll(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnsearch(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnsearch(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnselect(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnselect(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnselectstart(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnselectstart(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnsubmit(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnsubmit(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } void setJSSVGElementInstanceOnunload(ExecState* exec, JSObject* thisObject, JSValue value) { UNUSED_PARAM(exec); SVGElementInstance* imp = static_cast(static_cast(thisObject)->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (correspondingElementWrapper.isObject()) imp->setOnunload(createJSAttributeEventListener(exec, value, asObject(correspondingElementWrapper))); } JSValue JSSVGElementInstance::getConstructor(ExecState* exec, JSGlobalObject* globalObject) { return getDOMConstructor(exec, static_cast(globalObject)); } EncodedJSValue JSC_HOST_CALL jsSVGElementInstancePrototypeFunctionAddEventListener(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGElementInstance::s_info)) return throwVMTypeError(exec); JSSVGElementInstance* castedThis = static_cast(asObject(thisValue)); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (!correspondingElementWrapper.isObject()) return JSValue::encode(jsUndefined()); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); imp->addEventListener(ustringToAtomicString(exec->argument(0).toString(exec)), JSEventListener::create(asObject(listener), asObject(correspondingElementWrapper), false, currentWorld(exec)), exec->argument(2).toBoolean(exec)); return JSValue::encode(jsUndefined()); } EncodedJSValue JSC_HOST_CALL jsSVGElementInstancePrototypeFunctionRemoveEventListener(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGElementInstance::s_info)) return throwVMTypeError(exec); JSSVGElementInstance* castedThis = static_cast(asObject(thisValue)); SVGElementInstance* imp = static_cast(castedThis->impl()); JSValue correspondingElementWrapper = toJS(exec, imp->correspondingElement()); if (!correspondingElementWrapper.isObject()) return JSValue::encode(jsUndefined()); JSValue listener = exec->argument(1); if (!listener.isObject()) return JSValue::encode(jsUndefined()); imp->removeEventListener(ustringToAtomicString(exec->argument(0).toString(exec)), JSEventListener::create(asObject(listener), asObject(correspondingElementWrapper), false, currentWorld(exec)).get(), exec->argument(2).toBoolean(exec)); return JSValue::encode(jsUndefined()); } EncodedJSValue JSC_HOST_CALL jsSVGElementInstancePrototypeFunctionDispatchEvent(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGElementInstance::s_info)) return throwVMTypeError(exec); JSSVGElementInstance* castedThis = static_cast(asObject(thisValue)); SVGElementInstance* imp = static_cast(castedThis->impl()); ExceptionCode ec = 0; Event* event(toEvent(exec->argument(0))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = jsBoolean(imp->dispatchEvent(event, ec)); setDOMException(exec, ec); return JSValue::encode(result); } JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, SVGElementInstance* object) { return getDOMObjectWrapper(exec, globalObject, object); } SVGElementInstance* toSVGElementInstance(JSC::JSValue value) { return value.inherits(&JSSVGElementInstance::s_info) ? static_cast(asObject(value))->impl() : 0; } } #endif // ENABLE(SVG) ",16138,True,4091.258803461249,median "*&---------------------------------------------------------------------* *& Report ZCELLULAR_AUTOMATON *&---------------------------------------------------------------------* *& *&---------------------------------------------------------------------* REPORT zcellular_automaton. CLASS: lcl_simulation DEFINITION DEFERRED, lcl_playing_field DEFINITION DEFERRED. TYPES: BEGIN OF attendee, pos_x TYPE i, pos_y TYPE i, number TYPE text10, open TYPE i, "" open-mindedness comm TYPE i, "" communicative competence origin TYPE xfeld, "" origin of innovation adopted TYPE xfeld, "" innovation transfered generation TYPE i, END OF attendee. TYPES attendees TYPE TABLE OF attendee. TYPES: BEGIN OF protocol_entry, date TYPE sydatum, time TYPE syuzeit, generation TYPE i, text TYPE sdydo_text_element, END OF protocol_entry. TYPES protocol_entries TYPE TABLE OF protocol_entry. DATA gr_simulation TYPE REF TO lcl_simulation. ********************************************************************** SELECTION-SCREEN: BEGIN OF BLOCK info WITH FRAME TITLE title_01, COMMENT 1(79) text_000, COMMENT /1(79) text_001. SELECTION-SCREEN: END OF BLOCK info. SELECTION-SCREEN: BEGIN OF BLOCK params WITH FRAME TITLE title_02, BEGIN OF LINE, COMMENT 1(25) text_002, POSITION 27. PARAMETERS: pa_max_x TYPE numc2 DEFAULT 3. SELECTION-SCREEN: END OF LINE, BEGIN OF LINE, COMMENT 1(25) text_003, POSITION 27. PARAMETERS: pa_max_y TYPE numc2 DEFAULT 3. SELECTION-SCREEN: END OF LINE, BEGIN OF LINE, COMMENT 1(25) text_004, POSITION 27. PARAMETERS: pa_thgrn TYPE numc2 DEFAULT 5. SELECTION-SCREEN: END OF LINE, BEGIN OF LINE, COMMENT 1(25) text_005, POSITION 27. PARAMETERS: pa_thorg TYPE numc2 DEFAULT 10. SELECTION-SCREEN: END OF LINE, BEGIN OF LINE, COMMENT 1(25) text_006, POSITION 27. PARAMETERS: pa_thred TYPE numc2 DEFAULT 15. SELECTION-SCREEN: END OF LINE, END OF BLOCK params. ********************************************************************** CLASS lcx_error DEFINITION INHERITING FROM cx_static_check. PUBLIC SECTION. INTERFACES if_t100_dyn_msg. ENDCLASS. CLASS lcx_error IMPLEMENTATION. ENDCLASS. ********************************************************************** CLASS lcl_protocol DEFINITION. PUBLIC SECTION. METHODS add_entry IMPORTING iv_generation TYPE i iv_text TYPE sdydo_text_element. METHODS get_last_entry EXPORTING es_entry TYPE protocol_entry. METHODS get_entries_per_generation IMPORTING iv_generation TYPE i EXPORTING et_entries TYPE protocol_entries. PRIVATE SECTION. DATA mt_entries TYPE protocol_entries. ENDCLASS. ********************************************************************** CLASS lcl_attendees DEFINITION. PUBLIC SECTION. METHODS constructor IMPORTING ir_simulation TYPE REF TO lcl_simulation. METHODS get_attendee IMPORTING iv_pos_x TYPE i iv_pos_y TYPE i EXPORTING es_attendee TYPE attendee RAISING lcx_error. METHODS get_all_attendees EXPORTING et_attendees TYPE attendees. METHODS get_neighbourhood IMPORTING iv_pos_x TYPE i iv_pos_y TYPE i EXPORTING et_attendees TYPE attendees RAISING lcx_error. METHODS get_neighbour_above IMPORTING iv_pos_x TYPE i iv_pos_y TYPE i RETURNING VALUE(es_attendee) TYPE attendee RAISING lcx_error. METHODS get_neighbour_below IMPORTING iv_pos_x TYPE i iv_pos_y TYPE i RETURNING VALUE(es_attendee) TYPE attendee RAISING lcx_error. METHODS get_neighbour_to_the_left IMPORTING iv_pos_x TYPE i iv_pos_y TYPE i RETURNING VALUE(es_attendee) TYPE attendee RAISING lcx_error. METHODS get_neighbour_to_the_right IMPORTING iv_pos_x TYPE i iv_pos_y TYPE i RETURNING VALUE(es_attendee) TYPE attendee RAISING lcx_error. METHODS set_attendee_adopted IMPORTING iv_pos_x TYPE i iv_pos_y TYPE i iv_generation TYPE i. PRIVATE SECTION. DATA: mt_attendees TYPE attendees, mr_simulation TYPE REF TO lcl_simulation. ENDCLASS. ********************************************************************** CLASS lcl_playing_field DEFINITION. PUBLIC SECTION. METHODS constructor IMPORTING ir_simulation TYPE REF TO lcl_simulation ir_attendees TYPE REF TO lcl_attendees RAISING lcx_error. METHODS refresh. METHODS set_reference IMPORTING iv_reference TYPE REF TO cl_gui_alv_grid. METHODS display RAISING lcx_error. PRIVATE SECTION. DATA: mr_simulation TYPE REF TO lcl_simulation, mt_field_catalog TYPE lvc_t_fcat, mr_fields TYPE REF TO data, mr_reference TYPE REF TO cl_gui_alv_grid, mr_attendees TYPE REF TO lcl_attendees. METHODS build RAISING lcx_error. METHODS generate_tooltip IMPORTING iv_pos_x TYPE i iv_pos_y TYPE i RETURNING VALUE(ev_tooltip) TYPE text50 RAISING lcx_error. METHODS prepare_field_catalog RAISING lcx_error. ENDCLASS. ********************************************************************** CLASS lcl_simulation DEFINITION. PUBLIC SECTION. DATA: mr_protocol TYPE REF TO lcl_protocol, mv_count_attendees TYPE i READ-ONLY, mv_count_adoption TYPE i READ-ONLY, mv_count_left TYPE i READ-ONLY, mv_count_generation TYPE i READ-ONLY, mv_pos_max_x TYPE i READ-ONLY, mv_pos_max_y TYPE i READ-ONLY, mv_start_pos_x TYPE i READ-ONLY, mv_start_pos_y TYPE i READ-ONLY, mv_treshold_green TYPE numc2 READ-ONLY, mv_treshold_orange TYPE numc2 READ-ONLY, mv_treshold_red TYPE numc2 READ-ONLY. METHODS constructor IMPORTING iv_max_x TYPE numc2 iv_max_y TYPE numc2 iv_treshold_green TYPE numc2 iv_treshold_orange TYPE numc2 iv_treshold_red TYPE numc2 RAISING lcx_error. METHODS handle_context_menu_request FOR EVENT context_menu_request OF cl_gui_alv_grid IMPORTING e_object sender. METHODS set_playfield_reference IMPORTING iv_reference TYPE REF TO cl_gui_alv_grid. METHODS start_simulation. METHODS reset_timer. METHODS restart_timer. PRIVATE SECTION. DATA: mr_playing_field TYPE REF TO lcl_playing_field, mr_attendees TYPE REF TO lcl_attendees, mr_timer TYPE REF TO cl_gui_timer. METHODS check_innovation_adoption IMPORTING is_attendee TYPE attendee it_neighbourhood TYPE attendees EXPORTING ev_adopted TYPE xfeld RAISING lcx_error. METHODS create_new_generation RAISING lcx_error. METHODS handle_timer_finished FOR EVENT finished OF cl_gui_timer. ENDCLASS. ********************************************************************** CLASS lcl_protocol IMPLEMENTATION. METHOD add_entry. DATA ls_entry TYPE protocol_entry. IF iv_text IS INITIAL. RETURN. ENDIF. ls_entry-date = sy-datum. ls_entry-time = sy-uzeit. ls_entry-generation = iv_generation. ls_entry-text = iv_text. APPEND ls_entry TO mt_entries. ENDMETHOD. METHOD get_last_entry. DATA lv_lines TYPE i. lv_lines = lines( mt_entries ). READ TABLE mt_entries INTO es_entry INDEX lv_lines. IF sy-subrc <> 0. ENDIF. ENDMETHOD. METHOD get_entries_per_generation. DATA ls_entry LIKE LINE OF mt_entries. LOOP AT mt_entries INTO ls_entry WHERE generation = iv_generation. APPEND ls_entry TO et_entries. ENDLOOP. ENDMETHOD. ENDCLASS. ********************************************************************** CLASS lcl_attendees IMPLEMENTATION. METHOD constructor. DATA: ls_attendee TYPE attendee, lv_x TYPE numc2, lv_y TYPE numc2, lr_random_int TYPE REF TO cl_abap_random_int. mr_simulation = ir_simulation. lr_random_int = cl_abap_random_int=>create( seed = cl_abap_random=>seed( ) min = 1 max = 100 ). "" generate attendees with random communication and open-mindedness level DO mr_simulation->mv_pos_max_y TIMES. lv_y = sy-index. DO mr_simulation->mv_pos_max_x TIMES. CLEAR ls_attendee. lv_x = sy-index. ls_attendee-pos_x = lv_x. ls_attendee-pos_y = lv_y. CONCATENATE 'X' lv_x '-' 'Y' lv_y INTO ls_attendee-number. ls_attendee-comm = lr_random_int->get_next( ). ls_attendee-open = lr_random_int->get_next( ). IF lv_x = mr_simulation->mv_start_pos_x AND lv_y = mr_simulation->mv_start_pos_y. ls_attendee-origin = abap_true. ls_attendee-adopted = abap_true. ENDIF. APPEND ls_attendee TO mt_attendees. ENDDO. ENDDO. ENDMETHOD. METHOD get_attendee. FIELD-SYMBOLS TYPE attendee. READ TABLE mt_attendees ASSIGNING WITH KEY pos_x = iv_pos_x pos_y = iv_pos_y. IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE i499(sy) WITH 'Attendee not found.'. ENDIF. es_attendee = . ENDMETHOD. METHOD get_all_attendees. et_attendees = mt_attendees. ENDMETHOD. METHOD get_neighbour_above. DATA lv_pos_y TYPE i. lv_pos_y = iv_pos_y - 1. IF lv_pos_y <= 0. lv_pos_y = mr_simulation->mv_pos_max_y. ENDIF. READ TABLE mt_attendees INTO es_attendee WITH KEY pos_x = iv_pos_x pos_y = lv_pos_y. IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE e499(sy) WITH 'Neighbour above not found.'. ENDIF. ENDMETHOD. METHOD get_neighbour_below. DATA lv_pos_y TYPE i. lv_pos_y = iv_pos_y + 1. IF lv_pos_y > mr_simulation->mv_pos_max_y. lv_pos_y = 1. ENDIF. READ TABLE mt_attendees INTO es_attendee WITH KEY pos_x = iv_pos_x pos_y = lv_pos_y. IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE e499(sy) WITH 'Neighbour below not found.'. ENDIF. ENDMETHOD. METHOD get_neighbour_to_the_right. DATA lv_pos_x TYPE i. lv_pos_x = iv_pos_x + 1. IF lv_pos_x > mr_simulation->mv_pos_max_x. lv_pos_x = 1. ENDIF. READ TABLE mt_attendees INTO es_attendee WITH KEY pos_x = lv_pos_x pos_y = iv_pos_y. IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE e499(sy) WITH 'Neighbour to the right not found.'. ENDIF. ENDMETHOD. METHOD get_neighbour_to_the_left. DATA lv_pos_x TYPE i. lv_pos_x = iv_pos_x - 1. IF lv_pos_x <= 0. lv_pos_x = mr_simulation->mv_pos_max_x. ENDIF. READ TABLE mt_attendees INTO es_attendee WITH KEY pos_x = lv_pos_x pos_y = iv_pos_y. IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE e499(sy) WITH 'Neighbour to the left not found.'. ENDIF. ENDMETHOD. METHOD get_neighbourhood. DATA: lt_attendees TYPE attendees, ls_attendee TYPE attendee, lv_pos_y_above TYPE i, lv_pos_y_below TYPE i, lv_pos_y TYPE i. TRY. ls_attendee = get_neighbour_above( EXPORTING iv_pos_x = iv_pos_x iv_pos_y = iv_pos_y ). lv_pos_y_above = ls_attendee-pos_y. APPEND ls_attendee TO lt_attendees. CLEAR ls_attendee. ls_attendee = get_neighbour_below( EXPORTING iv_pos_x = iv_pos_x iv_pos_y = iv_pos_y ). lv_pos_y_below = ls_attendee-pos_y. APPEND ls_attendee TO lt_attendees. DO 3 TIMES. CASE sy-index. WHEN 1. lv_pos_y = lv_pos_y_above. WHEN 2. lv_pos_y = iv_pos_y. WHEN 3. lv_pos_y = lv_pos_y_below. ENDCASE. CLEAR ls_attendee. ls_attendee = get_neighbour_to_the_left( EXPORTING iv_pos_x = iv_pos_x iv_pos_y = lv_pos_y ). APPEND ls_attendee TO lt_attendees. CLEAR ls_attendee. ls_attendee = get_neighbour_to_the_right( EXPORTING iv_pos_x = iv_pos_x iv_pos_y = lv_pos_y ). APPEND ls_attendee TO lt_attendees. ENDDO. CATCH lcx_error. RAISE EXCEPTION TYPE lcx_error MESSAGE e499(sy) WITH 'Error identifying neighbourhood .'. ENDTRY. et_attendees = lt_attendees. ENDMETHOD. METHOD set_attendee_adopted. FIELD-SYMBOLS LIKE LINE OF mt_attendees. READ TABLE mt_attendees ASSIGNING WITH KEY pos_x = iv_pos_x pos_y = iv_pos_y. IF sy-subrc = 0. -adopted = abap_true. -generation = iv_generation. ENDIF. ENDMETHOD. ENDCLASS. ********************************************************************** CLASS lcl_playing_field IMPLEMENTATION. METHOD build. DATA: ls_line TYPE REF TO data, lv_field_name TYPE lvc_fname, lv_x_i TYPE i, lv_y_i TYPE i, lv_x_c TYPE numc2, lv_y_c TYPE numc2. FIELD-SYMBOLS: TYPE STANDARD TABLE, TYPE any, TYPE any. "" create playing field as internal table described by field catalog CALL METHOD cl_alv_table_create=>create_dynamic_table EXPORTING it_fieldcatalog = mt_field_catalog IMPORTING ep_table = mr_fields. ASSIGN mr_fields->* TO . IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE i499(sy) WITH 'Playing field could not be created.'. ENDIF. CREATE DATA ls_line LIKE LINE OF . ASSIGN ls_line->* TO . IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE i499(sy) WITH 'Playing field could not be created.'. ENDIF. "" initialize DO mr_simulation->mv_pos_max_y TIMES. lv_y_i = sy-index. lv_y_c = lv_y_i. DO mr_simulation->mv_pos_max_x TIMES. lv_x_i = sy-index. lv_x_c = lv_x_i. "" set icon CONCATENATE 'ICON-' lv_x_c INTO lv_field_name. ASSIGN COMPONENT lv_field_name OF STRUCTURE TO . IF sy-subrc = 0. = generate_tooltip( EXPORTING iv_pos_x = lv_x_i iv_pos_y = lv_y_i ). ENDIF. CONCATENATE 'NUMBER-' lv_x_c INTO lv_field_name. ASSIGN COMPONENT lv_field_name OF STRUCTURE TO . IF sy-subrc = 0. CONCATENATE 'X' lv_x_c '-' 'Y' lv_y_c INTO . ENDIF. ENDDO. IF ls_line IS NOT INITIAL. APPEND TO . ENDIF. ENDDO. ENDMETHOD. METHOD constructor. mr_simulation = ir_simulation. mr_attendees = ir_attendees. TRY. me->prepare_field_catalog( ). me->build( ). CATCH lcx_error. RAISE EXCEPTION TYPE lcx_error MESSAGE i499(sy) WITH 'Playing field could not be created.'. ENDTRY. ENDMETHOD. METHOD generate_tooltip. DATA: ls_attendee TYPE attendee, lv_op_level TYPE numc2, lv_com_level TYPE numc2, lv_generation TYPE numc3, lv_info TYPE text40, lv_icon TYPE icon_d. TRY. mr_attendees->get_attendee( EXPORTING iv_pos_x = iv_pos_x iv_pos_y = iv_pos_y IMPORTING es_attendee = ls_attendee ). CATCH lcx_error. RETURN. ENDTRY. lv_op_level = ls_attendee-open. lv_com_level = ls_attendee-comm. lv_info = 'OP: &1, COM: &2'. SHIFT lv_op_level LEFT DELETING LEADING '0'. REPLACE '&1' IN lv_info WITH lv_op_level. SHIFT lv_com_level LEFT DELETING LEADING '0'. REPLACE '&2' IN lv_info WITH lv_com_level. IF ls_attendee-generation <> 0. lv_generation = ls_attendee-generation. SHIFT lv_generation LEFT DELETING LEADING '0'. CONCATENATE lv_info ', GEN: &1' INTO lv_info. REPLACE '&1' IN lv_info WITH lv_generation. ENDIF. IF ls_attendee-origin = abap_true. lv_icon = icon_helpassistent_on. ELSE. IF ls_attendee-adopted = abap_true. lv_icon = icon_customer. ELSE. lv_icon = icon_hr_position. ENDIF. ENDIF. CALL FUNCTION 'ICON_CREATE' EXPORTING name = lv_icon text = space info = lv_info add_stdinf = space IMPORTING result = ev_tooltip EXCEPTIONS icon_not_found = 1 outputfield_too_short = 2 OTHERS = 3. IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE i499(sy) WITH 'Tooltip not generated.'. ENDIF. ENDMETHOD. METHOD refresh. DATA: ls_stable TYPE lvc_s_stbl, lt_attendees TYPE TABLE OF attendee, ls_attendee LIKE LINE OF lt_attendees, ls_line TYPE REF TO data, lv_position TYPE numc2, lv_field_name TYPE lvc_fname, ls_cell_color TYPE lvc_s_scol, lt_cell_color TYPE lvc_t_scol, ls_color TYPE lvc_s_colo, lt_color TYPE lvc_t_scol. FIELD-SYMBOLS: TYPE STANDARD TABLE, TYPE any, TYPE any. IF mr_reference IS NOT BOUND. RETURN. ENDIF. mr_attendees->get_all_attendees( IMPORTING et_attendees = lt_attendees ). ASSIGN mr_fields->* TO . IF sy-subrc <> 0. RETURN. ENDIF. CREATE DATA ls_line LIKE LINE OF . ASSIGN ls_line->* TO . IF sy-subrc <> 0. RETURN. ENDIF. LOOP AT ASSIGNING . "" every row CLEAR lt_cell_color. DO mr_simulation->mv_pos_max_x TIMES. "" every column lv_position = sy-index. CLEAR ls_attendee. CONCATENATE 'NUMBER-' lv_position INTO lv_field_name. ASSIGN COMPONENT lv_field_name OF STRUCTURE TO . IF sy-subrc = 0. READ TABLE lt_attendees INTO ls_attendee WITH KEY number = . IF sy-subrc = 0 AND ls_attendee-adopted = abap_true. CONCATENATE 'ICON-' lv_position INTO lv_field_name. ASSIGN COMPONENT lv_field_name OF STRUCTURE TO . IF sy-subrc = 0. TRY. = generate_tooltip( EXPORTING iv_pos_x = ls_attendee-pos_x iv_pos_y = ls_attendee-pos_y ). CATCH lcx_error. RETURN. ENDTRY. "" set background color ASSIGN COMPONENT 'COLOR' OF STRUCTURE TO . IF sy-subrc = 0. CLEAR: ls_cell_color, ls_color. IF ls_attendee-generation > 0 AND ls_attendee-generation <= mr_simulation->mv_treshold_green. ls_color-col = 5. ELSEIF ls_attendee-generation > mr_simulation->mv_treshold_green AND ls_attendee-generation <= mr_simulation->mv_treshold_orange. ls_color-col = 7. ELSEIF ls_attendee-generation >= mr_simulation->mv_treshold_red. ls_color-col = 6. ENDIF. ls_color-int = 1. ls_color-inv = 1. ls_cell_color-color = ls_color. CONCATENATE 'ICON-' lv_position INTO ls_cell_color-fname. APPEND ls_cell_color TO lt_cell_color. = lt_cell_color. ENDIF. ENDIF. ENDIF. ENDIF. ENDDO. ENDLOOP. ls_stable-col = abap_true. ls_stable-row = abap_true. CALL METHOD mr_reference->refresh_table_display EXPORTING is_stable = ls_stable i_soft_refresh = abap_false EXCEPTIONS finished = 1 OTHERS = 2. IF sy-subrc <> 0. RETURN. ENDIF. "" this part is needed to refresh information at top and bottom level CALL METHOD cl_gui_cfw=>set_new_ok_code EXPORTING new_code = '&IC1'. cl_gui_cfw=>flush( ). ENDMETHOD. METHOD prepare_field_catalog. DATA: ls_field_catalog TYPE lvc_s_fcat, lv_position TYPE numc2. DO mr_simulation->mv_pos_max_x TIMES. lv_position = sy-index. CLEAR ls_field_catalog. CONCATENATE 'ICON-' lv_position INTO ls_field_catalog-fieldname. ls_field_catalog-col_pos = lv_position. ls_field_catalog-intlen = 45. ls_field_catalog-inttype = 'C'. ls_field_catalog-outputlen = 4. ls_field_catalog-scrtext_s = space. ls_field_catalog-scrtext_m = space. ls_field_catalog-scrtext_l = space. ls_field_catalog-icon = abap_true. ls_field_catalog-col_opt = abap_true. APPEND ls_field_catalog TO mt_field_catalog. CLEAR ls_field_catalog. CONCATENATE 'NUMBER-' lv_position INTO ls_field_catalog-fieldname. ls_field_catalog-col_pos = lv_position. ls_field_catalog-no_out = abap_true. ls_field_catalog-datatype = 'TEXT10'. ls_field_catalog-inttype = 'C'. ls_field_catalog-intlen = 10. APPEND ls_field_catalog TO mt_field_catalog. ENDDO. CLEAR ls_field_catalog. ls_field_catalog-col_pos = lv_position + 1. ls_field_catalog-fieldname = 'COLOR'. ls_field_catalog-ref_field = 'TABCOL'. ls_field_catalog-ref_table = 'BAL_S_SHOW_COL'. ls_field_catalog-tech = abap_true. ls_field_catalog-no_out = abap_true. APPEND ls_field_catalog TO mt_field_catalog. ENDMETHOD. METHOD set_reference. mr_reference = iv_reference. ENDMETHOD. METHOD display. DATA: ls_layout TYPE lvc_s_layo, lt_events TYPE slis_t_event, lt_evexit TYPE slis_t_event_exit, ls_evexit TYPE slis_event_exit, lt_excl TYPE slis_t_extab, lv_cbpfs TYPE slis_formname, ls_line TYPE REF TO data, lv_number TYPE numc5, lv_fname TYPE lvc_fname, lv_count TYPE numc10, lv_text TYPE natxt. FIELD-SYMBOLS: TYPE STANDARD TABLE, TYPE slis_alv_event. ls_layout-ctab_fname = 'COLOR'. ls_layout-stylefname = 'STYLE'. ls_layout-col_opt = abap_true. ls_layout-sel_mode = 'D'. CALL FUNCTION 'REUSE_ALV_EVENTS_GET' EXPORTING i_list_type = 4 IMPORTING et_events = lt_events EXCEPTIONS list_type_wrong = 1 OTHERS = 2. IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE i499(sy) WITH 'Playing field could not be displayed.'. ENDIF. LOOP AT lt_events ASSIGNING . CASE -name. WHEN 'CALLER_EXIT'. -form = 'ALV_CALLER_EXIT'. WHEN 'END_OF_LIST'. -form = 'ALV_END_OF_LIST_2'. WHEN OTHERS. ENDCASE. ENDLOOP. ls_evexit-ucomm = '&INFO'. ls_evexit-after = 'X'. APPEND ls_evexit TO lt_evexit. ASSIGN mr_fields->* TO . IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE i499(sy) WITH 'Playing field could not be displayed.'. ENDIF. CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY_LVC' EXPORTING i_interface_check = ' ' i_bypassing_buffer = abap_true * i_buffer_active = i_callback_program = sy-repid * i_callback_pf_status_set = ' ' i_callback_user_command = 'ALV_USER_COMMAND' * i_callback_top_of_page = ' ' i_callback_html_top_of_page = 'ALV_TOP_OF_PAGE' i_callback_html_end_of_list = 'ALV_END_OF_LIST' * i_structure_name = * i_background_id = ' ' * i_grid_title = ' ' * i_grid_settings = is_layout_lvc = ls_layout it_fieldcat_lvc = mt_field_catalog * it_excluding = lt_excl * it_special_groups_lvc = * it_sort_lvc = * it_filter_lvc = * it_hyperlink = * is_sel_hide = i_default = abap_true * i_save = ' ' * is_variant = it_events = lt_events it_event_exit = lt_evexit * is_print_lvc = * is_reprep_id_lvc = * i_screen_start_column = 0 * i_screen_start_line = 0 * i_screen_end_column = 0 * i_screen_end_line = 0 * i_html_height_top = * i_html_height_end = * it_alv_graphics = * it_except_qinfo_lvc = * ir_salv_fullscreen_adapter = * IMPORTING * e_exit_caused_by_caller = * es_exit_caused_by_user = TABLES t_outtab = EXCEPTIONS program_error = 1 OTHERS = 2. IF sy-subrc <> 0. RAISE EXCEPTION TYPE lcx_error MESSAGE i499(sy) WITH 'Playing field could not be displayed.'. ENDIF. ENDMETHOD. ENDCLASS. ********************************************************************** CLASS lcl_simulation IMPLEMENTATION. METHOD constructor. DATA: lv_count_attendees TYPE i, lr_random_int TYPE REF TO cl_abap_random_int. mv_pos_max_x = iv_max_x. mv_pos_max_y = iv_max_y. mv_treshold_green = iv_treshold_green. mv_treshold_orange = iv_treshold_orange. mv_treshold_red = iv_treshold_red. CREATE OBJECT mr_protocol. mv_count_attendees = iv_max_x * iv_max_y. "" attendee with innovation included lr_random_int = cl_abap_random_int=>create( seed = cl_abap_random=>seed( ) min = 1 max = mv_pos_max_x ). mv_start_pos_x = lr_random_int->get_next( ). lr_random_int = cl_abap_random_int=>create( seed = cl_abap_random=>seed( ) min = 1 max = mv_pos_max_y ). mv_start_pos_y = lr_random_int->get_next( ). TRY. CREATE OBJECT mr_attendees EXPORTING ir_simulation = me. CREATE OBJECT mr_timer. SET HANDLER handle_timer_finished FOR mr_timer. mr_timer->interval = 1. mr_timer->run( ). CREATE OBJECT mr_playing_field EXPORTING ir_simulation = me ir_attendees = mr_attendees. CATCH lcx_error. ENDTRY. ENDMETHOD. METHOD check_innovation_adoption. DATA: lr_random_int TYPE REF TO cl_abap_random_int, lv_attendee_comm TYPE i, lv_neighbour_comm TYPE i, lv_open_minded TYPE i, lv_text TYPE sdydo_text_element, lv_number TYPE numc3, ls_neighbourhood LIKE LINE OF it_neighbourhood. FIELD-SYMBOLS LIKE LINE OF it_neighbourhood. lr_random_int = cl_abap_random_int=>create( seed = cl_abap_random=>seed( ) min = 1 max = 100 ). "" consider only neighbours who already adopted the innovation LOOP AT it_neighbourhood INTO ls_neighbourhood WHERE adopted = abap_true. "" check if attendee will communicate with neighbour lv_attendee_comm = lr_random_int->get_next( ). IF lv_attendee_comm > is_attendee-comm. CONTINUE. ENDIF. "" check if neighbour will communicate with attendee lv_neighbour_comm = lr_random_int->get_next( ). IF lv_neighbour_comm > ls_neighbourhood-comm. CONTINUE. ENDIF. "" check if innovation is adopted by attendee lv_open_minded = lr_random_int->get_next( ). IF lv_open_minded <= is_attendee-open. ev_adopted = abap_true. EXIT. ENDIF. ENDLOOP. IF ev_adopted = abap_true. lv_text = 'Attendee &1 adopted the innovation from &2 (COM attendee: &3/&4, COM neighbour: &5/&6, OP: &7/&8).'. REPLACE '&1' IN lv_text WITH is_attendee-number. REPLACE '&2' IN lv_text WITH ls_neighbourhood-number. lv_number = lv_attendee_comm. SHIFT lv_number LEFT DELETING LEADING '0'. REPLACE '&3' IN lv_text WITH lv_number. lv_number = is_attendee-comm. SHIFT lv_number LEFT DELETING LEADING '0'. REPLACE '&4' IN lv_text WITH lv_number. lv_number = lv_neighbour_comm. SHIFT lv_number LEFT DELETING LEADING '0'. REPLACE '&5' IN lv_text WITH lv_number. lv_number = ls_neighbourhood-comm. SHIFT lv_number LEFT DELETING LEADING '0'. REPLACE '&6' IN lv_text WITH lv_number. lv_number = lv_open_minded. SHIFT lv_number LEFT DELETING LEADING '0'. REPLACE '&7' IN lv_text WITH lv_number. lv_number = is_attendee-open. SHIFT lv_number LEFT DELETING LEADING '0'. REPLACE '&8' IN lv_text WITH lv_number. mr_protocol->add_entry( iv_generation = mv_count_generation iv_text = lv_text ). ENDIF. ENDMETHOD. METHOD create_new_generation. DATA: lv_pos_x TYPE i, lv_pos_y TYPE i, lt_attendees TYPE attendees, ls_attendee TYPE attendee, lt_adopted TYPE attendees. FIELD-SYMBOLS TYPE attendee. mv_count_generation = mv_count_generation + 1. DO mv_pos_max_y TIMES. "" every row lv_pos_y = sy-index. DO mv_pos_max_x TIMES. "" every column lv_pos_x = sy-index. CLEAR: lt_attendees, ls_attendee. mr_attendees->get_attendee( EXPORTING iv_pos_x = lv_pos_x iv_pos_y = lv_pos_y IMPORTING es_attendee = ls_attendee ). IF ls_attendee-adopted = abap_true. CONTINUE. ENDIF. mr_attendees->get_neighbourhood( EXPORTING iv_pos_x = lv_pos_x iv_pos_y = lv_pos_y IMPORTING et_attendees = lt_attendees ). me->check_innovation_adoption( EXPORTING is_attendee = ls_attendee it_neighbourhood = lt_attendees IMPORTING ev_adopted = ls_attendee-adopted ). IF ls_attendee-adopted = abap_true. APPEND ls_attendee TO lt_adopted. mv_count_adoption = mv_count_adoption + 1. ENDIF. ENDDO. ENDDO. LOOP AT lt_adopted ASSIGNING . mr_attendees->set_attendee_adopted( EXPORTING iv_pos_x = -pos_x iv_pos_y = -pos_y iv_generation = mv_count_generation ). ENDLOOP. mv_count_left = mv_count_attendees - ( mv_count_adoption + 1 ). ENDMETHOD. METHOD handle_timer_finished. TRY. me->create_new_generation( ). mr_playing_field->refresh( ). CATCH lcx_error. RETURN. ENDTRY. IF mv_count_left <> 0. mr_timer->run( ). ELSE. MESSAGE 'Simulation finished.' TYPE 'I'. ENDIF. ENDMETHOD. METHOD handle_context_menu_request. CALL METHOD e_object->add_separator. CALL METHOD e_object->add_function EXPORTING fcode = '&PAUSE' text = 'Pause simulation' icon = icon_system_copy. * ftype = * disabled = * hidden = * checked = * accelerator = * insert_at_the_top = SPACE CALL METHOD e_object->add_function EXPORTING fcode = '&CONTINUE' text = 'Continue simulation' icon = icon_system_copy. * ftype = * disabled = * hidden = * checked = * accelerator = * insert_at_the_top = SPACE ENDMETHOD. METHOD set_playfield_reference. mr_playing_field->set_reference( iv_reference ). ENDMETHOD. METHOD start_simulation. TRY. mr_playing_field->display( ). CATCH lcx_error. RETURN. ENDTRY. ENDMETHOD. METHOD reset_timer. mr_timer->cancel( ). ENDMETHOD. METHOD restart_timer. mr_timer->cancel( ). mr_timer->run( ). ENDMETHOD. ENDCLASS. ********************************************************************** INITIALIZATION. PERFORM initialize. START-OF-SELECTION. PERFORM start_simulation. ********************************************************************** FORM start_simulation. DATA: lr_error TYPE REF TO lcx_error, lv_message TYPE string. TRY. CREATE OBJECT gr_simulation EXPORTING iv_max_x = pa_max_x iv_max_y = pa_max_y iv_treshold_green = pa_thgrn iv_treshold_orange = pa_thorg iv_treshold_red = pa_thred. CATCH lcx_error INTO lr_error. lr_error->get_text( ). ENDTRY. IF gr_simulation IS BOUND. gr_simulation->start_simulation( ). ENDIF. ENDFORM. FORM alv_caller_exit USING us_data TYPE slis_data_caller_exit. DATA lr_grid TYPE REF TO cl_gui_alv_grid. sy-title = 'Simulation ""distribution of an innovation"" based on cellular automaton'. CALL FUNCTION 'GET_GLOBALS_FROM_SLVC_FULLSCR' * EXPORTING * ir_salv_fullscreen_adapter = IMPORTING * et_excluding = * e_repid = * e_callback_program = * e_callback_routine = e_grid = lr_grid. * et_fieldcat_lvc = * er_trace = * e_flg_no_html = * es_layout_kkblo = * es_sel_hide = * et_event_exit = * er_form_tol = * er_form_eol = IF lr_grid IS NOT BOUND. RETURN. ENDIF. gr_simulation->set_playfield_reference( lr_grid ). SET HANDLER gr_simulation->handle_context_menu_request FOR lr_grid. ENDFORM. FORM alv_user_command USING uv_ucomm TYPE syucomm us_selfield TYPE slis_selfield. IF uv_ucomm = '&IC1' OR uv_ucomm = '&CONTINUE'. IF uv_ucomm = '&CONTINUE'. MESSAGE 'Simulation continued.' TYPE 'S'. ENDIF. "" we need to restart our timer IF gr_simulation->mv_count_left > 0. gr_simulation->restart_timer( ). ENDIF. ELSE. "" timer is automatically deactivated MESSAGE 'Simulation paused.' TYPE 'S'. gr_simulation->reset_timer( ). ENDIF. ENDFORM. FORM alv_top_of_page USING ur_doc TYPE REF TO cl_dd_document. DATA: lv_count_generation TYPE numc5, lv_count_attendees TYPE numc5, lv_count_adoption TYPE numc5, lv_count_left TYPE numc5, lv_text TYPE sdydo_text_element. lv_count_attendees = gr_simulation->mv_count_attendees. SHIFT lv_count_attendees LEFT DELETING LEADING '0'. CONCATENATE 'Number of attendees: ' lv_count_attendees INTO lv_text SEPARATED BY space. CALL METHOD ur_doc->add_text EXPORTING text = lv_text * text_table = * fix_lines = * sap_style = * sap_color = sap_fontsize = cl_dd_area=>medium * sap_fontstyle = sap_emphasis = cl_dd_area=>strong. * style_class = * a11y_tooltip = * CHANGING * document = CALL METHOD ur_doc->new_line. * EXPORTING * repeat = CLEAR lv_text. lv_count_adoption = gr_simulation->mv_count_adoption. SHIFT lv_count_adoption LEFT DELETING LEADING '0'. IF lv_count_adoption = space. lv_text = 'Number of adoption: 0'. ELSE. CONCATENATE 'Number of adoption: ' lv_count_adoption INTO lv_text SEPARATED BY space. ENDIF. CALL METHOD ur_doc->add_text EXPORTING text = lv_text * text_table = * fix_lines = * sap_style = * sap_color = sap_fontsize = cl_dd_area=>medium * sap_fontstyle = sap_emphasis = cl_dd_area=>strong. * style_class = * a11y_tooltip = * CHANGING * document = CALL METHOD ur_doc->new_line. * EXPORTING * repeat = CLEAR lv_text. lv_count_left = gr_simulation->mv_count_left. SHIFT lv_count_left LEFT DELETING LEADING '0'. IF lv_count_left = space. lv_text = 'Left: 0'. ELSE. CONCATENATE 'Left: ' lv_count_left INTO lv_text SEPARATED BY space. ENDIF. CALL METHOD ur_doc->add_text EXPORTING text = lv_text * text_table = * fix_lines = * sap_style = * sap_color = sap_fontsize = cl_dd_area=>medium * sap_fontstyle = sap_emphasis = cl_dd_area=>strong. * style_class = * a11y_tooltip = * CHANGING * document = CALL METHOD ur_doc->new_line. * EXPORTING * repeat = CLEAR lv_text. lv_count_generation = gr_simulation->mv_count_generation. SHIFT lv_count_generation LEFT DELETING LEADING '0'. IF lv_count_generation = space. lv_text = 'Generation: 0'. ELSE. CONCATENATE 'Generation: ' lv_count_generation INTO lv_text SEPARATED BY space. ENDIF. CALL METHOD ur_doc->add_text EXPORTING text = lv_text * text_table = * fix_lines = * sap_style = * sap_color = sap_fontsize = cl_dd_area=>medium * sap_fontstyle = sap_emphasis = cl_dd_area=>strong. * style_class = * a11y_tooltip = * CHANGING * document = ENDFORM. FORM alv_end_of_list USING ur_doc TYPE REF TO cl_dd_document. DATA: lv_generation TYPE i, lv_number TYPE numc5, lt_protocol_entries TYPE protocol_entries, ls_protocol_entry LIKE LINE OF lt_protocol_entries, lv_text TYPE sdydo_text_element. "" protocol per generation below playing field lv_generation = gr_simulation->mv_count_generation. IF lv_generation = 0. RETURN. ENDIF. gr_simulation->mr_protocol->get_entries_per_generation( EXPORTING iv_generation = lv_generation IMPORTING et_entries = lt_protocol_entries ). lv_number = lv_generation. SHIFT lv_number LEFT DELETING LEADING '0'. lv_text = 'Generation &1 reached.'. REPLACE '&1' IN lv_text WITH lv_number. CALL METHOD ur_doc->add_text EXPORTING text = lv_text * text_table = * fix_lines = * sap_style = * sap_color = * sap_fontsize = * sap_fontstyle = sap_emphasis = cl_dd_area=>strong. * style_class = * a11y_tooltip = * CHANGING * document = CALL METHOD ur_doc->new_line. * EXPORTING * repeat = LOOP AT lt_protocol_entries INTO ls_protocol_entry. CALL METHOD ur_doc->add_text EXPORTING text = ls_protocol_entry-text * text_table = * fix_lines = * sap_style = * sap_color = sap_fontsize = cl_dd_area=>medium. * sap_fontstyle = * sap_emphasis = * style_class = * a11y_tooltip = * CHANGING * document = CALL METHOD ur_doc->new_line. * EXPORTING * repeat = ENDLOOP. ENDFORM. FORM initialize. sy-title = 'Simulation ""distribution of an innovation"" based on cellular automaton'. title_01 = 'Description'. title_02 = 'Parameters'. text_000 = 'The report demonstrate the use of cellular automaton to show how an innovation'. text_001 = 'is adopted by every member of a crowd.'. text_002 = 'Playfield max. X-Axis'. text_003 = 'Playfield max. Y-Axis'. text_004 = 'Treshold green'. text_005 = 'Treshold orange'. text_006 = 'Treshold red'. ENDFORM. ",10234,False,1875.9345427955088,median "//============================================================================== /* Software License Agreement (BSD License) Copyright (c) 2003-2016, CHAI3D. (www.chai3d.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: * 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 CHAI3D 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 \\author Francois Conti \\author Dan Morris \\version 3.2.0 $Rev: 2158 $ */ //============================================================================== //------------------------------------------------------------------------------ #include ""world/CGenericObject.h"" #include ""collisions/CGenericCollision.h"" #include ""math/CMaths.h"" #include ""graphics/CDraw3D.h"" #include ""effects/CEffectMagnet.h"" #include ""effects/CEffectStickSlip.h"" #include ""effects/CEffectSurface.h"" #include ""effects/CEffectVibration.h"" #include ""effects/CEffectViscosity.h"" #include ""shaders/CShaderProgram.h"" //------------------------------------------------------------------------------ #include #include //------------------------------------------------------------------------------ using namespace std; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace chai3d { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ cMaterialPtr cGenericObject::s_defaultMaterial = nullptr; cColorf cGenericObject::s_boundaryBoxColor(0.7f, 0.7f, 0.7f); //------------------------------------------------------------------------------ //============================================================================== /*! Constructor of cGenericObject. */ //============================================================================== cGenericObject::cGenericObject() { // object is enabled m_enabled = true; // initialize local position and orientation m_localPos.zero(); m_localRot.identity(); // initialize global position and orientation m_globalPos.zero(); m_globalRot.identity(); m_prevGlobalPos.zero(); m_prevGlobalRot.identity(); // initialize OpenGL matrix with position vector and orientation matrix m_frameGL.set(m_globalPos, m_globalRot); // initialize name m_name = """"; // custom user information m_userName = """"; m_userTag = 0; m_userData = NULL; m_userExternalObject = NULL; // initialize shared default material if necessary if (s_defaultMaterial == nullptr) s_defaultMaterial = cMaterial::create(); // should we use the material property? m_useMaterialProperty = true; // are vertex colors used during rendering process? m_useVertexColors = false; // should transparency be used? m_useTransparency = false; // should texture mapping be used if a texture is defined? m_useTextureMapping = false; // how are triangles displayed; FILL or LINE ? m_triangleMode = GL_FILL; // initialize texture m_texture = nullptr; // initialize normal map m_normalMap = nullptr; // turn off culling on by default m_cullingEnabled = false; // disable ghost setting m_ghostEnabled = false; // no external parent defined m_owner = this; // no parent defined m_parent = NULL; // object is not interacting with any tool m_interactionInside = false; m_interactionPoint.zero(); m_interactionNormal.set(1,0,0); // empty list of haptic effects m_effects.clear(); // setup default material m_material = s_defaultMaterial; // enable graphic rendering m_showEnabled = true; // enable haptic rendering m_hapticEnabled = true; // reference frame m_showFrame = false; setFrameSize(0.2); // boundary box m_showBoundaryBox = false; m_boundaryBoxMin.set(0.0, 0.0, 0.0); m_boundaryBoxMax.set(0.0, 0.0, 0.0); m_boundaryBoxEmpty = true; // collision detector m_collisionDetector = NULL; m_showCollisionDetector = false; // display list m_useDisplayList = false; } //============================================================================== /*! Destructor of cGenericObject. \\n Deletes all children starting from this point in the scene graph, so if you have objects that shouldn't be deleted, be sure to remove them from the scene graph before deleting their parents. */ //============================================================================== cGenericObject::~cGenericObject() { // delete collision detector deleteCollisionDetector(false); // delete all haptics effects deleteAllEffects(); // delete all children deleteAllChildren(); } //============================================================================== /*! This method enables or disables this object.\\n When an object is disabled, haptic and graphic rendering are no longer performed through the scenegraph and the object is simply ignored. Other operations however will still be active. \\n Enabling or disabling an object will not affect child objects, unless explicitly specified. \\param a_enabled If __true__ then object is enabled, __false__ otherwise. \\param a_affectChildren If __true__, then children are updated too. */ //============================================================================== void cGenericObject::setEnabled(bool a_enabled, const bool a_affectChildren) { m_enabled = a_enabled; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setEnabled(a_enabled, true); } } } //============================================================================== /*! This method translate this object by a specified offset passed as argument. \\param a_translation Translation offset. */ //============================================================================== void cGenericObject::translate(const cVector3d& a_translation) { cVector3d localPos = cAdd(m_localPos, a_translation); setLocalPos(localPos); } //============================================================================== /*! This method translates an object by a specified offset passed as argument. \\param a_x Translation component X. \\param a_y Translation component Y. \\param a_z Translation component Z. */ //============================================================================== void cGenericObject::translate(const double a_x, const double a_y, const double a_z) { translate(cVector3d(a_x,a_y,a_z)); } //============================================================================== /*! This method rotates this object around a specified rotation axis and angle. The axis is expressed in local coordinates. \\param a_axis Rotation axis. This vector must be normalized! \\param a_angleRad Rotation angle in defined in __radians__. */ //============================================================================== void cGenericObject::rotateAboutLocalAxisRad(const cVector3d& a_axis, const double a_angleRad) { cMatrix3d rot = m_localRot; rot.rotateAboutLocalAxisRad(a_axis, a_angleRad); setLocalRot(rot); } //============================================================================== /*! This method rotates this object around a specified rotation axis and angle. The axis is expressed in global coordinates. \\param a_axis Rotation axis. This vector must be normalized! \\param a_angleRad Rotation angle in defined in __radians__. */ //============================================================================== void cGenericObject::rotateAboutGlobalAxisRad(const cVector3d& a_axis, const double a_angleRad) { cMatrix3d rot = m_localRot; rot.rotateAboutGlobalAxisRad(a_axis, a_angleRad); setLocalRot(rot); } //============================================================================== /*! This method builds a rotation matrix from a set of Euler angles and fixed axes of rotations. \\param a_angleRad1 Angle in radians of the first rotation in the sequence. \\param a_angleRad2 Angle in radians of the second rotation in the sequence. \\param a_angleRad3 Angle in radians of the third rotation in the sequence. \\param a_eulerOrder The order of the axes about which the rotations are to be applied */ //============================================================================== void cGenericObject::rotateExtrinsicEulerAnglesRad(const double& a_angleRad1, const double& a_angleRad2, const double& a_angleRad3, const cEulerOrder a_eulerOrder) { cMatrix3d rot = m_localRot; rot.setExtrinsicEulerRotationRad(a_angleRad1, a_angleRad2, a_angleRad3, a_eulerOrder); setLocalRot(rot); } //============================================================================== /*! This method builds a rotation matrix from a set of Euler angles and co-moving axes of rotations. \\param a_angleRad1 Angle in radians of the first rotation in the sequence. \\param a_angleRad2 Angle in radians of the second rotation in the sequence. \\param a_angleRad3 Angle in radians of the third rotation in the sequence. \\param a_eulerOrder The order of the axes about which the rotations are to be applied. */ //============================================================================== void cGenericObject::rotateIntrinsicEulerAnglesRad(const double& a_angleRad1, const double& a_angleRad2, const double& a_angleRad3, const cEulerOrder a_eulerOrder) { cMatrix3d rot = m_localRot; rot.setIntrinsicEulerRotationRad(a_angleRad1, a_angleRad2, a_angleRad3, a_eulerOrder); setLocalRot(rot); } //============================================================================== /*! This method computes the global position and global rotation matrix given the local position and location rotation of this object, and the global configuration of its parent. \\n If \\a a_frameOnly is set to __false__, additional global positions such as vertex positions are computed too (which may be time-consuming!). \\n \\param a_frameOnly If __true__ then only the global frame is computed \\param a_globalPos Global position of parent object. \\param a_globalRot Global rotation matrix of parent object. */ //============================================================================== void cGenericObject::computeGlobalPositions(const bool a_frameOnly, const cVector3d& a_globalPos, const cMatrix3d& a_globalRot) { // check if node is a ghost. If yes, then ignore call if (m_ghostEnabled) { return; } // current values become previous values m_prevGlobalPos = m_globalPos; m_prevGlobalRot = m_globalRot; // update global position vector and global rotation matrix m_globalPos = cAdd(a_globalPos, cMul(a_globalRot, m_localPos)); m_globalRot = cMul(a_globalRot, m_localRot); // update any positions within the current object that need to be // updated (e.g. vertex positions) updateGlobalPositions(a_frameOnly); // propagate this method to my children vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->computeGlobalPositions(a_frameOnly, m_globalPos, m_globalRot); } } //============================================================================== /*! This method computes the global position and global rotation for this object only, by recursively climbing up the scene graph tree until the root is reached. If argument \\p a_frameOnly is set to __false__, additional global positions such as vertex positions are computed. \\param a_frameOnly If __true__ then only the global frame is computed. */ //============================================================================== void cGenericObject::computeGlobalPositionsFromRoot(const bool a_frameOnly) { cMatrix3d globalRot; cVector3d globalPos; globalRot.identity(); globalPos.zero(); // get a pointer to current object cGenericObject *curObject = getParent(); if (curObject != NULL) { // walk up the scene graph until we reach the root, updating // my global position and rotation at each step do { curObject->getLocalRot().mul(globalPos); globalPos.add(curObject->getLocalPos()); cMatrix3d rot; curObject->getLocalRot().mulr(globalRot, rot); rot.copyto(globalRot); curObject = curObject->getParent(); } while (curObject != NULL); } // compute global positions for current object and child computeGlobalPositions(a_frameOnly, globalPos, globalRot); } //============================================================================== /*! This method adds a haptic effect to this object. \\param a_effect Haptic effect to be added to the list. */ //============================================================================== bool cGenericObject::addEffect(cGenericEffect* a_effect) { if (a_effect->m_parent != this) { return (false); } // update the effect object's parent pointer a_effect->m_parent = this; // add this child to my list of children m_effects.push_back(a_effect); // success return (true); } //============================================================================== /*! This method removes a haptic effect from this object. \\param a_effect Haptic effect to be removed from the list of effects. */ //============================================================================== bool cGenericObject::removeEffect(cGenericEffect* a_effect) { // find haptic effect and remove it from list vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { if ((*it) == a_effect) { (*it)->m_parent = NULL; m_effects.erase(it); return (true); } } // operation failed return (false); } //============================================================================== /*! This method deletes all haptic effects and removes them from the list. */ //============================================================================== void cGenericObject::deleteAllEffects() { vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { delete (*it); } m_effects.clear(); } //============================================================================== /*! This method creates a magnetic haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::createEffectMagnetic() { bool flag = true; vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { if (dynamic_cast(*it) != NULL) { flag = false; } } if (flag) { cGenericEffect* effect = new cEffectMagnet(this); addEffect(effect); return (true); } return (false); } //============================================================================== /*! This method deletes the magnetic haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::deleteEffectMagnetic() { vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { cGenericEffect* effect = dynamic_cast(*it); if (effect != NULL) { m_effects.erase(it); delete effect; return (true); } } return (false); } //============================================================================== /*! This method creates a stick-and-slip haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::createEffectStickSlip() { bool flag = true; vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { if (dynamic_cast(*it) != NULL) { flag = false; } } if (flag) { cGenericEffect* effect = new cEffectStickSlip(this); addEffect(effect); return (true); } return (false); } //============================================================================== /*! This method deletes the stick-and-slip haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::deleteEffectStickSlip() { vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { cGenericEffect* effect = dynamic_cast(*it); if (effect != NULL) { m_effects.erase(it); delete effect; return (true); } } return (false); } //============================================================================== /*! This method creates a surface haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::createEffectSurface() { bool flag = true; vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { if (dynamic_cast(*it) != NULL) { flag = false; } } if (flag) { cGenericEffect* effect = new cEffectSurface(this); addEffect(effect); return (true); } return (false); } //============================================================================== /*! This method deletes the surface haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::deleteEffectSurface() { vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { cGenericEffect* effect = dynamic_cast(*it); if (effect != NULL) { m_effects.erase(it); delete effect; return (true); } } return (false); } //============================================================================== /*! This method creates a vibration haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::createEffectVibration() { bool flag = true; vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { if (dynamic_cast(*it) != NULL) { flag = false; } } if (flag) { cGenericEffect* effect = new cEffectVibration(this); addEffect(effect); return (true); } return (false); } //============================================================================== /*! This method deletes the current vibration haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::deleteEffectVibration() { vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { cGenericEffect* effect = dynamic_cast(*it); if (effect != NULL) { m_effects.erase(it); delete effect; return (true); } } return (false); } //============================================================================== /*! This method creates a viscous haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::createEffectViscosity() { bool flag = true; vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { if (dynamic_cast(*it) != NULL) { flag = false; } } if (flag) { cGenericEffect* effect = new cEffectViscosity(this); addEffect(effect); return (true); } return (false); } //============================================================================== /*! This method deletes the current viscous haptic effect. \\return __true__ if the operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::deleteEffectViscosity() { vector::iterator it; for (it = m_effects.begin(); it < m_effects.end(); it++) { cGenericEffect* effect = dynamic_cast(*it); if (effect != NULL) { m_effects.erase(it); delete effect; return (true); } } return (false); } //============================================================================== /*! This method enables or disables the object to be felt haptically. \\n If argument \\p a_affectChildren is set to __true__ then all children are updated with the new value. \\param a_hapticEnabled If __true__ then the object can be touched when visible. \\param a_affectChildren If __true__ then all children are updated too. */ //============================================================================== void cGenericObject::setHapticEnabled(const bool a_hapticEnabled, const bool a_affectChildren) { m_hapticEnabled = a_hapticEnabled; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setHapticEnabled(a_hapticEnabled, true); } } } //============================================================================== /*! This method sets the haptic stiffness for this object, optionally recursively affecting children. \\param a_stiffness The stiffness to apply to this object. \\param a_affectChildren If __true__, then children are updated too. */ //============================================================================== void cGenericObject::setStiffness(const double a_stiffness, const bool a_affectChildren) { m_material->setStiffness(a_stiffness); // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setStiffness(a_stiffness, true); } } } //============================================================================== /*! This method sets the static and dynamic friction properties for this object, optionally recursively affecting children. \\param a_staticFriction The static friction to apply to this object. \\param a_dynamicFriction The dynamic friction to apply to this object. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setFriction(double a_staticFriction, double a_dynamicFriction, const bool a_affectChildren) { m_material->setStaticFriction(a_staticFriction); m_material->setDynamicFriction(a_dynamicFriction); // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setFriction(a_staticFriction, a_dynamicFriction, true); } } } //============================================================================== /*! This method graphically shows or hides this object, optionally recursively affecting children. \\param a_show If __true__ then object is visible. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setShowEnabled(const bool a_show, const bool a_affectChildren) { // update current object m_showEnabled = a_show; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setShowEnabled(a_show, true); } } } //============================================================================== /*! This method specifies whether transparency is enabled. If transparency is enabled then make sure that multi-pass rendering is enabled too. For more information, see class \\ref cCamera. \\param a_useTransparency If __true__ then transparency is enabled. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setUseTransparency(const bool a_useTransparency, const bool a_affectChildren) { // update changes to object m_useTransparency = a_useTransparency; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setUseTransparency(a_useTransparency, true); } } } //============================================================================== /*! This method sets the alpha value to all components of the object, optionally propagating the operation to children. \\n Using the 'apply to textures' option causes the actual texture alpha values to be over-written in my texture, if it exists. \\n \\param a_level Level of transparency ranging from 0.0 to 1.0. \\param a_applyToTextures If __true__, then apply changes to texture pixels. \\param a_applyToVertices If __true__, then apply changes to vertex colors. \\param a_affectChildren If __true__, then children are updated too. */ //============================================================================== void cGenericObject::setTransparencyLevel(const float a_level, const bool a_applyToVertices, const bool a_applyToTextures, const bool a_affectChildren) { // if the transparency level is equal to 1.0, then do not apply transparency // otherwise enable it. if (a_level < 1.0) { setUseTransparency(true); } else { setUseTransparency(false); } // apply new value to material if (m_material != nullptr) { m_material->setTransparencyLevel(a_level); } // apply new value to texture if (m_texture != nullptr) { if (m_texture->m_image != nullptr) { unsigned char level = (unsigned char)(255.0 * a_level); m_texture->m_image->setTransparency(level); } } // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setTransparencyLevel(a_level, a_applyToVertices, a_applyToTextures, true); } } } //============================================================================== /*! This method enables or disables wireframe rendering, optionally propagating the operation to children. \\param a_showWireMode If __true__ then wireframe mode is used. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setWireMode(const bool a_showWireMode, const bool a_affectChildren) { if (a_showWireMode) { // enable line mode m_triangleMode = GL_LINE; } else { // enable solid mode m_triangleMode = GL_FILL; } // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setWireMode(a_showWireMode, true); } } } //============================================================================== /*! This method enables or disables back face culling. \\n Rendering in OpenGL is much faster with culling enabled. \\param a_useCulling If __true__ then back faces are culled. \\param a_affectChildren If __true__ then then children are updated too. */ //============================================================================== void cGenericObject::setUseCulling(const bool a_useCulling, const bool a_affectChildren) { m_cullingEnabled = a_useCulling; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setUseCulling(a_useCulling, true); } } } //============================================================================== /*! This method enables or disables the use of per-vertex color information of when rendering the mesh. \\param a_useColors If __true__ then then vertex color information is applied. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setUseVertexColors(const bool a_useColors, const bool a_affectChildren) { m_useVertexColors = a_useColors; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setUseVertexColors(a_useColors, true); } } } //============================================================================== /*! This method creates a backup of the material color properties of this object, optionally recursively affecting children. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::backupMaterialColors(const bool a_affectChildren) { // backup colors for current material if ((m_material != nullptr) && (m_material != s_defaultMaterial)) { m_material->backupColors(); } // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->backupMaterialColors(true); } } } //============================================================================== /*! This method restores material color properties for this object, optionally recursively affecting children. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::restoreMaterialColors(const bool a_affectChildren) { // restore original colors for current material if ((m_material != nullptr) && (m_material != s_defaultMaterial)) { m_material->restoreColors(); } // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->restoreMaterialColors(true); } } } //============================================================================== /*! This method enables the use of display lists for mesh rendering. Display lists significantly speed up rendering for large meshes, but it means that any changes that are made on the object (e.g changing vertex positions) will not take effect until you invalidate the existing display list by calling \\ref markForUpdate(). \\param a_useDisplayList If __true__ then a display list is created (cMesh). \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setUseDisplayList(const bool a_useDisplayList, const bool a_affectChildren) { // update changes to object m_useDisplayList = a_useDisplayList; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setUseDisplayList(a_useDisplayList, true); } } } //============================================================================== /*! This method invalidates any existing display lists. You should call this on if you're using display lists and you modify mesh options, vertex positions, etc. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::markForUpdate(const bool a_affectChildren) { // invalidate display list m_displayList.invalidate(); // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->markForUpdate(true); } } } //============================================================================== /*! This method enables or disables the use of material properties. \\param a_useMaterial If __true__ then material properties are used for rendering. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setUseMaterial(const bool a_useMaterial, const bool a_affectChildren) { // update changes to object m_useMaterialProperty = a_useMaterial; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setUseMaterial(a_useMaterial, true); } } } //============================================================================== /*! This method copies all material properties defined in \\p a_material to the material structure of this object.\\n Note that this does not affect whether material rendering is enabled; it sets the material that will be rendered _if_ material rendering is enabled. Call method \\ref setUseMaterial() to enable or disable material rendering. \\param a_material The material to apply to this object. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setMaterial(cMaterialPtr a_material, const bool a_affectChildren) { // copy material properties m_material = a_material; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setMaterial(a_material, true); } } } //============================================================================== /*! This method copies all material properties defined in \\p a_material to the material structure of this object.\\n Note that this does not affect whether material rendering is enabled; it sets the material that will be rendered _if_ material rendering is enabled. Call method \\ref setUseMaterial() to enable or disable material rendering. \\param a_material The material to apply to this object \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setMaterial(cMaterial& a_material, const bool a_affectChildren) { // copy material properties if ((m_material == nullptr) || (m_material == s_defaultMaterial)) { m_material = cMaterial::create(); a_material.copyTo(m_material); } else { a_material.copyTo(m_material); } // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setMaterial(a_material, true); } } } //============================================================================== /*! This method enables or disables texture-mapping, optionally recursively affecting children. \\param a_useTexture If __true__ then texture mapping is used. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setUseTexture(const bool a_useTexture, const bool a_affectChildren) { m_useTextureMapping = a_useTexture; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setUseTexture(a_useTexture, true); } } } //============================================================================== /*! This method sets the current texture for this mesh, optionally recursively affecting children. \\n Note that this does not affect whether texturing is enabled; it sets the texture that will be rendered _if_ texturing is enabled. Call method \\ref setUseTexture() to enable or disable texturing. \\param a_texture The texture to apply to this object. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setTexture(cTexture1dPtr a_texture, const bool a_affectChildren) { m_texture = a_texture; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setTexture(a_texture, true); } } } //============================================================================== /*! This method assigns a shader program to this object. \\n If \\p a_affectChildren is set to __true__ then all children are assigned with the shader program. \\param a_shaderProgram Shader program to be assigned to object. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setShaderProgram(cShaderProgramPtr a_shaderProgram, const bool a_affectChildren) { m_shaderProgram = a_shaderProgram; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setShaderProgram(a_shaderProgram, true); } } } //============================================================================== /*! This method enables or disables the graphic representation of the boundary box of this object. \\n If \\p a_affectChildren is set to __true__ then all children are updated with the new value. \\param a_showBoundaryBox If __true__ boundary box is displayed. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setShowBoundaryBox(const bool a_showBoundaryBox, const bool a_affectChildren) { // update current object m_showBoundaryBox = a_showBoundaryBox; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setShowBoundaryBox(a_showBoundaryBox, true); } } } //============================================================================== /*! This method computes the boundary box of this object and all of its children. If argument \\p a_includeChildren is set to __true__ then each object's bounding box covers its own volume and the volume of its children. If it is set to false, then the object's bounding volume shall only cover its own geometrical elements. \\param a_includeChildren If __true__, then children are included in the boundary volume of the parent. */ //============================================================================== void cGenericObject::computeBoundaryBox(const bool a_includeChildren) { // check if node is a ghost. If yes, then ignore call if (m_ghostEnabled) { return; } // compute the bounding box of this object updateBoundaryBox(); // if children are not included, then we simply propagate the command // recursively so that all children update their bounding box individually. if (a_includeChildren == false) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { cGenericObject* object = (*it); // compute boundary box of child object->computeBoundaryBox(false); } return; } // compute the bounding box of all my children cVector3d minBox, maxBox; if (m_boundaryBoxEmpty) { minBox.set( C_LARGE, C_LARGE, C_LARGE); maxBox.set(-C_LARGE,-C_LARGE,-C_LARGE); } else { minBox = m_boundaryBoxMin; maxBox = m_boundaryBoxMax; } bool empty = true; vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { cGenericObject* object = (*it); // compute boundary box of child object->computeBoundaryBox(a_includeChildren); // if boundary box is not empty, then include update if (!object->getBoundaryBoxEmpty()) { // since child is not empty, parent is no longer empty too. empty = false; // retrieve position and orientation of child. cVector3d pos = object->getLocalPos(); cMatrix3d rot = object->getLocalRot(); // compute position of corners of child within parent reference frame double xMin = object->getBoundaryMin().x(); double yMin = object->getBoundaryMin().y(); double zMin = object->getBoundaryMin().z(); double xMax = object->getBoundaryMax().x(); double yMax = object->getBoundaryMax().y(); double zMax = object->getBoundaryMax().z(); cVector3d corners[8]; corners[0] = pos + rot * cVector3d(xMin, yMin, zMin); corners[1] = pos + rot * cVector3d(xMin, yMin, zMax); corners[2] = pos + rot * cVector3d(xMin, yMax, zMin); corners[3] = pos + rot * cVector3d(xMin, yMax, zMax); corners[4] = pos + rot * cVector3d(xMax, yMin, zMin); corners[5] = pos + rot * cVector3d(xMax, yMin, zMax); corners[6] = pos + rot * cVector3d(xMax, yMax, zMin); corners[7] = pos + rot * cVector3d(xMax, yMax, zMax); // update boundary box by taking into account child boundary box for (int i=0; i<8; i++) { minBox(0) = cMin(corners[i](0), m_boundaryBoxMin(0)); minBox(1) = cMin(corners[i](1), m_boundaryBoxMin(1)); minBox(2) = cMin(corners[i](2), m_boundaryBoxMin(2)); maxBox(0) = cMin(corners[i](0), m_boundaryBoxMax(0)); maxBox(1) = cMin(corners[i](1), m_boundaryBoxMax(1)); maxBox(2) = cMin(corners[i](2), m_boundaryBoxMax(2)); } } } if (empty && m_boundaryBoxEmpty) { m_boundaryBoxMin.zero(); m_boundaryBoxMax.zero(); m_boundaryBoxEmpty = true; } else { m_boundaryBoxMin = minBox; m_boundaryBoxMax = maxBox; m_boundaryBoxEmpty = false; } } //============================================================================== /*! This method enables of disables the display of the reference frame. The reference frame is a set of arrows that represent this object's position and orientation. If argument \\p a_affectChildren is set to __true__ then all children are updated with the new value. \\param a_showFrame If __true__ then frame is displayed. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setShowFrame(const bool a_showFrame, const bool a_affectChildren) { // update current object m_showFrame = a_showFrame; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setShowFrame(a_showFrame, true); } } } //============================================================================== /*! This method sets the display size of the arrows representing my reference frame. The size corresponds to the length of each displayed axis (X-Y-Z). \\n If argument \\p a_affectChildren is set to __true__ then all children are updated with the new value. \\param a_size Length of graphical representation of frame. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setFrameSize(const double a_size, const bool a_affectChildren) { // sanity check m_frameSize = fabs(a_size); m_frameThicknessScale = 1.7 * m_frameSize; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setFrameSize(a_size, true); } } } //============================================================================== /*! This method deletes any existing collision detector and sets the current collision detector to __null__. \\n It's fine for an object to have a null collision detector (that's the default for a new object, in fact), it just means that no collisions will be found. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::deleteCollisionDetector(const bool a_affectChildren) { // delete current collision detector if (m_collisionDetector) { delete m_collisionDetector; m_collisionDetector = NULL; } // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->deleteCollisionDetector(true); } } } //============================================================================== /*! This method determines whether a given segment intersects this object or any of its descendants.\\n The segment is described by a start point \\p a_segmentPointA and end point \\p a_segmentPointB. \\n All detected collisions are reported in the collision recorder passed by argument \\p a_recorder. \\n Specifications about the type of collisions reported are specified by argument \\p a_settings. \\param a_segmentPointA Start point of segment. \\param a_segmentPointB End point of segment. \\param a_recorder Recorder which stores all collision events. \\param a_settings Collision settings information. \\return __true__ if one or more collisions have occurred, __false__ otherwise. */ //============================================================================== bool cGenericObject::computeCollisionDetection(const cVector3d& a_segmentPointA, const cVector3d& a_segmentPointB, cCollisionRecorder& a_recorder, cCollisionSettings& a_settings) { /////////////////////////////////////////////////////////////////////////// // INITIALIZATION /////////////////////////////////////////////////////////////////////////// // check if node is a ghost. If yes, then ignore call if (m_ghostEnabled) { return (false); } // temp variable bool hit = false; // get the transpose of the local rotation matrix cMatrix3d transLocalRot; m_localRot.transr(transLocalRot); // convert first endpoint of the segment into local coordinate frame cVector3d localSegmentPointA = a_segmentPointA; localSegmentPointA.sub(m_localPos); transLocalRot.mul(localSegmentPointA); // convert second endpoint of the segment into local coordinate frame cVector3d localSegmentPointB = a_segmentPointB; localSegmentPointB.sub(m_localPos); transLocalRot.mul(localSegmentPointB); /////////////////////////////////////////////////////////////////////////// // CHECK COLLISIONS /////////////////////////////////////////////////////////////////////////// if ((m_enabled) && ((a_settings.m_checkVisibleObjects && m_showEnabled) || (a_settings.m_checkHapticObjects && m_hapticEnabled))) { /////////////////////////////////////////////////////////////////////// // DYNAMIC MOTION COMPENSATION // adjust the first segment endpoint so that it is in the same position // relative to the moving object as it was at the previous haptic iteration /////////////////////////////////////////////////////////////////////// cVector3d localSegmentPointAadjusted; if (a_settings.m_adjustObjectMotion) { adjustCollisionSegment(localSegmentPointA, localSegmentPointAadjusted); } else { localSegmentPointAadjusted = localSegmentPointA; } /////////////////////////////////////////////////////////////////////// // COLLISION DETECTOR /////////////////////////////////////////////////////////////////////// if (m_collisionDetector != NULL) { // call the collision detector's collision detection function if (m_collisionDetector->computeCollision(this, localSegmentPointAadjusted, localSegmentPointB, a_recorder, a_settings)) { // record that there has been a collision hit = true; } } // compute any other collisions. This is a virtual function that can be extended for // classes that may contain other objects (sibling) for which collision detection may // need to be computed. hit = hit | computeOtherCollisionDetection(localSegmentPointAadjusted, localSegmentPointB, a_recorder, a_settings); } /////////////////////////////////////////////////////////////////////////// // CHECK CHILDREN /////////////////////////////////////////////////////////////////////////// // check for collisions with all children of this object for (unsigned int i=0; icomputeCollisionDetection(localSegmentPointA, localSegmentPointB, a_recorder, a_settings); // update if a hit occurred hit = hit | hitChild; } /////////////////////////////////////////////////////////////////////////// // FINALIZE /////////////////////////////////////////////////////////////////////////// // return whether there was a collision between the segment and this world return (hit); } //============================================================================== /*! This method enables or disables graphic representation of the collision detector at this node. \\n If argument \\p a_affectChildren is set to __true__ then all children are updated with the new value. \\param a_showCollisionDetector If __true__ then display collision detector graphically. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setShowCollisionDetector(const bool a_showCollisionDetector, const bool a_affectChildren) { m_showCollisionDetector = a_showCollisionDetector; // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setShowCollisionDetector(a_showCollisionDetector, true); } } } //============================================================================== /*! This method sets the rendering properties of the the graphic representation of the collision detector. \\n If argument \\p a_affectChildren is set to __true__ then all children are updated with the new values. \\param a_color Color used to render collision detector. \\param a_displayDepth Indicated which depth of collision tree needs to be displayed (see cGenericCollision). \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::setCollisionDetectorProperties(unsigned int a_displayDepth, cColorf& a_color, const bool a_affectChildren) { if (m_collisionDetector != NULL) { m_collisionDetector->m_color = a_color; m_collisionDetector->setDisplayDepth(a_displayDepth); } // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->setCollisionDetectorProperties(a_displayDepth, a_color, true); } } } //============================================================================== /*! This method adds an object to the scene graph below this object. \\n Note that an object can only be a child of \\b one single object, unless )ghosting_ is enabled. \\param a_object Object to be added to child list. \\return __true__ if operation succeeded. */ //============================================================================== bool cGenericObject::addChild(cGenericObject* a_object) { // sanity check if ((a_object == NULL) || (a_object == this)) { return (false); } // the object does not have any parent yet, so we can add it as a child // to current object. if (a_object->m_parent == NULL) { m_children.push_back(a_object); a_object->m_parent = this; return (true); } // the object already has a parent, however since ghosting is enabled we add it // as a child without changing its m_parent member else if (m_ghostEnabled) { m_children.push_back(a_object); return (true); } // operation fails return (false); } //============================================================================== /*! This method removes an object from the list of children, without deleting the child object from memory. \\n This method assigns the child object's parent point to null, so if you're moving an object around in your scene graph, make sure you call this function _before_ you add the child to another node in the scene graph. \\param a_object Object to be removed from my list of children. \\return __true__ if the specified object was found on my list of children, __false__ otherwise. */ //============================================================================== bool cGenericObject::removeChild(cGenericObject* a_object) { // sanity check if (a_object == NULL) { return (false); } vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { if ((*it) == a_object) { // he doesn't have a parent any more a_object->m_parent = NULL; // remove this object from my list of children m_children.erase(it); // return success return (true); } } // operation failed return (false); } //============================================================================== /*! This method removes this object from its parent's list of children. \\return __true__ if operation succeeds, __false__ otherwise. */ //============================================================================== bool cGenericObject::removeFromGraph() { if (m_parent) { return (m_parent->removeChild(this)); } else { return (false); } } //============================================================================== /*! This method removes an object from its list of children, and deletes the child object from memory. \\param a_object Object to be removed from my list of children and deleted. \\return __true__ if the specified object was found in the child list. */ //============================================================================== bool cGenericObject::deleteChild(cGenericObject* a_object) { // sanity check if (a_object == NULL) { return (false); } // remove object from list bool result = removeChild(a_object); // if operation succeeds, delete the object if (result) { delete (a_object); } // return result return result; } //============================================================================== /*! This method clears all objects from my list of children, without deleting them. */ //============================================================================== void cGenericObject::clearAllChildren() { // clear parent member for all children vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->m_parent = NULL; } // clear children list m_children.clear(); } //============================================================================== /*! This method deletes and clear all objects the list of children. */ //============================================================================== void cGenericObject::deleteAllChildren() { // delete all children vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { cGenericObject* nextObject = (*it); delete (nextObject); } // clear my list of children m_children.clear(); } //============================================================================== /*! This method returns the total number of descendants, optionally including this object. \\param a_includeCurrentObject If __true__ then this object is included in the count. \\return Number of descendants found. */ //============================================================================== unsigned int cGenericObject::getNumDescendants(bool a_includeCurrentObject) { unsigned int numDescendants = a_includeCurrentObject?1:0; vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { numDescendants += (*it)->getNumDescendants(true); } return (numDescendants); } //============================================================================== /*! This method performs a uniform scale on the object, optionally including children. \\param a_scaleFactor Scale factor. \\param a_affectChildren If __true__ then children are updated too. */ //============================================================================== void cGenericObject::scale(const double& a_scaleFactor, const bool a_affectChildren) { // scale object scaleObject(a_scaleFactor); // apply change to children if (a_affectChildren) { vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { (*it)->m_localPos.mul(a_scaleFactor); (*it)->scale(a_scaleFactor, true); } } } //============================================================================== /*! This method render this object. Subclasses will generally override this method. This is called from renderSceneGraph, which subclasses generally do not need to override. \\n\\n A word on OpenGL conventions: \\n CHAI3D does not re-initialize the OpenGL state at every rendering pass. The only OpenGL state variables that CHAI3D sets explicitly in a typical rendering pass are: \\n\\n * lighting is enabled (cWorld) \\n * depth-testing is enabled (cWorld) \\n * glColorMaterial is enabled and set to GL_AMBIENT_AND_DIFFUSE/GL_FRONT_AND_BACK (cWorld) \\n * a perspective projection matrix is set up (cCamera) \\n\\n This adherence to the defaults is nice because it lets an application change an important piece of state globally and not worry about it getting changed by CHAI3D objects. \\n\\n It is expected that objects will ""clean up after themselves"" if they change any rendering state besides:\\n\\n * color (glColor) \\n * material properties (glMaterial) \\n * normals (glNormal) \\n\\n For example, if my object changes the rendering color, I don't need to set it back before returning, but if my object turns on vertex buffering, I should turn it off before returning. Consequently if I care about the current color, I should set it up in my own render() function, because I shouldn't count on it being meaningful when my render() function is called. \\n\\n Necessary exceptions to these conventions include: \\n\\n * cLight will change the lighting state for his assigned GL_LIGHT \\n * cCamera sets up relevant transformation matrices \\n\\n \\param a_options Rendering options. */ //============================================================================== void cGenericObject::render(cRenderOptions& a_options) { } //============================================================================== /*! This method uses the position of the tool and searches for the nearest point located at the surface of the current object and identifies if the point is located inside or outside of the object. \\param a_toolPos Position of the tool. \\param a_toolVel Velocity of the tool. \\param a_IDN Identification number of the force algorithm. */ //============================================================================== void cGenericObject::computeLocalInteraction(const cVector3d& a_toolPos, const cVector3d& a_toolVel, const unsigned int a_IDN) { m_interactionPoint.set(0,0,0); double length = a_toolPos.length(); if (length == 0.0) { m_interactionNormal.set(0,0,1); } else { m_interactionNormal = -(1.0/length)*a_toolPos; } m_interactionInside = true; } //============================================================================== /*! This method copies all material and texture properties from current generic object to another. This function is typically called by \\ref copy() method which duplicates an instance of a subclass of cGenericObject. \\param a_obj Object to which properties are copied to \\param a_duplicateMaterialData If __true__, material (if available) is duplicated, otherwise it is shared. \\param a_duplicateTextureData If __true__, texture data (if available) is duplicated, otherwise it is shared. \\param a_duplicateMeshData If __true__, mesh data (if available) is duplicated, otherwise it is shared. \\param a_buildCollisionDetector If __true__, collision detector (if available) is duplicated, otherwise it is shared. */ //============================================================================== void cGenericObject::copyGenericObjectProperties(cGenericObject* a_obj, const bool a_duplicateMaterialData, const bool a_duplicateTextureData, const bool a_duplicateMeshData, const bool a_buildCollisionDetector) { // sanity check if (a_obj == NULL) { return; } // copy material if ((a_duplicateMaterialData) && ((m_material != nullptr) || (m_material != s_defaultMaterial))) { a_obj->m_material = m_material->copy(); } else { a_obj->m_material = m_material; } // copy texture if ((a_duplicateTextureData) && (m_texture != nullptr)) { a_obj->m_texture = m_texture->copy(); } else { a_obj->m_texture = m_texture; } // copy general properties and settings a_obj->m_useTextureMapping = m_useTextureMapping; a_obj->m_useMaterialProperty = m_useMaterialProperty; a_obj->m_useVertexColors = m_useVertexColors; a_obj->m_useTransparency = m_useTransparency; a_obj->m_cullingEnabled = m_cullingEnabled; a_obj->m_localPos = m_localPos; a_obj->m_localRot = m_localRot; } //============================================================================== /*! This method renders the scene graph starting at this object. This method is called for each object and optionally render the object itself, its reference frame and the collision and/or scenegraph trees. \\n The object itself is rendered by calling render(), which should be defined for each subclass that has a graphical representation. renderSceneGraph does not generally need to be over-ridden in subclasses. \\n The a_options parameter is used to allow multiple rendering passes. See CRenderOptionh.h for more information. \\param a_options Rendering options. */ //============================================================================== void cGenericObject::renderSceneGraph(cRenderOptions& a_options) { #ifdef C_USE_OPENGL ///////////////////////////////////////////////////////////////////////// // Initialize rendering ///////////////////////////////////////////////////////////////////////// // convert the position and orientation of the object into a 4x4 matrix // that is supported by openGL. This task only needs to be performed during the first // rendering pass if (a_options.m_storeObjectPositions) { m_frameGL.set(m_localPos, m_localRot); } // push object position/orientation on stack glPushMatrix(); glMultMatrixd( (const double *)m_frameGL.getData() ); // render if object is enabled if (m_enabled) { //-------------------------------------------------------------------------- // Request for RESET //----------------------------------------------------------------------- if(a_options.m_markForUpdate) { // invalidate display list markForUpdate(false); // invalidate texture if (m_texture != nullptr) { m_texture->markForUpdate(); } } //----------------------------------------------------------------------- // Init //----------------------------------------------------------------------- glEnable(GL_LIGHTING); glDisable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE); //----------------------------------------------------------------------- // Render bounding box, frame, collision detector. (opaque components) //----------------------------------------------------------------------- if (SECTION_RENDER_OPAQUE_PARTS_ONLY(a_options) && (!a_options.m_rendering_shadow)) { // disable lighting glDisable(GL_LIGHTING); // render boundary box if (m_showBoundaryBox) { // set size on lines glLineWidth(1.0); // set color of boundary box glColor4fv(s_boundaryBoxColor.getData()); // draw box line cDrawWireBox(m_boundaryBoxMin(0) , m_boundaryBoxMax(0) , m_boundaryBoxMin(1) , m_boundaryBoxMax(1) , m_boundaryBoxMin(2) , m_boundaryBoxMax(2) ); } // render collision tree if (m_showCollisionDetector && (m_collisionDetector != NULL)) { m_collisionDetector->render(a_options); } // enable lighting glEnable(GL_LIGHTING); } // render frame if (m_showFrame && (a_options.m_single_pass_only || a_options.m_render_opaque_objects_only)) { glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_INDEX_ARRAY); glDisableClientState(GL_EDGE_FLAG_ARRAY); glDisable(GL_COLOR_MATERIAL); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glColor4f(1.0,1.0,1.0,1.0); // set rendering properties glPolygonMode(GL_FRONT, GL_FILL); // draw frame cDrawFrame(m_frameSize, m_frameThicknessScale); } //----------------------------------------------------------------------- // Render graphical representation of object //----------------------------------------------------------------------- if (m_showEnabled) { // set polygon and face mode glPolygonMode(GL_FRONT_AND_BACK, m_triangleMode); // initialize line width glLineWidth(1.0f); ///////////////////////////////////////////////////////////////////// // CREATING SHADOW DEPTH MAP ///////////////////////////////////////////////////////////////////// if (a_options.m_creating_shadow_map) { glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); // render object render(a_options); glDisable(GL_CULL_FACE); } ///////////////////////////////////////////////////////////////////// // SINGLE PASS RENDERING ///////////////////////////////////////////////////////////////////// else if (a_options.m_single_pass_only) { if (m_cullingEnabled) { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } else { glDisable(GL_CULL_FACE); } if (m_useTransparency) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(GL_FALSE); } else { glDisable(GL_BLEND); glDepthMask(GL_TRUE); } // render object render(a_options); // disable blending glDisable(GL_BLEND); glDepthMask(GL_TRUE); } ///////////////////////////////////////////////////////////////////// // MULTI PASS RENDERING ///////////////////////////////////////////////////////////////////// else { // opaque objects if (a_options.m_render_opaque_objects_only) { if (m_cullingEnabled) { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } else { glDisable(GL_CULL_FACE); } render(a_options); } // render transparent back triangles if (a_options.m_render_transparent_back_faces_only) { if (m_useTransparency) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(GL_FALSE); } else { glDisable(GL_BLEND); glDepthMask(GL_TRUE); } glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); render(a_options); // disable blending glDisable(GL_BLEND); glDepthMask(GL_TRUE); } // render transparent front triangles if (a_options.m_render_transparent_front_faces_only) { if (m_useTransparency) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(GL_FALSE); } else { glDisable(GL_BLEND); glDepthMask(GL_TRUE); } glEnable(GL_CULL_FACE); glCullFace(GL_BACK); render(a_options); // disable blending glDisable(GL_BLEND); glDepthMask(GL_TRUE); } } } } // render children for (unsigned int i=0; irenderSceneGraph(a_options); } // pop current matrix glPopMatrix(); #endif } //============================================================================== /*! This method adjusts the collision segment to take into consideration motion from an object. This feature is used by the finger-proxy algorithm to avoid ""popping"" through objects if their move toward the proxy while the proxy remains till. \\param a_segmentPointA Start point of segment. \\param a_segmentPointAadjusted Adjusted start point of segment. */ //============================================================================== void cGenericObject::adjustCollisionSegment(cVector3d& a_segmentPointA, cVector3d& a_segmentPointAadjusted) { // convert point from local to global coordinates by using // the previous object position and orientation cVector3d point = cAdd(m_globalPos, cMul(m_globalRot, a_segmentPointA)); // compute the new position of the point based on // the new object position and orientation a_segmentPointAadjusted = cMul( cTranspose(m_prevGlobalRot), cSub(point, m_prevGlobalPos)); } //============================================================================== /*! This method descends through child objects to compute interactions for all cGenericEffect classes defined for each object. \\param a_toolPos Current position of tool. \\param a_toolVel Current position of tool. \\param a_IDN Identification number of the force algorithm. \\param a_interactions List of recorded interactions. \\return Resulting interaction force. */ //============================================================================== cVector3d cGenericObject::computeInteractions(const cVector3d& a_toolPos, const cVector3d& a_toolVel, const unsigned int a_IDN, cInteractionRecorder& a_interactions) { // compute inverse rotation cMatrix3d localRotTrans; m_localRot.transr(localRotTrans); // compute local position of tool and velocity vector cVector3d toolPosLocal = cMul(localRotTrans, cSub(a_toolPos, m_localPos)); // compute interaction between tool and current object cVector3d toolVelLocal = cMul(localRotTrans, a_toolVel); // compute forces based on the effects programmed for this object cVector3d localForce(0,0,0); // check if node is a ghost. If yes, then ignore call if (m_ghostEnabled) { return (cVector3d(0,0,0)); } // process current object if enabled if (m_enabled) { // compute local interaction with current object computeLocalInteraction(toolPosLocal, toolVelLocal, a_IDN); if(m_hapticEnabled) { // compute each force effect bool interactionEvent = false; for (unsigned int i=0; igetEnabled()) { cVector3d force(0,0,0); interactionEvent = interactionEvent | nextEffect->computeForce(toolPosLocal, toolVelLocal, a_IDN, force); localForce.add(force); } } // report any interaction if (interactionEvent) { cInteractionEvent newInteractionEvent; newInteractionEvent.m_object = this; newInteractionEvent.m_isInside = m_interactionInside; newInteractionEvent.m_localPos = toolPosLocal; newInteractionEvent.m_localSurfacePos = m_interactionPoint; newInteractionEvent.m_localNormal = m_interactionNormal; newInteractionEvent.m_localForce = localForce; a_interactions.m_interactions.push_back(newInteractionEvent); } // compute any other force interactions cVector3d force = computeOtherInteractions(toolPosLocal, toolVelLocal, a_IDN, a_interactions); localForce.add(force); } } // descend through the children vector::iterator it; for (it = m_children.begin(); it < m_children.end(); it++) { cVector3d force = (*it)->computeInteractions(toolPosLocal, toolVelLocal, a_IDN, a_interactions); localForce.add(force); } // convert the reaction force into my parent coordinates cVector3d m_globalForce = cMul(m_localRot, localForce); // return resulting force return (m_globalForce); } //------------------------------------------------------------------------------ } // namespace chai3d //------------------------------------------------------------------------------ ",16158,True,3342.022716117045,median "CLASS zcl_abapgit_object_wdyn DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super FINAL CREATE PUBLIC . PUBLIC SECTION. INTERFACES zif_abapgit_object . ALIASES mo_files FOR zif_abapgit_object~mo_files . PROTECTED SECTION. PRIVATE SECTION. DATA: mt_components TYPE TABLE OF wdy_ctlr_compo_vrs, mt_sources TYPE TABLE OF wdy_ctlr_compo_source_vrs. METHODS: get_limu_objects RETURNING VALUE(rt_objects) TYPE wdy_md_transport_keys, read RETURNING VALUE(rs_component) TYPE wdy_component_metadata RAISING zcx_abapgit_exception, read_controller IMPORTING is_key TYPE wdy_md_controller_key RETURNING VALUE(rs_controller) TYPE wdy_md_controller_meta_data RAISING zcx_abapgit_exception, read_definition IMPORTING is_key TYPE wdy_md_component_key RETURNING VALUE(rs_definition) TYPE wdy_md_component_meta_data RAISING zcx_abapgit_exception, read_view IMPORTING is_key TYPE wdy_md_view_key RETURNING VALUE(rs_view) TYPE wdy_md_view_meta_data RAISING zcx_abapgit_exception, recover_controller IMPORTING is_controller TYPE wdy_md_controller_meta_data RAISING zcx_abapgit_exception, recover_definition IMPORTING is_definition TYPE wdy_md_component_meta_data iv_package TYPE devclass RAISING zcx_abapgit_exception, recover_view IMPORTING is_view TYPE wdy_md_view_meta_data RAISING zcx_abapgit_exception, delta_controller IMPORTING is_controller TYPE wdy_md_controller_meta_data RETURNING VALUE(rs_delta) TYPE svrs2_xversionable_object RAISING zcx_abapgit_exception, delta_definition IMPORTING is_definition TYPE wdy_md_component_meta_data VALUE(iv_package) TYPE devclass RETURNING VALUE(rs_delta) TYPE svrs2_xversionable_object RAISING zcx_abapgit_exception, delta_view IMPORTING is_view TYPE wdy_md_view_meta_data RETURNING VALUE(rs_delta) TYPE svrs2_xversionable_object RAISING zcx_abapgit_exception, add_fm_param_exporting IMPORTING iv_name TYPE string ig_value TYPE any CHANGING ct_param TYPE abap_func_parmbind_tab, add_fm_param_tables IMPORTING iv_name TYPE string CHANGING ct_value TYPE ANY TABLE ct_param TYPE abap_func_parmbind_tab, add_fm_exception IMPORTING iv_name TYPE string iv_value TYPE i CHANGING ct_exception TYPE abap_func_excpbind_tab, add_with_inactive_parts RAISING zcx_abapgit_exception . ENDCLASS. CLASS zcl_abapgit_object_wdyn IMPLEMENTATION. METHOD add_fm_exception. DATA: ls_exception LIKE LINE OF ct_exception. ls_exception-name = iv_name. ls_exception-value = iv_value. INSERT ls_exception INTO TABLE ct_exception. ENDMETHOD. METHOD add_fm_param_exporting. DATA: ls_param LIKE LINE OF ct_param. ls_param-kind = abap_func_exporting. ls_param-name = iv_name. GET REFERENCE OF ig_value INTO ls_param-value. INSERT ls_param INTO TABLE ct_param. ENDMETHOD. METHOD add_fm_param_tables. DATA: ls_param LIKE LINE OF ct_param. ls_param-kind = abap_func_tables. ls_param-name = iv_name. GET REFERENCE OF ct_value INTO ls_param-value. INSERT ls_param INTO TABLE ct_param. ENDMETHOD. METHOD add_with_inactive_parts. DATA: lv_obj_name TYPE trobj_name, lv_object TYPE trobjtype, lt_objects TYPE dwinactiv_tab. FIELD-SYMBOLS: LIKE LINE OF lt_objects. lv_obj_name = ms_item-obj_name. lv_object = ms_item-obj_type. CALL FUNCTION 'RS_INACTIVE_OBJECTS_IN_OBJECT' EXPORTING obj_name = lv_obj_name object = lv_object TABLES inactive_objects = lt_objects EXCEPTIONS object_not_found = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. LOOP AT lt_objects ASSIGNING . zcl_abapgit_objects_activation=>add( iv_type = -object iv_name = -obj_name ). ENDLOOP. ENDMETHOD. METHOD delta_controller. DATA: li_controller TYPE REF TO if_wdy_md_controller, lx_error TYPE REF TO cx_wdy_md_exception, lv_found TYPE abap_bool, ls_key TYPE wdy_md_controller_key, ls_obj_new TYPE svrs2_versionable_object, ls_obj_old TYPE svrs2_versionable_object. FIELD-SYMBOLS: LIKE LINE OF mt_components, LIKE LINE OF mt_sources, TYPE ANY TABLE, TYPE ANY TABLE, TYPE ANY TABLE, TYPE ANY TABLE. ls_key-component_name = is_controller-definition-component_name. ls_key-controller_name = is_controller-definition-controller_name. lv_found = cl_wdy_md_controller=>check_existency( component_name = ls_key-component_name controller_name = ls_key-controller_name ). IF lv_found = abap_false. TRY. li_controller ?= cl_wdy_md_controller=>create_complete( component_name = ls_key-component_name controller_name = ls_key-controller_name controller_type = is_controller-definition-controller_type ). li_controller->save_to_database( ). li_controller->unlock( ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error creating dummy controller: { lx_error->get_text( ) }| ). ENDTRY. ENDIF. ls_obj_new-objtype = wdyn_limu_component_controller. ls_obj_new-objname = ls_key. ls_obj_old-objtype = wdyn_limu_component_controller. ls_obj_old-objname = ls_key. APPEND is_controller-definition TO ls_obj_old-wdyc-defin. LOOP AT mt_components ASSIGNING WHERE component_name = ls_key-component_name AND controller_name = ls_key-controller_name. APPEND TO ls_obj_old-wdyc-ccomp. ENDLOOP. LOOP AT mt_sources ASSIGNING WHERE component_name = ls_key-component_name AND controller_name = ls_key-controller_name. APPEND TO ls_obj_old-wdyc-ccoms. ENDLOOP. ls_obj_old-wdyc-descr = is_controller-descriptions. ls_obj_old-wdyc-cusag = is_controller-controller_usages. ls_obj_old-wdyc-ccomt = is_controller-controller_component_texts. ls_obj_old-wdyc-cpara = is_controller-controller_parameters. ls_obj_old-wdyc-cpart = is_controller-controller_parameter_texts. ls_obj_old-wdyc-cnode = is_controller-context_nodes. ls_obj_old-wdyc-cattr = is_controller-context_attributes. ls_obj_old-wdyc-cmapp = is_controller-context_mappings. * Version 702 doesn't have these two attributes so we * use them dynamically for downward compatibility ASSIGN COMPONENT 'CONTROLLER_EXCEPTIONS' OF STRUCTURE is_controller TO . IF sy-subrc = 0. ASSIGN COMPONENT 'EXCP' OF STRUCTURE ls_obj_old-wdyc TO . IF sy-subrc = 0. = . ENDIF. ENDIF. ASSIGN COMPONENT 'CONTROLLER_EXCEPTIONS_TEXTS' OF STRUCTURE is_controller TO . IF sy-subrc = 0. ASSIGN COMPONENT 'EXCPT' OF STRUCTURE ls_obj_old-wdyc TO . IF sy-subrc = 0. = . ENDIF. ENDIF. ls_obj_old-wdyc-fgrps = is_controller-fieldgroups. CALL FUNCTION 'SVRS_MAKE_OBJECT_DELTA' EXPORTING obj_old = ls_obj_new obj_new = ls_obj_old CHANGING delta = rs_delta EXCEPTIONS inconsistent_objects = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from SVRS_MAKE_OBJECT_DELTA' ). ENDIF. ENDMETHOD. METHOD delta_definition. DATA: ls_key TYPE wdy_md_component_key, lv_found TYPE abap_bool, ls_obj_new TYPE svrs2_versionable_object, li_component TYPE REF TO if_wdy_md_component, lx_error TYPE REF TO cx_wdy_md_exception, ls_obj_old TYPE svrs2_versionable_object. ls_key-component_name = is_definition-definition-component_name. lv_found = cl_wdy_md_component=>check_existency( ls_key-component_name ). IF lv_found = abap_false. TRY. cl_wdy_md_component=>create_complete( EXPORTING name = ls_key-component_name IMPORTING component = li_component CHANGING devclass = iv_package ). li_component->save_to_database( ). li_component->unlock( ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error creating dummy component: { lx_error->get_text( ) }| ). ENDTRY. ENDIF. ls_obj_new-objtype = wdyn_limu_component_definition. ls_obj_new-objname = ls_key-component_name. ls_obj_old-objtype = wdyn_limu_component_definition. ls_obj_old-objname = ls_key-component_name. APPEND is_definition-definition TO ls_obj_old-wdyd-defin. ls_obj_old-wdyd-descr = is_definition-descriptions. ls_obj_old-wdyd-cusag = is_definition-component_usages. ls_obj_old-wdyd-intrf = is_definition-interface_implementings. ls_obj_old-wdyd-libra = is_definition-library_usages. ls_obj_old-wdyd-ctuse = is_definition-ext_ctlr_usages. ls_obj_old-wdyd-ctmap = is_definition-ext_ctx_mappings. CALL FUNCTION 'SVRS_MAKE_OBJECT_DELTA' EXPORTING obj_old = ls_obj_new obj_new = ls_obj_old CHANGING delta = rs_delta EXCEPTIONS inconsistent_objects = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from SVRS_MAKE_OBJECT_DELTA' ). ENDIF. ENDMETHOD. METHOD delta_view. DATA: ls_key TYPE wdy_md_view_key, ls_obj_new TYPE svrs2_versionable_object, ls_obj_old TYPE svrs2_versionable_object, lv_found TYPE abap_bool, lx_error TYPE REF TO cx_wdy_md_exception, li_view TYPE REF TO if_wdy_md_abstract_view. FIELD-SYMBOLS: LIKE LINE OF ls_obj_old-wdyv-defin. ls_key-component_name = is_view-definition-component_name. ls_key-view_name = is_view-definition-view_name. lv_found = cl_wdy_md_abstract_view=>check_existency( component_name = ls_key-component_name name = ls_key-view_name ). IF lv_found = abap_false. TRY. li_view = cl_wdy_md_abstract_view=>create( component_name = is_view-definition-component_name view_name = is_view-definition-view_name type = is_view-definition-type ). li_view->save_to_database( ). li_view->unlock( ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error creating dummy view: { lx_error->get_text( ) }| ). ENDTRY. ENDIF. ls_obj_new-objtype = wdyn_limu_component_view. ls_obj_new-objname = ls_key. ls_obj_old-objtype = wdyn_limu_component_view. ls_obj_old-objname = ls_key. APPEND INITIAL LINE TO ls_obj_old-wdyv-defin ASSIGNING . MOVE-CORRESPONDING is_view-definition TO . ls_obj_old-wdyv-descr = is_view-descriptions. ls_obj_old-wdyv-vcont = is_view-view_containers. ls_obj_old-wdyv-vcntt = is_view-view_container_texts. ls_obj_old-wdyv-ibplg = is_view-iobound_plugs. ls_obj_old-wdyv-ibplt = is_view-iobound_plug_texts. ls_obj_old-wdyv-plpar = is_view-plug_parameters. ls_obj_old-wdyv-plprt = is_view-plug_parameter_texts. ls_obj_old-wdyv-uiele = is_view-ui_elements. ls_obj_old-wdyv-uicon = is_view-ui_context_bindings. ls_obj_old-wdyv-uievt = is_view-ui_event_bindings. ls_obj_old-wdyv-uiddc = is_view-ui_ddic_bindings. ls_obj_old-wdyv-uiprp = is_view-ui_properties. ls_obj_old-wdyv-navil = is_view-navigation_links. ls_obj_old-wdyv-navit = is_view-navigation_target_refs. ls_obj_old-wdyv-vshno = is_view-vsh_nodes. ls_obj_old-wdyv-vshpl = is_view-vsh_placeholders. ls_obj_old-wdyv-views = is_view-viewset_properties. CALL FUNCTION 'SVRS_MAKE_OBJECT_DELTA' EXPORTING obj_old = ls_obj_new obj_new = ls_obj_old CHANGING delta = rs_delta EXCEPTIONS inconsistent_objects = 1. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from SVRS_MAKE_OBJECT_DELTA' ). ENDIF. ENDMETHOD. METHOD get_limu_objects. DATA: lv_name TYPE wdy_component_name. lv_name = ms_item-obj_name. CALL FUNCTION 'WDYN_GET_LIMU_OBJECTS' EXPORTING component_name = lv_name IMPORTING limu_objects = rt_objects. ENDMETHOD. METHOD read. DATA: lt_objects TYPE wdy_md_transport_keys, ls_controller_key TYPE wdy_md_controller_key, ls_component_key TYPE wdy_md_component_key, ls_view_key TYPE wdy_md_view_key. FIELD-SYMBOLS: LIKE LINE OF lt_objects, LIKE LINE OF rs_component-ctlr_metadata, LIKE LINE OF rs_component-view_metadata, TYPE ANY TABLE, TYPE ANY TABLE. CLEAR mt_components. CLEAR mt_sources. lt_objects = get_limu_objects( ). LOOP AT lt_objects ASSIGNING . CASE -sub_type. WHEN wdyn_limu_component_controller. ls_controller_key = -sub_name. APPEND read_controller( ls_controller_key ) TO rs_component-ctlr_metadata. WHEN wdyn_limu_component_definition. ls_component_key = -sub_name. rs_component-comp_metadata = read_definition( ls_component_key ). WHEN wdyn_limu_component_view. ls_view_key = -sub_name. APPEND read_view( ls_view_key ) TO rs_component-view_metadata. WHEN OTHERS. ASSERT 0 = 1. ENDCASE. ENDLOOP. SORT rs_component-ctlr_metadata BY definition-component_name ASCENDING definition-controller_name ASCENDING. LOOP AT rs_component-ctlr_metadata ASSIGNING . SORT -descriptions. SORT -controller_usages. SORT -controller_components. SORT -controller_component_texts. SORT -controller_parameters. SORT -controller_parameter_texts. SORT -context_nodes. SORT -context_attributes. SORT -context_mappings. SORT -fieldgroups. * Version 702 doesn't have these two attributes so we * use them dynamically for downward compatibility ASSIGN COMPONENT 'CONTROLLER_EXCEPTIONS' OF STRUCTURE TO . IF sy-subrc = 0. SORT . ENDIF. ASSIGN COMPONENT 'CONTROLLER_EXCEPTION_TEXTS' OF STRUCTURE TO . IF sy-subrc = 0. SORT . ENDIF. ENDLOOP. LOOP AT rs_component-view_metadata ASSIGNING . SORT -ui_elements. ENDLOOP. SORT mt_components BY component_name ASCENDING controller_name ASCENDING cmpname ASCENDING. SORT mt_sources BY component_name ASCENDING controller_name ASCENDING cmpname ASCENDING line_number ASCENDING. ENDMETHOD. METHOD read_controller. DATA: lt_components TYPE TABLE OF wdy_ctlr_compo_vrs, lt_sources TYPE TABLE OF wdy_ctlr_compo_source_vrs, lt_definition TYPE TABLE OF wdy_controller, lt_psmodilog TYPE TABLE OF smodilog, lt_psmodisrc TYPE TABLE OF smodisrc, lt_fm_param TYPE abap_func_parmbind_tab, lt_fm_exception TYPE abap_func_excpbind_tab. FIELD-SYMBOLS: TYPE ANY TABLE, TYPE ANY TABLE. * Calling FM dynamically because version 702 has less parameters * FM parameters add_fm_param_exporting( EXPORTING iv_name = 'CONTROLLER_KEY' ig_value = is_key CHANGING ct_param = lt_fm_param ). add_fm_param_exporting( EXPORTING iv_name = 'GET_ALL_TRANSLATIONS' ig_value = abap_false CHANGING ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'DEFINITION' CHANGING ct_value = lt_definition ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'DESCRIPTIONS' CHANGING ct_value = rs_controller-descriptions ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_USAGES' CHANGING ct_value = rs_controller-controller_usages ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_COMPONENTS' CHANGING ct_value = lt_components ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_COMPONENT_SOURCES' CHANGING ct_value = lt_sources ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_COMPONENT_TEXTS' CHANGING ct_value = rs_controller-controller_component_texts ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_PARAMETERS' CHANGING ct_value = rs_controller-controller_parameters ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_PARAMETER_TEXTS' CHANGING ct_value = rs_controller-controller_parameter_texts ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTEXT_NODES' CHANGING ct_value = rs_controller-context_nodes ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTEXT_ATTRIBUTES' CHANGING ct_value = rs_controller-context_attributes ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'CONTEXT_MAPPINGS' CHANGING ct_value = rs_controller-context_mappings ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'FIELDGROUPS' CHANGING ct_value = rs_controller-fieldgroups ct_param = lt_fm_param ). * Version 702 doesn't have these two attributes so we * use them dynamically for downward compatibility ASSIGN COMPONENT 'CONTROLLER_EXCEPTIONS' OF STRUCTURE rs_controller TO . IF sy-subrc = 0. add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_EXCEPTIONS' CHANGING ct_value = ct_param = lt_fm_param ). ENDIF. ASSIGN COMPONENT 'CONTROLLER_EXCEPTION_TEXTS' OF STRUCTURE rs_controller TO . IF sy-subrc = 0. add_fm_param_tables( EXPORTING iv_name = 'CONTROLLER_EXCEPTION_TEXTS' CHANGING ct_value = ct_param = lt_fm_param ). ENDIF. add_fm_param_tables( EXPORTING iv_name = 'PSMODILOG' CHANGING ct_value = lt_psmodilog ct_param = lt_fm_param ). add_fm_param_tables( EXPORTING iv_name = 'PSMODISRC' CHANGING ct_value = lt_psmodisrc ct_param = lt_fm_param ). * FM exceptions add_fm_exception( EXPORTING iv_name = 'NOT_EXISTING' iv_value = 1 CHANGING ct_exception = lt_fm_exception ). add_fm_exception( EXPORTING iv_name = 'OTHERS' iv_value = 2 CHANGING ct_exception = lt_fm_exception ). CALL FUNCTION 'WDYC_GET_OBJECT' PARAMETER-TABLE lt_fm_param EXCEPTION-TABLE lt_fm_exception. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from WDYC_GET_OBJECT' ). ENDIF. APPEND LINES OF lt_components TO mt_components. APPEND LINES OF lt_sources TO mt_sources. READ TABLE lt_definition INDEX 1 INTO rs_controller-definition. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'WDYC, definition not found' ). ENDIF. CLEAR: rs_controller-definition-author, rs_controller-definition-createdon, rs_controller-definition-changedby, rs_controller-definition-changedon. ENDMETHOD. METHOD read_definition. DATA: lt_definition TYPE TABLE OF wdy_component, lt_psmodilog TYPE TABLE OF smodilog, lt_psmodisrc TYPE TABLE OF smodisrc. CALL FUNCTION 'WDYD_GET_OBJECT' EXPORTING component_key = is_key get_all_translations = abap_false TABLES definition = lt_definition descriptions = rs_definition-descriptions component_usages = rs_definition-component_usages interface_implementings = rs_definition-interface_implementings library_usages = rs_definition-library_usages ext_ctlr_usages = rs_definition-ext_ctlr_usages ext_ctx_mappings = rs_definition-ext_ctx_mappings psmodilog = lt_psmodilog "" not optional in all versions psmodisrc = lt_psmodisrc "" not optional in all versions EXCEPTIONS not_existing = 1 OTHERS = 2. IF sy-subrc = 1. RETURN. ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from WDYD_GET_OBJECT' ). ENDIF. READ TABLE lt_definition INDEX 1 INTO rs_definition-definition. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'WDYD, definition not found' ). ENDIF. CLEAR: rs_definition-definition-author, rs_definition-definition-createdon, rs_definition-definition-changedby, rs_definition-definition-changedon, rs_definition-definition-gendate, rs_definition-definition-gentime. ENDMETHOD. METHOD read_view. DATA: lt_definition TYPE TABLE OF wdy_view_vrs, lt_psmodilog TYPE TABLE OF smodilog, lt_psmodisrc TYPE TABLE OF smodisrc. FIELD-SYMBOLS: LIKE LINE OF lt_definition. CALL FUNCTION 'WDYV_GET_OBJECT' EXPORTING view_key = is_key get_all_translations = abap_false TABLES definition = lt_definition descriptions = rs_view-descriptions view_containers = rs_view-view_containers view_container_texts = rs_view-view_container_texts iobound_plugs = rs_view-iobound_plugs iobound_plug_texts = rs_view-iobound_plug_texts plug_parameters = rs_view-plug_parameters plug_parameter_texts = rs_view-plug_parameter_texts ui_elements = rs_view-ui_elements ui_context_bindings = rs_view-ui_context_bindings ui_event_bindings = rs_view-ui_event_bindings ui_ddic_bindings = rs_view-ui_ddic_bindings ui_properties = rs_view-ui_properties navigation_links = rs_view-navigation_links navigation_target_refs = rs_view-navigation_target_refs vsh_nodes = rs_view-vsh_nodes vsh_placeholders = rs_view-vsh_placeholders viewset_properties = rs_view-viewset_properties psmodilog = lt_psmodilog psmodisrc = lt_psmodisrc EXCEPTIONS not_existing = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from WDYV_GET_OBJECT' ). ENDIF. READ TABLE lt_definition INDEX 1 ASSIGNING . ASSERT sy-subrc = 0. MOVE-CORRESPONDING TO rs_view-definition. CLEAR: rs_view-definition-author, rs_view-definition-createdon, rs_view-definition-changedby, rs_view-definition-changedon. ENDMETHOD. METHOD recover_controller. DATA: ls_key TYPE wdy_controller_key, lv_corrnr TYPE trkorr, lx_error TYPE REF TO cx_wdy_md_exception, ls_delta TYPE svrs2_xversionable_object. ls_delta = delta_controller( is_controller ). ls_key-component_name = is_controller-definition-component_name. ls_key-controller_name = is_controller-definition-controller_name. TRY. cl_wdy_md_controller=>recover_version( EXPORTING controller_key = ls_key delta = ls_delta-wdyc CHANGING corrnr = lv_corrnr ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error recovering version of controller: { lx_error->get_text( ) }| ). ENDTRY. ENDMETHOD. METHOD recover_definition. DATA: ls_key TYPE wdy_md_component_key, lv_corrnr TYPE trkorr, lx_error TYPE REF TO cx_wdy_md_exception, ls_delta TYPE svrs2_xversionable_object. ls_delta = delta_definition( is_definition = is_definition iv_package = iv_package ). ls_key-component_name = is_definition-definition-component_name. TRY. cl_wdy_md_component=>recover_version( EXPORTING component_key = ls_key delta = ls_delta-wdyd CHANGING corrnr = lv_corrnr ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error recovering version of component: { lx_error->get_text( ) }| ). ENDTRY. ENDMETHOD. METHOD recover_view. DATA: ls_key TYPE wdy_md_view_key, lv_corrnr TYPE trkorr, lx_error TYPE REF TO cx_wdy_md_exception, ls_delta TYPE svrs2_xversionable_object. ls_delta = delta_view( is_view ). ls_key-component_name = is_view-definition-component_name. ls_key-view_name = is_view-definition-view_name. TRY. cl_wdy_md_abstract_view=>recover_version( EXPORTING view_key = ls_key delta = ls_delta-wdyv CHANGING corrnr = lv_corrnr ). CATCH cx_wdy_md_exception INTO lx_error. zcx_abapgit_exception=>raise( |Error recovering version of abstract view: { lx_error->get_text( ) }| ). ENDTRY. ENDMETHOD. METHOD zif_abapgit_object~changed_by. rv_user = c_user_unknown. "" todo ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lo_component TYPE REF TO cl_wdy_wb_component, lo_request TYPE REF TO cl_wb_request, li_state TYPE REF TO if_wb_program_state, lv_object_name TYPE seu_objkey. lo_component = NEW #( ). lv_object_name = ms_item-obj_name. lo_request = NEW #( p_object_type = 'YC' p_object_name = lv_object_name p_operation = swbm_c_op_delete_no_dialog ). lo_component->if_wb_program~process_wb_request( p_wb_request = lo_request p_wb_program_state = li_state ). ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: ls_component TYPE wdy_component_metadata, ls_description TYPE wdy_ext_ctx_map. FIELD-SYMBOLS: LIKE LINE OF ls_component-view_metadata, LIKE LINE OF ls_component-ctlr_metadata. io_xml->read( EXPORTING iv_name = 'COMPONENT' CHANGING cg_data = ls_component ). io_xml->read( EXPORTING iv_name = 'COMPONENTS' CHANGING cg_data = mt_components ). io_xml->read( EXPORTING iv_name = 'SOURCES' CHANGING cg_data = mt_sources ). ls_component-comp_metadata-definition-author = sy-uname. ls_component-comp_metadata-definition-createdon = sy-datum. recover_definition( is_definition = ls_component-comp_metadata iv_package = iv_package ). LOOP AT ls_component-ctlr_metadata ASSIGNING . -definition-author = sy-uname. -definition-createdon = sy-datum. recover_controller( ). ENDLOOP. LOOP AT ls_component-view_metadata ASSIGNING . -definition-author = sy-uname. -definition-createdon = sy-datum. recover_view( ). ENDLOOP. READ TABLE ls_component-comp_metadata-descriptions INTO ls_description INDEX 1. IF sy-subrc = 0. zcl_abapgit_sotr_handler=>create_sotr( iv_package = iv_package io_xml = io_xml ). ENDIF. add_with_inactive_parts( ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_component_name TYPE wdy_component-component_name. SELECT SINGLE component_name FROM wdy_component INTO lv_component_name WHERE component_name = ms_item-obj_name. ""#EC CI_GENBUFF rv_bool = xsdbool( sy-subrc = 0 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. rv_is_locked = abap_false. ENDMETHOD. METHOD zif_abapgit_object~jump. "" Covered by ZCL_ABAPGIT_OBJECTS=>JUMP ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: ls_component TYPE wdy_component_metadata, ls_description TYPE wdy_ext_ctx_map. ls_component = read( ). io_xml->add( iv_name = 'COMPONENT' ig_data = ls_component ). io_xml->add( ig_data = mt_components iv_name = 'COMPONENTS' ). io_xml->add( ig_data = mt_sources iv_name = 'SOURCES' ). READ TABLE ls_component-comp_metadata-descriptions INTO ls_description INDEX 1. IF sy-subrc = 0. zcl_abapgit_sotr_handler=>read_sotr( iv_pgmid = 'LIMU' iv_object = 'WDYV' iv_obj_name = ms_item-obj_name io_xml = io_xml ). ENDIF. ENDMETHOD. ENDCLASS. ",7425,False,1740.5593891555786,median "[[netty-component]] = Netty Component *Since Camel 2.14* 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 6 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *maximumPoolSize* (advanced) | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | int | *configuration* (advanced) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *executorService* (advanced) | To use the given EventExecutorGroup. | | EventExecutorGroup | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | 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. | | 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 operation 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. | | 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. | WARN | LoggingLevel | *serverClosedChannel ExceptionCaughtLogLevel* (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. | DEBUG | LoggingLevel | *serverExceptionCaughtLog Level* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. | 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 | *producerPoolMinEvictable Idle* (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 operation 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. | 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. | 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 // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-netty-starter x.x.x ---- The component supports 78 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.netty.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.netty.configuration.allow-default-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 | *camel.component.netty.configuration.allow-serialized-headers* | 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 | *camel.component.netty.configuration.auto-append-delimiter* | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | Boolean | *camel.component.netty.configuration.backlog* | 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. | | Integer | *camel.component.netty.configuration.boss-count* | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | Integer | *camel.component.netty.configuration.boss-group* | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *camel.component.netty.configuration.broadcast* | Setting to choose Multicast over UDP | false | Boolean | *camel.component.netty.configuration.channel-group* | To use a explicit ChannelGroup. | | ChannelGroup | *camel.component.netty.configuration.client-initializer-factory* | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *camel.component.netty.configuration.client-mode* | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | Boolean | *camel.component.netty.configuration.connect-timeout* | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | Integer | *camel.component.netty.configuration.correlation-manager* | 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 {@link 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 | *camel.component.netty.configuration.decoder* | A custom ChannelHandler class that can be used to perform special marshalling of inbound payloads. | | ChannelHandler | *camel.component.netty.configuration.decoder-max-line-length* | The max line length to use for the textline codec. | 1024 | Integer | *camel.component.netty.configuration.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. | | List | *camel.component.netty.configuration.delimiter* | The delimiter to use for the textline codec. Possible values are LINE and NULL. | | TextLineDelimiter | *camel.component.netty.configuration.disconnect* | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | Boolean | *camel.component.netty.configuration.disconnect-on-no-reply* | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | Boolean | *camel.component.netty.configuration.enabled-protocols* | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *camel.component.netty.configuration.encoder* | A custom ChannelHandler class that can be used to perform special marshalling of outbound payloads. | | ChannelHandler | *camel.component.netty.configuration.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. | | List | *camel.component.netty.configuration.encoding* | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *camel.component.netty.configuration.host* | 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 | *camel.component.netty.configuration.keep-alive* | Setting to ensure socket is not closed due to inactivity | true | Boolean | *camel.component.netty.configuration.key-store-format* | Keystore format to be used for payload encryption. Defaults to ""JKS"" if not set | | String | *camel.component.netty.configuration.key-store-resource* | 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 | *camel.component.netty.configuration.lazy-channel-creation* | 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 | *camel.component.netty.configuration.native-transport* | 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 | *camel.component.netty.configuration.need-client-auth* | Configures whether the server needs client authentication when using SSL. | false | Boolean | *camel.component.netty.configuration.netty-server-bootstrap-factory* | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *camel.component.netty.configuration.network-interface* | 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 | *camel.component.netty.configuration.no-reply-log-level* | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. | | LoggingLevel | *camel.component.netty.configuration.options* | 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 | *camel.component.netty.configuration.passphrase* | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *camel.component.netty.configuration.port* | The host port number | | Integer | *camel.component.netty.configuration.producer-pool-enabled* | 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 {@link NettyCamelStateCorrelationManager} as correlation manager and configure it via the correlationManager option.

See also the correlationManager option for more details. | true | Boolean | *camel.component.netty.configuration.producer-pool-max-active* | 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 | Integer | *camel.component.netty.configuration.producer-pool-max-idle* | Sets the cap on the number of ""idle"" instances in the pool. | 100 | Integer | *camel.component.netty.configuration.producer-pool-min-evictable-idle* | 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 | *camel.component.netty.configuration.producer-pool-min-idle* | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | Integer | *camel.component.netty.configuration.protocol* | The protocol to use which can be tcp or udp. | | String | *camel.component.netty.configuration.receive-buffer-size* | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty.configuration.receive-buffer-size-predictor* | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | Integer | *camel.component.netty.configuration.reconnect* | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | Boolean | *camel.component.netty.configuration.reconnect-interval* | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | Integer | *camel.component.netty.configuration.request-timeout* | 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 | *camel.component.netty.configuration.reuse-address* | Setting to facilitate socket multiplexing | true | Boolean | *camel.component.netty.configuration.reuse-channel* | This option allows producers and consumers (in client mode) to reuse the same Netty {@link Channel} for the lifecycle of processing the {@link 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 {@link Exchange} is done; or disconnected if the disconnect option is set to true.

The reused {@link Channel} is stored on the {@link Exchange} as an exchange property with the key {@link NettyConstants#NETTY_CHANNEL} which allows you to obtain the channel during routing and use it as well. | false | Boolean | *camel.component.netty.configuration.security-provider* | Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. | | String | *camel.component.netty.configuration.send-buffer-size* | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty.configuration.server-closed-channel-exception-caught-log-level* | 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. | | LoggingLevel | *camel.component.netty.configuration.server-exception-caught-log-level* | If the server (NettyConsumer) catches an exception then its logged using this logging level. | | LoggingLevel | *camel.component.netty.configuration.server-initializer-factory* | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *camel.component.netty.configuration.ssl* | Setting to specify whether SSL encryption is applied to this endpoint | false | Boolean | *camel.component.netty.configuration.ssl-client-cert-headers* | 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 | *camel.component.netty.configuration.ssl-context-parameters* | To configure security using SSLContextParameters | | SSLContextParameters | *camel.component.netty.configuration.ssl-handler* | Reference to a class that could be used to return an SSL Handler | | SslHandler | *camel.component.netty.configuration.sync* | Setting to set endpoint as one-way or request-response | true | Boolean | *camel.component.netty.configuration.tcp-no-delay* | Setting to improve TCP protocol performance | true | Boolean | *camel.component.netty.configuration.textline* | 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. | false | Boolean | *camel.component.netty.configuration.transfer-exchange* | 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 | *camel.component.netty.configuration.trust-store-resource* | 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 | *camel.component.netty.configuration.udp-byte-array-codec* | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | Boolean | *camel.component.netty.configuration.udp-connectionless-sending* | 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 | *camel.component.netty.configuration.use-byte-buf* | If the useByteBuf is true, netty producer will turn the message body into {@link ByteBuf} before sending it out. | false | Boolean | *camel.component.netty.configuration.using-executor-service* | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | Boolean | *camel.component.netty.configuration.worker-count* | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | Integer | *camel.component.netty.configuration.worker-group* | 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 | *camel.component.netty.enabled* | Whether to enable auto configuration of the netty component. This is enabled by default. | | Boolean | *camel.component.netty.executor-service* | To use the given EventExecutorGroup. The option is a io.netty.util.concurrent.EventExecutorGroup type. | | String | *camel.component.netty.maximum-pool-size* | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | Integer | *camel.component.netty.ssl-context-parameters* | To configure security using SSLContextParameters. The option is a org.apache.camel.support.jsse.SSLContextParameters type. | | String | *camel.component.netty.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean | *camel.component.netty.configuration.client-pipeline-factory* | *Deprecated* | | ClientInitializerFactory | *camel.component.netty.configuration.key-store-file* | *Deprecated* Client side certificate keystore to be used for encryption | | File | *camel.component.netty.configuration.server-pipeline-factory* | *Deprecated* | | ServerInitializerFactory | *camel.component.netty.configuration.trust-store-file* | *Deprecated* Server side certificate keystore to be used for encryption | | File |=== // spring-boot-auto-configure 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 [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); poetry.setPoet(""Dr. Sarojini Naidu""); exchange.getOut().setBody(poetry); } } } }; ---- === 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-UsingBasicSSL/TLSconfigurationontheJettyComponent]] 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. ",12467,False,2324.088202244481,median "//------------------------------------------------------------------------------ // Implementation of AliPerformanceEff class. It keeps information from // comparison of reconstructed and MC particle tracks. In addtion, // it keeps selection cuts used during comparison. The comparison // information is stored in the ROOT histograms. Analysis of these // histograms can be done by using Analyse() class function. The result of // the analysis (histograms/graphs) are stored in the folder which is // a data member of AliPerformanceEff. // // Author: J.Otwinowski 04/02/2008 // Changes by J.Salzwedel 10/30/2014 //------------------------------------------------------------------------------ /* // after running comparison task, read the file, and get component gROOT->LoadMacro(""$ALICE_PHYSICS/PWGPP/Macros/LoadMyLibs.C""); LoadMyLibs(); TFile f(""Output.root""); AliPerformanceEff * compObj = (AliPerformanceEff*)coutput->FindObject(""AliPerformanceEff""); // Analyse comparison data compObj->Analyse(); // the output histograms/graphs will be stored in the folder ""folderEff"" compObj->GetAnalysisFolder()->ls(""*""); // user can save whole comparison object (or only folder with anlysed histograms) // in the seperate output file (e.g.) TFile fout(""Analysed_Eff.root"",""recreate""); compObj->Write(); // compObj->GetAnalysisFolder()->Write(); fout.Close(); */ #include #include #include #include #include ""THnSparse.h"" // #include ""AliExternalTrackParam.h"" #include ""AliLog.h"" #include ""AliTracker.h"" #include ""AliVEvent.h"" #include ""AliMCEvent.h"" #include ""AliMCParticle.h"" #include ""AliHeader.h"" #include ""AliGenEventHeader.h"" #include ""AliPerformanceEff.h"" using namespace std; #define TPC_PRIMARY_MIN_PT 0.08 ClassImp(AliPerformanceEff) bool AliPerformanceEff::fReadNClsTree = false; //_____________________________________________________________________________ AliPerformanceEff::AliPerformanceEff(TRootIOCtor* b): AliPerformanceObject(b), // histograms fEffHisto(NULL), fEffSecHisto(NULL), fTrackPtNCls(NULL), fTrackNClsFound(NULL), // histogram folder fAnalysisFolder(NULL), fNClsTreeFile(NULL), fNClsTree(NULL), fNClsVec(NULL) { // io constructor } //_____________________________________________________________________________ AliPerformanceEff::AliPerformanceEff(const Char_t* name, const Char_t* title, Int_t analysisMode, Bool_t hptGenerator): AliPerformanceObject(name,title), // histograms fEffHisto(NULL), fEffSecHisto(NULL), fTrackPtNCls(NULL), fTrackNClsFound(NULL), // histogram folder fAnalysisFolder(NULL), fNClsTreeFile(NULL), fNClsTree(NULL), fNClsVec(NULL) { // named constructor // SetAnalysisMode(analysisMode); SetHptGenerator(hptGenerator); Init(); } //_____________________________________________________________________________ AliPerformanceEff::~AliPerformanceEff() { // destructor if(fEffHisto) delete fEffHisto; fEffHisto=0; if(fEffSecHisto) delete fEffSecHisto; fEffSecHisto=0; if(fAnalysisFolder) delete fAnalysisFolder; fAnalysisFolder=0; if(fTrackPtNCls) delete fTrackPtNCls; fTrackPtNCls=0; if(fTrackNClsFound) delete fTrackNClsFound; fTrackNClsFound=0; } //_____________________________________________________________________________ void AliPerformanceEff::Init() { // Init histograms // // set pt bins Int_t nPtBins = 50; Double_t ptMin = 0.015, ptMax = 20.; if (GetAnalysisMode() == 0) ptMin = TPC_PRIMARY_MIN_PT; Double_t *binsPt = 0; if (IsHptGenerator()) { ptMax = 100.; } binsPt = CreateLogAxis(nPtBins,ptMin,ptMax); /* Int_t nPtBins = 31; Double_t binsPt[32] = {0.,0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.7,0.8,0.9,1.0,1.2,1.4,1.6,1.8,2.0,2.25,2.5,2.75,3.,3.5,4.,5.,6.,8.,10.}; Double_t ptMin = 0., ptMax = 10.; if(IsHptGenerator() == kTRUE) { nPtBins = 100; ptMin = 0.; ptMax = 100.; } */ //mceta:mcphi:mcpt:pid:recStatus:findable:charge:clones:fakes Int_t binsEffHisto[9]={30,144,nPtBins,5,2,2,3,fgkMaxClones+1,fgkMaxFakes+1}; Double_t minEffHisto[9]={-1.5,0.,ptMin,0.,0.,0.,-1.5,0,0}; Double_t maxEffHisto[9]={ 1.5,2.*TMath::Pi(), ptMax,5.,2.,2.,1.5,fgkMaxClones+1,fgkMaxFakes+1}; fEffHisto = new THnSparseF(""fEffHisto"",""mceta:mcphi:mcpt:pid:recStatus:findable:charge:nclones:nfakes"",9,binsEffHisto,minEffHisto,maxEffHisto); fEffHisto->SetBinEdges(2,binsPt); fEffHisto->GetAxis(0)->SetTitle(""#eta_{mc}""); fEffHisto->GetAxis(1)->SetTitle(""#phi_{mc} (rad)""); fEffHisto->GetAxis(2)->SetTitle(""p_{Tmc} (GeV/c)""); fEffHisto->GetAxis(3)->SetTitle(""pid""); fEffHisto->GetAxis(4)->SetTitle(""recStatus""); fEffHisto->GetAxis(5)->SetTitle(""findable""); fEffHisto->GetAxis(6)->SetTitle(""charge""); fEffHisto->GetAxis(7)->SetTitle(""nClones""); fEffHisto->GetAxis(8)->SetTitle(""nFakes""); fEffHisto->Sumw2(); //mceta:mcphi:mcpt:pid:recStatus:findable:mcR:mother_phi:mother_eta:charge:clones:fakes Int_t binsEffSecHisto[12]={30,60,nPtBins,5,2,2,100,60,30,3,fgkMaxClones+1,fgkMaxFakes+1}; Double_t minEffSecHisto[12]={-1.5,0.,ptMin,0.,0.,0.,0.,0.,-1.5,-1.5,0,0}; Double_t maxEffSecHisto[12]={ 1.5,2.*TMath::Pi(), ptMax,5.,2.,2.,200,2.*TMath::Pi(),1.5,1.5,fgkMaxClones+1,fgkMaxFakes+1}; fEffSecHisto = new THnSparseF(""fEffSecHisto"",""mceta:mcphi:mcpt:pid:recStatus:findable:mcR:mother_phi:mother_eta:charge:nclones:nfakes"",12,binsEffSecHisto,minEffSecHisto,maxEffSecHisto); fEffSecHisto->SetBinEdges(2,binsPt); fEffSecHisto->GetAxis(0)->SetTitle(""#eta_{mc}""); fEffSecHisto->GetAxis(1)->SetTitle(""#phi_{mc} (rad)""); fEffSecHisto->GetAxis(2)->SetTitle(""p_{Tmc} (GeV/c)""); fEffSecHisto->GetAxis(3)->SetTitle(""pid""); fEffSecHisto->GetAxis(4)->SetTitle(""recStatus""); fEffSecHisto->GetAxis(5)->SetTitle(""findable""); fEffSecHisto->GetAxis(6)->SetTitle(""mcR (cm)""); fEffSecHisto->GetAxis(7)->SetTitle(""mother_phi (rad)""); fEffSecHisto->GetAxis(8)->SetTitle(""mother_eta""); fEffSecHisto->GetAxis(9)->SetTitle(""charge""); fEffSecHisto->GetAxis(10)->SetTitle(""nClones""); fEffSecHisto->GetAxis(11)->SetTitle(""nFakes""); fEffSecHisto->Sumw2(); // init folder fAnalysisFolder = CreateFolder(""folderEff"",""Analysis Efficiency Folder""); if (fReadNClsTree) { fNClsTreeFile = new TFile(""nclTPCperMCtrack.root""); fNClsTree = (TTree*) fNClsTreeFile->Get(""nclPerMCtrack""); if (fNClsTree == NULL) { AliDebug(AliLog::kFatal, ""Stack not available for event""); } fNClsTree->SetBranchAddress(""nclPerTrack"", &fNClsVec); fTrackPtNCls = new TH1D(""fTrackPtNCls"", ""total number of cluster vs track Pt"", nPtBins, binsPt); fTrackNClsFound = new TH2D(""fTrackNClsFound"", ""found number of clusters vs mc number of clusters"", 80, 0., 320, 40, 0., 160); } } //_____________________________________________________________________________ void AliPerformanceEff::ProcessTPC(AliMCEvent* const mcEvent, AliVEvent *const vEvent) { // Fill TPC only efficiency comparison information if(!vEvent) return; if(!mcEvent) return; Int_t *labelsRec = NULL; labelsRec = new Int_t[vEvent->GetNumberOfTracks()]; if(!labelsRec) { Printf(""Cannot create labelsRec""); return; } for(Int_t i=0;iGetNumberOfTracks();i++) { labelsRec[i] = 0; } Int_t *labelsAllRec = NULL; labelsAllRec = new Int_t[vEvent->GetNumberOfTracks()]; if(!labelsAllRec) { delete [] labelsRec; Printf(""Cannot create labelsAllRec""); return; } for(Int_t i=0;iGetNumberOfTracks();i++) { labelsAllRec[i] = 0; } // loop over rec. tracks AliVTrack *vTrack=0; for (Int_t iTrack = 0; iTrack < vEvent->GetNumberOfTracks(); iTrack++) { vTrack = dynamic_cast(vEvent->GetTrack(iTrack)); if(!vTrack) continue; if(vTrack->Charge()==0) continue; // if not fUseKinkDaughters don't use tracks with kink index > 0 if(!fUseKinkDaughters && vTrack->GetKinkIndex(0) > 0) continue; //Int_t label = TMath::Abs(vTrack->GetLabel()); Int_t label = vTrack->GetTPCLabel(); //Use TPC-only label for TPC-only efficiency analysis labelsAllRec[iTrack]=label; // TPC only if(IsRecTPC(vTrack) != 0) { labelsRec[iTrack]=label; } } // // MC histograms for efficiency studies // Int_t nPart = mcEvent->GetNumberOfTracks(); Int_t nPrim = mcEvent->GetNumberOfPrimaries(); if (fReadNClsTree) { fNClsTree->GetEntry(vEvent->GetEventNumberInFile()); if (nPart != fNClsVec->size()) { AliDebug(AliLog::kFatal, ""nMCTracks mismatch""); } } //Int_t nPart = stack->GetNprimary(); for (Int_t iMc = 0; iMc < nPart; ++iMc) { if (iMc == 0) continue; //Cannot distinguish between track or fake track TParticle* particle = ((AliMCParticle*)mcEvent->GetTrack(iMc))->Particle(); if (!particle) continue; if (!particle->GetPDG()) continue; if (particle->GetPDG()->Charge() == 0.0) continue; Float_t mcpt = particle->Pt(); if (fReadNClsTree) fTrackPtNCls->Fill(mcpt, (*fNClsVec)[iMc]); // physical primary Bool_t prim = mcEvent->IsPhysicalPrimary(iMc); if(!prim) continue; // --- check for double filling in stack // use only particles with no daughters in the list of primaries //RS we just need to know if there are prim. daughters if (particle->GetFirstDaughter() != -1 && particle->GetFirstDaughter() < nPrim) continue; /*Bool_t findable = kFALSE; for(Int_t iRec=0; iRecGetNumberOfTracks(); ++iRec) { // check findable if(iMc == labelsAllRec[iRec]) { findable = IsFindable(mcEvent,iMc); break; } }*/ if (!HasTPCReference(mcEvent, iMc)) continue; //Filter particles that do not touch the TPC if (fReadNClsTree && (*fNClsVec)[iMc] == 0) continue; Bool_t findable = IsFindable(mcEvent,iMc); Bool_t recStatus = kFALSE; Int_t nClones = 0, nFakes = 0; Int_t nClsRec = 0; for(Int_t iRec=0; iRecGetNumberOfTracks(); ++iRec) { // check reconstructed if(iMc == labelsRec[iRec]) { if (recStatus && nClones < fgkMaxClones) nClones++; recStatus = kTRUE; if (fReadNClsTree) nClsRec = ((AliVTrack*) vEvent->GetTrack(iRec))->GetTPCNcls(); } //In order to relate the fake track to track parameters, we assign it to the best matching ESD track. if (labelsRec[iRec] < 0 && -labelsRec[iRec] == iMc && nFakes < fgkMaxFakes) nFakes++; } // Only 5 charged particle species (e,mu,pi,K,p) if (fCutsMC.IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) continue; // transform Pdg to Pid Int_t pid = TransformToPID(particle); Float_t mceta = particle->Eta(); Float_t mcphi = particle->Phi(); if(mcphi<0) mcphi += 2.*TMath::Pi(); Float_t charge = 0.; if (particle->GetPDG()->Charge() < 0) charge = -1.; else if (particle->GetPDG()->Charge() > 0) charge = 1.; if (fReadNClsTree && recStatus) fTrackNClsFound->Fill((*fNClsVec)[iMc], nClsRec); // Fill histograms Double_t vEffHisto[9] = {mceta, mcphi, mcpt, static_cast(pid), static_cast(recStatus), static_cast(findable), static_cast(charge), static_cast(nClones), static_cast(nFakes)}; fEffHisto->Fill(vEffHisto); } if(labelsRec) delete [] labelsRec; labelsRec = 0; if(labelsAllRec) delete [] labelsAllRec; labelsAllRec = 0; } //_____________________________________________________________________________ void AliPerformanceEff::ProcessTPCSec(AliMCEvent* const mcEvent, AliVEvent *const vEvent) { // Fill TPC only efficiency comparison information for secondaries if(!vEvent) return; if(!mcEvent) return; AliStack *stack = mcEvent->Stack(); if (!stack) { AliDebug(AliLog::kError, ""Stack not available for event""); return; } Int_t *labelsRecSec = NULL; labelsRecSec = new Int_t[vEvent->GetNumberOfTracks()]; if(!labelsRecSec) { Printf(""Cannot create labelsRecSec""); return; } for(Int_t i=0;iGetNumberOfTracks();i++) { labelsRecSec[i] = 0; } Int_t *labelsAllRecSec = NULL; labelsAllRecSec = new Int_t[vEvent->GetNumberOfTracks()]; if(!labelsAllRecSec) { delete [] labelsRecSec; Printf(""Cannot create labelsAllRecSec""); return; } for(Int_t i=0;iGetNumberOfTracks();i++) { labelsAllRecSec[i] = 0; } // loop over rec. tracks AliVTrack *vTrack=0; Int_t multAll=0, multRec=0; for (Int_t iTrack = 0; iTrack < vEvent->GetNumberOfTracks(); iTrack++) { vTrack = dynamic_cast(vEvent->GetTrack(iTrack)); if(!vTrack) continue; if(vTrack->Charge()==0) continue; // if not fUseKinkDaughters don't use tracks with kink index > 0 if(!fUseKinkDaughters && vTrack->GetKinkIndex(0) > 0) continue; //Int_t label = TMath::Abs(track->GetLabel()); Int_t label = vTrack->GetTPCLabel(); //Use TPC-only label for TPC-only efficiency analysis labelsAllRecSec[multAll]=label; multAll++; // TPC only if(IsRecTPC(vTrack) != 0) { labelsRecSec[multRec]=label; multRec++; } } // // MC histograms for efficiency studies // if(mcEvent) { Int_t nPart = mcEvent->GetNumberOfTracks(); //Int_t nPart = stack->GetNprimary(); if (fReadNClsTree) { fNClsTree->GetEntry(vEvent->GetEventNumberInFile()); if (nPart != fNClsVec->size()) { AliDebug(AliLog::kFatal, ""nMCTracks mismatch""); } } for (Int_t iMc = 0; iMc < nPart; ++iMc) { if (iMc == 0) continue; //Cannot distinguish between track or fake track TParticle* particle = ((AliMCParticle*)mcEvent->GetTrack(iMc))->Particle(); if (!particle) continue; if (!particle->GetPDG()) continue; if (particle->GetPDG()->Charge() == 0.0) continue; // physical primary Bool_t prim = mcEvent->IsPhysicalPrimary(iMc); // only secondaries which can be reconstructed at TPC if(prim) continue; //Float_t radius = TMath::Sqrt(particle->Vx()*particle->Vx()+particle->Vy()*particle->Vy()+particle->Vz()*particle->Vz()); //if(radius > fCutsMC->GetMaxR()) continue; // only secondary electrons from gamma conversion //if( TMath::Abs(particle->GetPdgCode())!=fCutsMC->GetEM() || particle->GetUniqueID() != 5) continue; /*Bool_t findable = kFALSE; for(Int_t iRec=0; iRecGetTrack(iMc))->XvYvZv(xyz); if ((xyz[2] >= 250 && particle->Pz() > 0) || (xyz[2] <= -250 && particle->Pz() < 0)) continue; //Filter particles created at high Z in the TPC readout electronics and flying away if (sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1]) - fabs(666. / particle->Pt()) > 250) continue; //will never touch the TPC if (fReadNClsTree && (*fNClsVec)[iMc] == 0) continue; Bool_t findable = IsFindable(mcEvent,iMc); Bool_t recStatus = kFALSE; Int_t nClones = 0, nFakes = 0; Int_t nClsRec = 0; for(Int_t iRec=0; iRecGetTrack(iRec))->GetTPCNcls(); } //In order to relate the fake track to track parameters, we assign it to the best matching ESD track. if (labelsRecSec[iRec] < 0 && -labelsRecSec[iRec] == iMc && nFakes < fgkMaxFakes) nFakes++; } // Only 5 charged particle species (e,mu,pi,K,p) if (fCutsMC.IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) continue; // transform Pdg to Pid Int_t pid = TransformToPID(particle); Float_t mceta = particle->Eta(); Float_t mcphi = particle->Phi(); if(mcphi<0) mcphi += 2.*TMath::Pi(); Float_t mcpt = particle->Pt(); Float_t mcR = particle->R(); if (fReadNClsTree && recStatus) fTrackNClsFound->Fill((*fNClsVec)[iMc], nClsRec); // get info about mother Int_t motherLabel = particle->GetMother(0); if(motherLabel < 0) continue; TParticle *mother = ((AliMCParticle*)mcEvent->GetTrack(motherLabel))->Particle(); if(!mother) continue; Float_t mother_eta = mother->Eta(); Float_t mother_phi = mother->Phi(); if(mother_phi<0) mother_phi += 2.*TMath::Pi(); Float_t charge = 0.; if (particle->GetPDG()->Charge() < 0) charge = -1.; else if (particle->GetPDG()->Charge() > 0) charge = 1.; // Fill histograms Double_t vEffSecHisto[12] = { mceta, mcphi, mcpt, static_cast(pid), static_cast(recStatus), static_cast(findable), mcR, mother_phi, mother_eta, static_cast(charge), static_cast(nClones), static_cast(nFakes) }; fEffSecHisto->Fill(vEffSecHisto); } } if(labelsRecSec) delete [] labelsRecSec; labelsRecSec = 0; if(labelsAllRecSec) delete [] labelsAllRecSec; labelsAllRecSec = 0; } //_____________________________________________________________________________ void AliPerformanceEff::ProcessTPCITS(AliMCEvent* const mcEvent, AliVEvent *const vEvent) { // Fill efficiency comparison information if(!vEvent) return; if(!mcEvent) return; Int_t *labelsRecTPCITS = NULL; labelsRecTPCITS = new Int_t[vEvent->GetNumberOfTracks()]; if(!labelsRecTPCITS) { Printf(""Cannot create labelsRecTPCITS""); return; } for(Int_t i=0;iGetNumberOfTracks();i++) { labelsRecTPCITS[i] = 0; } Int_t *labelsAllRecTPCITS = NULL; labelsAllRecTPCITS = new Int_t[vEvent->GetNumberOfTracks()]; if(!labelsAllRecTPCITS) { delete [] labelsRecTPCITS; Printf(""Cannot create labelsAllRecTPCITS""); return; } for(Int_t i=0;iGetNumberOfTracks();i++) { labelsAllRecTPCITS[i] = 0; } // loop over rec. tracks AliVTrack *vTrack=0; for (Int_t iTrack = 0; iTrack < vEvent->GetNumberOfTracks(); iTrack++) { vTrack = dynamic_cast(vEvent->GetTrack(iTrack)); if(!vTrack) continue; if(vTrack->Charge()==0) continue; // if not fUseKinkDaughters don't use tracks with kink index > 0 if(!fUseKinkDaughters && vTrack->GetKinkIndex(0) > 0) continue; //Int_t label = TMath::Abs(track->GetLabel()); Int_t label = vTrack->GetLabel(); //Use global label for combined efficiency analysis labelsAllRecTPCITS[iTrack]=label; // iTPC+ITS if(IsRecTPCITS(vTrack) != 0) labelsRecTPCITS[iTrack]=label; } // // MC histograms for efficiency studies // //Int_t nPart = stack->GetNtrack(); Int_t nPart = mcEvent->GetNumberOfPrimaries(); for (Int_t iMc = 0; iMc < nPart; ++iMc) { if (iMc == 0) continue; //Cannot distinguish between track or fake track TParticle* particle = ((AliMCParticle*)mcEvent->GetTrack(iMc))->Particle(); if (!particle) continue; if (!particle->GetPDG()) continue; if (particle->GetPDG()->Charge() == 0.0) continue; // physical primary Bool_t prim = mcEvent->IsPhysicalPrimary(iMc); if(!prim) continue; Bool_t findable = IsFindable(mcEvent,iMc); Bool_t recStatus = kFALSE; Int_t nClones = 0, nFakes = 0; for(Int_t iRec=0; iRecGetNumberOfTracks(); ++iRec) { // check reconstructed if(iMc == labelsRecTPCITS[iRec]) { if (recStatus && nClones < fgkMaxClones) nClones++; recStatus = kTRUE; } //In order to relate the fake track to track parameters, we assign it to the best matching reconstructed track. if (labelsRecTPCITS[iRec] < 0 && -labelsRecTPCITS[iRec] == iMc && nFakes < fgkMaxFakes) nFakes++; } // Only 5 charged particle species (e,mu,pi,K,p) if (fCutsMC.IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) continue; // transform Pdg to Pid Int_t pid = TransformToPID(particle); Float_t mceta = particle->Eta(); Float_t mcphi = particle->Phi(); if(mcphi<0) mcphi += 2.*TMath::Pi(); Float_t mcpt = particle->Pt(); Float_t charge = 0.; if (particle->GetPDG()->Charge() < 0) charge = -1.; else if (particle->GetPDG()->Charge() > 0) charge = 1.; // Fill histograms Double_t vEffHisto[9] = { mceta, mcphi, mcpt, static_cast(pid), static_cast(recStatus), static_cast(findable), static_cast(charge), static_cast(nClones), static_cast(nFakes)}; fEffHisto->Fill(vEffHisto); } if(labelsRecTPCITS) delete [] labelsRecTPCITS; labelsRecTPCITS = 0; if(labelsAllRecTPCITS) delete [] labelsAllRecTPCITS; labelsAllRecTPCITS = 0; } //_____________________________________________________________________________ void AliPerformanceEff::ProcessConstrained(AliMCEvent* const mcEvent, AliVEvent *const vEvent) { // Process MC vs reconstructed comparison information for TPC-only tracks // constrained to the primary vertex if(!vEvent) return; if(!mcEvent) return; Int_t *labelsRecConstrained = NULL; labelsRecConstrained = new Int_t[vEvent->GetNumberOfTracks()]; if(!labelsRecConstrained) { Printf(""Cannot create labelsRecConstrained""); return; } for(Int_t i=0;iGetNumberOfTracks();i++) { labelsRecConstrained[i] = 0; } Int_t *labelsAllRecConstrained = NULL; labelsAllRecConstrained = new Int_t[vEvent->GetNumberOfTracks()]; if(!labelsAllRecConstrained) { delete [] labelsRecConstrained; Printf(""Cannot create labelsAllRecConstrained""); return; } for(Int_t i=0;iGetNumberOfTracks();i++) { labelsAllRecConstrained[i] = 0; } // loop over rec. tracks AliVTrack *vTrack=0; for (Int_t iTrack = 0; iTrack < vEvent->GetNumberOfTracks(); iTrack++) { vTrack = dynamic_cast(vEvent->GetTrack(iTrack)); if(!vTrack) continue; // if not fUseKinkDaughters don't use tracks with kink index > 0 if(!fUseKinkDaughters && vTrack->GetKinkIndex(0) > 0) continue; //Int_t label = TMath::Abs(track->GetLabel()); Int_t label = vTrack->GetLabel(); labelsAllRecConstrained[iTrack]=label; // Constrained if(IsRecConstrained(vTrack) != 0) labelsRecConstrained[iTrack]=label; } // // MC histograms for efficiency studies // //Int_t nPart = stack->GetNtrack(); Int_t nPart = mcEvent->GetNumberOfPrimaries(); for (Int_t iMc = 0; iMc < nPart; ++iMc) { if (iMc == 0) continue; //Cannot distinguish between track or fake track TParticle* particle = ((AliMCParticle*)mcEvent->GetTrack(iMc))->Particle(); if (!particle) continue; if (!particle->GetPDG()) continue; if (particle->GetPDG()->Charge() == 0.0) continue; // physical primary Bool_t prim = mcEvent->IsPhysicalPrimary(iMc); if(!prim) continue; Bool_t findable = IsFindable(mcEvent,iMc); Bool_t recStatus = kFALSE; Int_t nClones = 0, nFakes = 0; for(Int_t iRec=0; iRecGetNumberOfTracks(); ++iRec) { // check reconstructed if(iMc == labelsRecConstrained[iRec]) { if (recStatus && nClones < fgkMaxClones) nClones++; recStatus = kTRUE; } //In order to relate the fake track to track parameters, we assign it to the best matching reconstructed track. if (labelsRecConstrained[iRec] < 0 && -labelsRecConstrained[iRec] == iMc && nFakes < fgkMaxFakes) nFakes++; } // Only 5 charged particle species (e,mu,pi,K,p) if (fCutsMC.IsPdgParticle(TMath::Abs(particle->GetPdgCode())) == kFALSE) continue; // transform Pdg to Pid Int_t pid = TransformToPID(particle); Float_t mceta = particle->Eta(); Float_t mcphi = particle->Phi(); if(mcphi<0) mcphi += 2.*TMath::Pi(); Float_t mcpt = particle->Pt(); Float_t charge = 0.; if (particle->GetPDG()->Charge() < 0) charge = -1.; else if (particle->GetPDG()->Charge() > 0) charge = 1.; // Fill histograms Double_t vEffHisto[9] = { mceta, mcphi, mcpt, static_cast(pid), static_cast(recStatus), static_cast(findable), static_cast(charge), static_cast(nClones), static_cast(nFakes) }; fEffHisto->Fill(vEffHisto); } if(labelsRecConstrained) delete [] labelsRecConstrained; labelsRecConstrained = 0; if(labelsAllRecConstrained) delete [] labelsAllRecConstrained; labelsAllRecConstrained = 0; } //_____________________________________________________________________________ void AliPerformanceEff::Exec(AliMCEvent* const mcEvent, AliVEvent *const vEvent, AliVfriendEvent *const vFriendEvent, const Bool_t bUseMC, const Bool_t bUseVfriend) { // Process comparison information if(!vEvent) { Error(""Exec"",""vEvent not available""); return; } AliHeader* header = 0; AliGenEventHeader* genHeader = 0; TArrayF vtxMC(3); if(bUseMC) { if(!mcEvent) { Error(""Exec"",""mcEvent not available""); return; } // get MC event header header = mcEvent->Header(); if (!header) { Error(""Exec"",""Header not available""); return; } // get MC vertex genHeader = header->GenEventHeader(); if (!genHeader) { Error(""Exec"",""Could not retrieve genHeader from Header""); return; } genHeader->PrimaryVertex(vtxMC); } else { Error(""Exec"",""MC information required!""); return; } // use V friends if(bUseVfriend) { if(!vFriendEvent) { Error(""Exec"",""esdFriend not available""); return; } } // // Process events // if(GetAnalysisMode() == 0) ProcessTPC(mcEvent,vEvent); else if(GetAnalysisMode() == 1) ProcessTPCITS(mcEvent,vEvent); else if(GetAnalysisMode() == 2) ProcessConstrained(mcEvent,vEvent); else if(GetAnalysisMode() == 5) ProcessTPCSec(mcEvent,vEvent); else { printf(""ERROR: AnalysisMode %d \\n"",fAnalysisMode); return; } } //_____________________________________________________________________________ Int_t AliPerformanceEff::TransformToPID(TParticle *particle) { // transform Pdg to Pid // Pdg convension is different for hadrons and leptons // (e.g. K+/K- = 321/-321; e+/e- = -11/11 ) Int_t pid = -1; if( TMath::Abs(particle->GetPdgCode())==fCutsMC.GetEM() ) pid = 0; if( TMath::Abs(particle->GetPdgCode())==fCutsMC.GetMuM() ) pid = 1; if( TMath::Abs(particle->GetPdgCode())==fCutsMC.GetPiP() ) pid = 2; if( TMath::Abs(particle->GetPdgCode())==fCutsMC.GetKP() ) pid = 3; if( TMath::Abs(particle->GetPdgCode())==fCutsMC.GetProt() ) pid = 4; return pid; } //_____________________________________________________________________________ Bool_t AliPerformanceEff::IsFindable(const AliMCEvent *mcEvent, Int_t label) { // // Determine if track is findable // if (fReadNClsTree) { return((*fNClsVec)[label] > 70); } if(!mcEvent) return kFALSE; AliMCParticle *mcParticle = (AliMCParticle*) mcEvent->GetTrack(label); if(!mcParticle) return kFALSE; Int_t counter; Float_t tpcTrackLength = mcParticle->GetTPCTrackLength(AliTracker::GetBz(),TPC_PRIMARY_MIN_PT,counter,3.0); //printf(""tpcTrackLength %f \\n"", tpcTrackLength); return (tpcTrackLength>fCutsMC.GetMinTrackLength()); } Bool_t AliPerformanceEff::HasTPCReference(const AliMCEvent *mcEvent, Int_t label) { // // Determine if track is findable // if(!mcEvent) return kFALSE; AliMCParticle *mcParticle = (AliMCParticle*) mcEvent->GetTrack(label); if(!mcParticle) return kFALSE; for (int i = 0;i < mcParticle->GetNumberOfTrackReferences();i++) { if (mcParticle->GetTrackReference(i)->DetectorId() == AliTrackReference::kTPC) return(true); } return(false); } //_____________________________________________________________________________ Bool_t AliPerformanceEff::IsRecTPC(AliVTrack *vTrack) { // // Check whether track is reconstructed in TPC // if(!vTrack) return kFALSE; Bool_t recStatus = kFALSE; const AliExternalTrackParam *track = vTrack->GetTPCInnerParam(); if(!track) return recStatus; if(vTrack->GetTPCNcls()>fCutsRC.GetMinNClustersTPC()) recStatus = kTRUE; return recStatus; } //_____________________________________________________________________________ Bool_t AliPerformanceEff::IsRecTPCITS(AliVTrack *vTrack) { // // Check whether track is reconstructed in TPCITS // if(!vTrack) return kFALSE; Bool_t recStatus = kFALSE; if ((vTrack->GetStatus()&AliVTrack::kTPCrefit)==0) return recStatus; // TPC refit if ((vTrack->GetStatus()&AliVTrack::kITSrefit)==0) return recStatus; // ITS refit if (vTrack && vTrack->GetITSclusters(0)GetStatus()&AliVTrack::kTPCrefit)==0) return kFALSE; // TPC refit if (vTrack->GetTPCNcls()GetConstrainedParam(); if(!track) return recStatus; if(vTrack->GetITSclusters(0)IsEmpty()) return 1; TIterator* iter = list->MakeIterator(); TObject* obj = 0; // collection of generated histograms Int_t count=0; while((obj = iter->Next()) != 0) { AliPerformanceEff* entry = dynamic_cast(obj); if (entry == 0) continue; fEffHisto->Add(entry->fEffHisto); fEffSecHisto->Add(entry->fEffSecHisto); if (fTrackPtNCls && entry->fTrackPtNCls) fTrackPtNCls->Add(entry->fTrackPtNCls); if (fTrackNClsFound && entry->fTrackNClsFound) fTrackNClsFound->Add(entry->fTrackNClsFound); count++; } return count; } //_____________________________________________________________________________ void AliPerformanceEff::Analyse() { // Analyse comparison information and store output histograms // in the folder ""folderEff"" // TH1::AddDirectory(kFALSE); TObjArray *aFolderObj = new TObjArray; if(!aFolderObj) return; // char title[256]; // // efficiency vs pt // if(GetAnalysisMode() != 5) { fEffHisto->GetAxis(0)->SetRangeUser(-0.9,0.89); // eta range fEffHisto->GetAxis(2)->SetRangeUser(TPC_PRIMARY_MIN_PT,19.99); // pt range , primaries below 0.1 do not exist in TPC // rec efficiency vs pt fEffHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(2, ""ptRecEff"", ""rec. efficiency"", 0)); aFolderObj->Add(AddHistoEff(2, ""ptClone"", ""clone rate"", 1)); aFolderObj->Add(AddHistoEff(2, ""ptFake"", ""fake rate"", 2)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(2, ""ptRecEffNeg"", ""rec. efficiency neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(2, ""ptRecEffPos"", ""rec. efficiency pos."", 0)); // rec efficiency vs pid vs pt fEffHisto->GetAxis(3)->SetRange(3,3); // pions fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(2, ""ptRecEffPi"", ""rec. efficiency (pions)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(2, ""ptRecEffPiNeg"", ""rec. efficiency (pions) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(2, ""ptRecEffPiPos"", ""rec. efficiency (pions) pos."", 0)); fEffHisto->GetAxis(3)->SetRange(4,4); // kaons fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(2, ""ptRecEffK"", ""rec. efficiency (kaons)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(2, ""ptRecEffKNeg"", ""rec. efficiency (kaons) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(2, ""ptRecEffKPos"", ""rec. efficiency (kaons) pos."", 0)); fEffHisto->GetAxis(3)->SetRange(5,5); // protons fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(2, ""ptRecEffP"", ""rec. efficiency (protons)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(2, ""ptRecEffPNeg"", ""rec. efficiency (protons) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(2, ""ptRecEffPPos"", ""rec. efficiency (protons) pos."", 0)); // findable efficiency vs pt fEffHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset fEffHisto->GetAxis(5)->SetRange(2,2); // findable fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(2, ""ptRecEffF"", ""rec. efficiency (findable)"", 0)); aFolderObj->Add(AddHistoEff(2, ""ptCloneF"", ""clone rate (findable)"", 1)); aFolderObj->Add(AddHistoEff(2, ""ptFakeF"", ""fake rate (findable)"", 2)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(2, ""ptRecEffFNeg"", ""rec. efficiency (findable) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(2, ""ptRecEffFPos"", ""rec. efficiency (findable) pos."", 0)); // // efficiency vs eta // fEffHisto->GetAxis(0)->SetRangeUser(-1.5,1.49); // eta range fEffHisto->GetAxis(2)->SetRangeUser(0.1,19.99); // pt range fEffHisto->GetAxis(5)->SetRange(1,0); //reset // rec efficiency vs eta fEffHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(0, ""etaRecEff"", ""rec. efficiency"", 0)); aFolderObj->Add(AddHistoEff(0, ""etaClone"", ""clone rate"", 1)); aFolderObj->Add(AddHistoEff(0, ""etaFake"", ""fake rate"", 2)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(0, ""etaRecEffNeg"", ""rec. efficiency neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(0, ""etaRecEffPos"", ""rec. efficiency pos."", 0)); // rec efficiency vs pid vs eta fEffHisto->GetAxis(3)->SetRange(3,3); // pions fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(0, ""etaRecEffPi"", ""rec. efficiency (pions)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(0, ""etaRecEffPiNeg"", ""rec. efficiency (pions) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(0, ""etaRecEffPiPos"", ""rec. efficiency (pions) pos."", 0)); fEffHisto->GetAxis(3)->SetRange(4,4); // kaons fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(0, ""etaRecEffK"", ""rec. efficiency (kaons)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(0, ""etaRecEffKNeg"", ""rec. efficiency (kaons) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(0, ""etaRecEffKPos"", ""rec. efficiency (kaons) pos."", 0)); fEffHisto->GetAxis(3)->SetRange(5,5); // protons fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(0, ""etaRecEffP"", ""rec. efficiency (protons)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(0, ""etaRecEffPNeg"", ""rec. efficiency (protons) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(0, ""etaRecEffPPos"", ""rec. efficiency (protons) pos."", 0)); // findable efficiency vs eta fEffHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset fEffHisto->GetAxis(5)->SetRange(2,2); // findable fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(0, ""etaRecEffF"", ""rec. efficiency (findable)"", 0)); aFolderObj->Add(AddHistoEff(0, ""etaCloneF"", ""clone rate (findable)"", 1)); aFolderObj->Add(AddHistoEff(0, ""etaFakeF"", ""fake rate (findable)"", 2)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(0, ""etaRecEffFNeg"", ""rec. efficiency (findable) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(0, ""etaRecEffFPos"", ""rec. efficiency (findable) pos."", 0)); // // efficiency vs phi // fEffHisto->GetAxis(0)->SetRangeUser(-0.9,0.89); // eta range fEffHisto->GetAxis(2)->SetRangeUser(0.1,19.99); // pt range fEffHisto->GetAxis(5)->SetRange(1,0); //reset // rec efficiency vs phi fEffHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(1, ""phiRecEff"", ""rec. efficiency"", 0)); aFolderObj->Add(AddHistoEff(1, ""phiClone"", ""clone rate"", 1)); aFolderObj->Add(AddHistoEff(1, ""phiFake"", ""fake rate"", 2)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(1, ""phiRecEffNeg"", ""rec. efficiency neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(1, ""phiRecEffPos"", ""rec. efficiency pos."", 0)); // rec efficiency vs pid vs phi fEffHisto->GetAxis(3)->SetRange(3,3); // pions fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(1, ""phiRecEffPi"", ""rec. efficiency (pions)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(1, ""phiRecEffPiNeg"", ""rec. efficiency (pions) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(1, ""phiRecEffPiPos"", ""rec. efficiency (pions) pos."", 0)); fEffHisto->GetAxis(3)->SetRange(4,4); // kaons fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(1, ""phiRecEffK"", ""rec. efficiency (kaons)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(1, ""phiRecEffKNeg"", ""rec. efficiency (kaons) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(1, ""phiRecEffKPos"", ""rec. efficiency (kaons) pos."", 0)); fEffHisto->GetAxis(3)->SetRange(5,5); // protons fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(1, ""phiRecEffP"", ""rec. efficiency (protons)"", 0)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(1, ""phiRecEffPNeg"", ""rec. efficiency (protons) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(1, ""phiRecEffPPos"", ""rec. efficiency (protons) pos."", 0)); // findable efficiency vs phi fEffHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset fEffHisto->GetAxis(5)->SetRange(2,2); // findable fEffHisto->GetAxis(6)->SetRangeUser(-2.,2.); // charge all aFolderObj->Add(AddHistoEff(1, ""phiRecEffF"", ""rec. efficiency (findable)"", 0)); aFolderObj->Add(AddHistoEff(1, ""phiCloneF"", ""clone rate (findable)"", 1)); aFolderObj->Add(AddHistoEff(1, ""phiFakeF"", ""fake rate (findable)"", 2)); fEffHisto->GetAxis(6)->SetRangeUser(-2.,0.); // charge negativ aFolderObj->Add(AddHistoEff(1, ""phiRecEffFNeg"", ""rec. efficiency (findable) neg."", 0)); fEffHisto->GetAxis(6)->SetRangeUser(0.,2.); // charge positiv aFolderObj->Add(AddHistoEff(1, ""phiRecEffFPos"", ""rec. efficiency (findable) pos."", 0)); } else { // Float_t minEta=-1.5, maxEta=1.49; Float_t minR=0.0, maxR=150.0; Float_t minPt=15e-3, maxPt=19.99; // mother eta range fEffSecHisto->GetAxis(8)->SetRangeUser(minEta,maxEta); // particle creation radius range fEffSecHisto->GetAxis(6)->SetRangeUser(minR,maxR); // particle eta and pt cut fEffSecHisto->GetAxis(0)->SetRangeUser(-0.9,0.89); fEffSecHisto->GetAxis(2)->SetRangeUser(minPt,maxPt); // rec efficiency vs pt aFolderObj->Add(AddHistoEff(2, ""ptRecEff"", ""rec. efficiency"", 0, 1)); aFolderObj->Add(AddHistoEff(2, ""ptClone"", ""clone rate"", 1, 1)); aFolderObj->Add(AddHistoEff(2, ""ptFake"", ""fake rate"", 2, 1)); // rec efficiency vs pid vs pt fEffSecHisto->GetAxis(3)->SetRange(1,1); // electrons aFolderObj->Add(AddHistoEff(2, ""ptRecEffEle"", ""rec. efficiency (electrons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(3,3); // pions aFolderObj->Add(AddHistoEff(2, ""ptRecEffPi"", ""rec. efficiency (pions)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(4,4); // kaons aFolderObj->Add(AddHistoEff(2, ""ptRecEffK"", ""rec. efficiency (kaons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(5,5); // protons aFolderObj->Add(AddHistoEff(2, ""ptRecEffP"", ""rec. efficiency (protons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset // findable efficiency vs pt fEffSecHisto->GetAxis(5)->SetRange(2,2); // findable aFolderObj->Add(AddHistoEff(2, ""ptRecEffF"", ""rec. efficiency (findable)"", 0, 1)); aFolderObj->Add(AddHistoEff(2, ""ptCloneF"", ""clone rate (findable)"", 1, 1)); aFolderObj->Add(AddHistoEff(2, ""ptFakeF"", ""fake rate (findable)"", 2, 1)); // // efficiency vs eta // fEffSecHisto->GetAxis(0)->SetRangeUser(minEta,maxEta); fEffSecHisto->GetAxis(2)->SetRangeUser(0.1,maxPt); fEffSecHisto->GetAxis(5)->SetRange(1,0); //reset aFolderObj->Add(AddHistoEff(0, ""etaRecEff"", ""rec. efficiency"", 0, 1)); aFolderObj->Add(AddHistoEff(0, ""etaClone"", ""clone rate"", 1, 1)); aFolderObj->Add(AddHistoEff(0, ""etaFake"", ""fake rate"", 2, 1)); // rec efficiency vs pid vs eta fEffSecHisto->GetAxis(3)->SetRange(1,1); // electrons aFolderObj->Add(AddHistoEff(0, ""etaRecEffEle"", ""rec. efficiency (electrons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(3,3); // pions aFolderObj->Add(AddHistoEff(0, ""etaRecEffPi"", ""rec. efficiency (pions)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(4,4); // kaons aFolderObj->Add(AddHistoEff(0, ""etaRecEffK"", ""rec. efficiency (kaons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(5,5); // protons aFolderObj->Add(AddHistoEff(0, ""etaRecEffP"", ""rec. efficiency (protons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset // findable efficiency vs eta fEffSecHisto->GetAxis(5)->SetRange(2,2); // findable aFolderObj->Add(AddHistoEff(0, ""etaRecEffF"", ""rec. efficiency (findable)"", 0, 1)); aFolderObj->Add(AddHistoEff(0, ""etaCloneF"", ""clone rate (findable)"", 1, 1)); aFolderObj->Add(AddHistoEff(0, ""etaFakeF"", ""fake rate (findable)"", 2, 1)); // // efficiency vs phi // fEffSecHisto->GetAxis(0)->SetRangeUser(-0.9,0.89); fEffSecHisto->GetAxis(2)->SetRangeUser(0.1,maxPt); fEffSecHisto->GetAxis(5)->SetRange(1,0); //reset aFolderObj->Add(AddHistoEff(1, ""phiRecEff"", ""rec. efficiency"", 0, 1)); aFolderObj->Add(AddHistoEff(1, ""phiClone"", ""clone rate"", 1, 1)); aFolderObj->Add(AddHistoEff(1, ""phiFake"", ""fake rate"", 2, 1)); // rec efficiency vs pid vs phi fEffSecHisto->GetAxis(3)->SetRange(1,1); aFolderObj->Add(AddHistoEff(1, ""phiRecEffEle"", ""rec. efficiency (electrons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(3,3); // pions aFolderObj->Add(AddHistoEff(1, ""phiRecEffPi"", ""rec. efficiency (pions)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(4,4); // kaons aFolderObj->Add(AddHistoEff(1, ""phiRecEffK"", ""rec. efficiency (kaons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRange(5,5); // protons aFolderObj->Add(AddHistoEff(1, ""phiRecEffP"", ""rec. efficiency (protons)"", 0, 1)); fEffSecHisto->GetAxis(3)->SetRangeUser(0.,5.); //reset // findable efficiency vs phi fEffSecHisto->GetAxis(5)->SetRange(2,2); // findable aFolderObj->Add(AddHistoEff(1, ""phiRecEffF"", ""rec. efficiency (findable)"", 0, 1)); aFolderObj->Add(AddHistoEff(1, ""phiCloneF"", ""clone rate (findable)"", 1, 1)); aFolderObj->Add(AddHistoEff(1, ""phiFakeF"", ""fake rate (findable)"", 2, 1)); } THnSparseF* h = (GetAnalysisMode() != 5) ? fEffHisto : fEffSecHisto; for (Int_t i = 0;i < h->GetNdimensions();i++) { h->GetAxis(i)->SetRange(1,0); //Reset Range } // export objects to analysis folder fAnalysisFolder = ExportToFolder(aFolderObj); // delete only TObjArray if(aFolderObj) delete aFolderObj; } //_____________________________________________________________________________ TFolder* AliPerformanceEff::ExportToFolder(TObjArray * array) { // recreate folder avery time and export objects to new one // AliPerformanceEff * comp=this; TFolder *folder = comp->GetAnalysisFolder(); TString name, title; TFolder *newFolder = 0; Int_t i = 0; Int_t size = array->GetSize(); if(folder) { // get name and title from old folder name = folder->GetName(); title = folder->GetTitle(); // delete old one delete folder; // create new one newFolder = CreateFolder(name.Data(),title.Data()); newFolder->SetOwner(); // add objects to folder while(i < size) { newFolder->Add(array->At(i)); i++; } } return newFolder; } //_____________________________________________________________________________ TFolder* AliPerformanceEff::CreateFolder(TString name,TString title) { // create folder for analysed histograms // TFolder *folder = 0; folder = new TFolder(name.Data(),title.Data()); return folder; } TH1D* AliPerformanceEff::WeightedProjection(THnSparseF* src, Int_t axis, Int_t nWeights, Int_t* weightCoords) { THnSparseF* tmp = (THnSparseF*) src->Clone(); Int_t i; for (i = 0;i < tmp->GetNbins();i++) { Int_t coords[12]; tmp->GetBinContent(i, coords); Int_t weight = 0, j; for (j = 0;j < nWeights;j++) { //The coordinates range from 1 to maxClones / maxFakes + 1, so we have to subtract one weight += coords[weightCoords[j]] - 1; } tmp->SetBinContent(i, weight); tmp->SetBinError(i, weight); } TH1D* ret = tmp->Projection(axis); delete tmp; return(ret); } //_____________________________________________________________________________ TH1D* AliPerformanceEff::AddHistoEff(Int_t axis, const Char_t *name, const Char_t* vsTitle, const Int_t type, const Int_t secondary) { // Create and add rec efficiency vs pt, eta, phi char title[256]; TH1D *recc = NULL; THnSparseF* EffHisto = secondary ? fEffSecHisto : fEffHisto; Int_t axis_clone = secondary ? 10 : 7; Int_t axis_fake = secondary ? 11 : 8; Int_t axis_all[3] = {4, axis_clone, axis_fake}; if (type == 0) // Efficiency { EffHisto->GetAxis(4)->SetRange(1.,2.); // all TH1D *all = EffHisto->Projection(axis); EffHisto->GetAxis(4)->SetRange(2.,2.); // reconstructed TH1D *rec = EffHisto->Projection(axis); recc = (TH1D*)rec->Clone(); if(recc) { recc->Divide(rec,all,1,1,""B""); recc->GetYaxis()->SetTitle(""efficiency""); } } else if (type == 1) // Clone Rate { EffHisto->GetAxis(4)->SetRange(2.,2.); // reconstructed TH1D *all = WeightedProjection(EffHisto, axis, 3, axis_all); EffHisto->GetAxis(4)->SetRange(2.,2.); // reconstructed TH1D *clone = WeightedProjection(EffHisto, axis, 1, &axis_clone); recc = (TH1D*) clone->Clone(); if(recc) { recc->Divide(clone,all,1,1,""B""); recc->GetYaxis()->SetTitle(""clone rate""); } } else if (type == 2) // Fake Rate { EffHisto->GetAxis(4)->SetRange(2.,2.); // reconstructed TH1D *all = WeightedProjection(EffHisto, axis, 3, axis_all); EffHisto->GetAxis(4)->SetRange(2.,2.); // reconstructed TH1D *fake = WeightedProjection(EffHisto, axis, 1, &axis_fake); recc = (TH1D*) fake->Clone(); if(recc) { recc->Divide(fake,all,1,1,""B""); recc->GetYaxis()->SetTitle(""fake rate""); } } EffHisto->GetAxis(4)->SetRange(1,0); //Reset Range if (recc) { // Coverity fix recc->SetName(name); recc->GetXaxis()->SetTitle(fEffHisto->GetAxis(axis)->GetTitle()); snprintf(title,256,""%s vs %s"",vsTitle, fEffHisto->GetAxis(axis)->GetTitle()); recc->SetTitle(title); if (axis == 2 ) recc->SetBit(TH1::kLogX); } return recc; } ",16284,True,2978.119178453053,median "/* * * Copyright (c) 2020-2021 Project CHIP Authors * * 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. */ /** * @file * mbedTLS based implementation of CHIP crypto primitives */ #include ""CHIPCryptoPAL.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(MBEDTLS_X509_CRT_PARSE_C) #include #endif // defined(MBEDTLS_X509_CRT_PARSE_C) #include #include #include #include #include #include #include #include #include #include namespace chip { namespace Crypto { #define MAX_ERROR_STR_LEN 128 #define NUM_BYTES_IN_SHA256_HASH 32 // In mbedTLS 3.0.0 direct access to structure fields was replaced with using MBEDTLS_PRIVATE macro. #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) #define CHIP_CRYPTO_PAL_PRIVATE(x) MBEDTLS_PRIVATE(x) #else #define CHIP_CRYPTO_PAL_PRIVATE(x) x #endif typedef struct { bool mInitialized; bool mDRBGSeeded; mbedtls_ctr_drbg_context mDRBGCtxt; mbedtls_entropy_context mEntropy; } EntropyContext; static EntropyContext gsEntropyContext; static void _log_mbedTLS_error(int error_code) { if (error_code != 0) { #if defined(MBEDTLS_ERROR_C) char error_str[MAX_ERROR_STR_LEN]; mbedtls_strerror(error_code, error_str, sizeof(error_str)); ChipLogError(Crypto, ""mbedTLS error: %s"", error_str); #else // Error codes defined in 16-bit negative hex numbers. Ease lookup by printing likewise ChipLogError(Crypto, ""mbedTLS error: -0x%04X"", -static_cast(error_code)); #endif } } static bool _isValidTagLength(size_t tag_length) { if (tag_length == 8 || tag_length == 12 || tag_length == 16) { return true; } return false; } static bool _isValidKeyLength(size_t length) { // 16 bytes key for AES-CCM-128, 32 for AES-CCM-256 if (length == 16 || length == 32) { return true; } return false; } CHIP_ERROR AES_CCM_encrypt(const uint8_t * plaintext, size_t plaintext_length, const uint8_t * aad, size_t aad_length, const uint8_t * key, size_t key_length, const uint8_t * nonce, size_t nonce_length, uint8_t * ciphertext, uint8_t * tag, size_t tag_length) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 1; mbedtls_ccm_context context; mbedtls_ccm_init(&context); VerifyOrExit(plaintext != nullptr || plaintext_length == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(ciphertext != nullptr || plaintext_length == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(key != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(_isValidKeyLength(key_length), error = CHIP_ERROR_UNSUPPORTED_ENCRYPTION_TYPE); VerifyOrExit(nonce != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(nonce_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(tag != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(_isValidTagLength(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT); if (aad_length > 0) { VerifyOrExit(aad != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); } // Size of key = key_length * number of bits in a byte (8) // Cast is safe because we called _isValidKeyLength above. result = mbedtls_ccm_setkey(&context, MBEDTLS_CIPHER_ID_AES, Uint8::to_const_uchar(key), static_cast(key_length * 8)); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // Encrypt result = mbedtls_ccm_encrypt_and_tag(&context, plaintext_length, Uint8::to_const_uchar(nonce), nonce_length, Uint8::to_const_uchar(aad), aad_length, Uint8::to_const_uchar(plaintext), Uint8::to_uchar(ciphertext), Uint8::to_uchar(tag), tag_length); _log_mbedTLS_error(result); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: mbedtls_ccm_free(&context); return error; } CHIP_ERROR AES_CCM_decrypt(const uint8_t * ciphertext, size_t ciphertext_len, const uint8_t * aad, size_t aad_len, const uint8_t * tag, size_t tag_length, const uint8_t * key, size_t key_length, const uint8_t * nonce, size_t nonce_length, uint8_t * plaintext) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 1; mbedtls_ccm_context context; mbedtls_ccm_init(&context); VerifyOrExit(plaintext != nullptr || ciphertext_len == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(ciphertext != nullptr || ciphertext_len == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(tag != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(_isValidTagLength(tag_length), error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(key != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(_isValidKeyLength(key_length), error = CHIP_ERROR_UNSUPPORTED_ENCRYPTION_TYPE); VerifyOrExit(nonce != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(nonce_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); if (aad_len > 0) { VerifyOrExit(aad != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); } // Size of key = key_length * number of bits in a byte (8) // Cast is safe because we called _isValidKeyLength above. result = mbedtls_ccm_setkey(&context, MBEDTLS_CIPHER_ID_AES, Uint8::to_const_uchar(key), static_cast(key_length * 8)); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // Decrypt result = mbedtls_ccm_auth_decrypt(&context, ciphertext_len, Uint8::to_const_uchar(nonce), nonce_length, Uint8::to_const_uchar(aad), aad_len, Uint8::to_const_uchar(ciphertext), Uint8::to_uchar(plaintext), Uint8::to_const_uchar(tag), tag_length); _log_mbedTLS_error(result); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: mbedtls_ccm_free(&context); return error; } CHIP_ERROR Hash_SHA256(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) { // zero data length hash is supported. VerifyOrReturnError(data != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha256(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer), 0); #else const int result = mbedtls_sha256_ret(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer), 0); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA1(const uint8_t * data, const size_t data_length, uint8_t * out_buffer) { // zero data length hash is supported. VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha1(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer)); #else const int result = mbedtls_sha1_ret(Uint8::to_const_uchar(data), data_length, Uint8::to_uchar(out_buffer)); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } static_assert(kMAX_Hash_SHA256_Context_Size >= sizeof(mbedtls_sha256_context), ""kMAX_Hash_SHA256_Context_Size is too small for the size of underlying mbedtls_sha256_context""); static inline mbedtls_sha256_context * to_inner_hash_sha256_context(HashSHA256OpaqueContext * context) { return SafePointerCast(context); } Hash_SHA256_stream::Hash_SHA256_stream(void) { mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); mbedtls_sha256_init(context); } Hash_SHA256_stream::~Hash_SHA256_stream(void) { mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); mbedtls_sha256_free(context); Clear(); } CHIP_ERROR Hash_SHA256_stream::Begin(void) { mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha256_starts(context, 0); #else const int result = mbedtls_sha256_starts_ret(context, 0); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::AddData(const ByteSpan data) { mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha256_update(context, Uint8::to_const_uchar(data.data()), data.size()); #else const int result = mbedtls_sha256_update_ret(context, Uint8::to_const_uchar(data.data()), data.size()); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR Hash_SHA256_stream::GetDigest(MutableByteSpan & out_buffer) { mbedtls_sha256_context * context = to_inner_hash_sha256_context(&mContext); // Back-up context as we are about to finalize the hash to extract digest. mbedtls_sha256_context previous_ctx; mbedtls_sha256_clone(&previous_ctx, context); // Pad + compute digest, then finalize context. It is restored next line to continue. CHIP_ERROR result = Finish(out_buffer); // Restore context prior to finalization. mbedtls_sha256_clone(context, &previous_ctx); return result; } CHIP_ERROR Hash_SHA256_stream::Finish(MutableByteSpan & out_buffer) { VerifyOrReturnError(out_buffer.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); mbedtls_sha256_context * const context = to_inner_hash_sha256_context(&mContext); #if (MBEDTLS_VERSION_NUMBER >= 0x03000000) const int result = mbedtls_sha256_finish(context, Uint8::to_uchar(out_buffer.data())); #else const int result = mbedtls_sha256_finish_ret(context, Uint8::to_uchar(out_buffer.data())); #endif VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); out_buffer = out_buffer.SubSpan(0, kSHA256_Hash_Length); return CHIP_NO_ERROR; } void Hash_SHA256_stream::Clear(void) { mbedtls_platform_zeroize(this, sizeof(*this)); } CHIP_ERROR HKDF_sha::HKDF_SHA256(const uint8_t * secret, const size_t secret_length, const uint8_t * salt, const size_t salt_length, const uint8_t * info, const size_t info_length, uint8_t * out_buffer, size_t out_length) { VerifyOrReturnError(secret != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(secret_length > 0, CHIP_ERROR_INVALID_ARGUMENT); // Salt is optional if (salt_length > 0) { VerifyOrReturnError(salt != nullptr, CHIP_ERROR_INVALID_ARGUMENT); } VerifyOrReturnError(info_length > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(info != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); const mbedtls_md_info_t * const md = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); VerifyOrReturnError(md != nullptr, CHIP_ERROR_INTERNAL); const int result = mbedtls_hkdf(md, Uint8::to_const_uchar(salt), salt_length, Uint8::to_const_uchar(secret), secret_length, Uint8::to_const_uchar(info), info_length, Uint8::to_uchar(out_buffer), out_length); _log_mbedTLS_error(result); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR HMAC_sha::HMAC_SHA256(const uint8_t * key, size_t key_length, const uint8_t * message, size_t message_length, uint8_t * out_buffer, size_t out_length) { VerifyOrReturnError(key != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(key_length > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(message != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(message_length > 0, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_length >= kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); const mbedtls_md_info_t * const md = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); VerifyOrReturnError(md != nullptr, CHIP_ERROR_INTERNAL); const int result = mbedtls_md_hmac(md, Uint8::to_const_uchar(key), key_length, Uint8::to_const_uchar(message), message_length, out_buffer); _log_mbedTLS_error(result); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR PBKDF2_sha256::pbkdf2_sha256(const uint8_t * password, size_t plen, const uint8_t * salt, size_t slen, unsigned int iteration_count, uint32_t key_length, uint8_t * output) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; const mbedtls_md_info_t * md_info; mbedtls_md_context_t md_ctxt; constexpr int use_hmac = 1; bool free_md_ctxt = false; VerifyOrExit(password != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(plen > 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(salt != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(slen >= kSpake2p_Min_PBKDF_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(slen <= kSpake2p_Max_PBKDF_Salt_Length, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(key_length > 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(output != nullptr, error = CHIP_ERROR_INVALID_ARGUMENT); md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); VerifyOrExit(md_info != nullptr, error = CHIP_ERROR_INTERNAL); mbedtls_md_init(&md_ctxt); free_md_ctxt = true; result = mbedtls_md_setup(&md_ctxt, md_info, use_hmac); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_pkcs5_pbkdf2_hmac(&md_ctxt, Uint8::to_const_uchar(password), plen, Uint8::to_const_uchar(salt), slen, iteration_count, key_length, Uint8::to_uchar(output)); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); if (free_md_ctxt) { mbedtls_md_free(&md_ctxt); } return error; } static EntropyContext * get_entropy_context() { if (!gsEntropyContext.mInitialized) { mbedtls_entropy_init(&gsEntropyContext.mEntropy); mbedtls_ctr_drbg_init(&gsEntropyContext.mDRBGCtxt); gsEntropyContext.mInitialized = true; } return &gsEntropyContext; } static mbedtls_ctr_drbg_context * get_drbg_context() { EntropyContext * const context = get_entropy_context(); mbedtls_ctr_drbg_context * const drbgCtxt = &context->mDRBGCtxt; if (!context->mDRBGSeeded) { const int status = mbedtls_ctr_drbg_seed(drbgCtxt, mbedtls_entropy_func, &context->mEntropy, nullptr, 0); if (status != 0) { _log_mbedTLS_error(status); return nullptr; } context->mDRBGSeeded = true; } return drbgCtxt; } CHIP_ERROR add_entropy_source(entropy_source fn_source, void * p_source, size_t threshold) { VerifyOrReturnError(fn_source != nullptr, CHIP_ERROR_INVALID_ARGUMENT); EntropyContext * const entropy_ctxt = get_entropy_context(); VerifyOrReturnError(entropy_ctxt != nullptr, CHIP_ERROR_INTERNAL); const int result = mbedtls_entropy_add_source(&entropy_ctxt->mEntropy, fn_source, p_source, threshold, MBEDTLS_ENTROPY_SOURCE_STRONG); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } CHIP_ERROR DRBG_get_bytes(uint8_t * out_buffer, const size_t out_length) { VerifyOrReturnError(out_buffer != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(out_length > 0, CHIP_ERROR_INVALID_ARGUMENT); mbedtls_ctr_drbg_context * const drbg_ctxt = get_drbg_context(); VerifyOrReturnError(drbg_ctxt != nullptr, CHIP_ERROR_INTERNAL); const int result = mbedtls_ctr_drbg_random(drbg_ctxt, Uint8::to_uchar(out_buffer), out_length); VerifyOrReturnError(result == 0, CHIP_ERROR_INTERNAL); return CHIP_NO_ERROR; } static int CryptoRNG(void * ctxt, uint8_t * out_buffer, size_t out_length) { return (chip::Crypto::DRBG_get_bytes(out_buffer, out_length) == CHIP_NO_ERROR) ? 0 : 1; } mbedtls_ecp_group_id MapECPGroupId(SupportedECPKeyTypes keyType) { switch (keyType) { case SupportedECPKeyTypes::ECP256R1: return MBEDTLS_ECP_DP_SECP256R1; default: return MBEDTLS_ECP_DP_NONE; } } static inline mbedtls_ecp_keypair * to_keypair(P256KeypairContext * context) { return SafePointerCast(context); } static inline const mbedtls_ecp_keypair * to_const_keypair(const P256KeypairContext * context) { return SafePointerCast(context); } CHIP_ERROR P256Keypair::ECDSA_sign_msg(const uint8_t * msg, const size_t msg_length, P256ECDSASignature & out_signature) { #if defined(MBEDTLS_ECDSA_C) VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError((msg != nullptr) && (msg_length > 0), CHIP_ERROR_INVALID_ARGUMENT); uint8_t digest[kSHA256_Hash_Length]; memset(&digest[0], 0, sizeof(digest)); ReturnErrorOnFailure(Hash_SHA256(msg, msg_length, &digest[0])); return ECDSA_sign_hash(&digest[0], sizeof(digest), out_signature); #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } CHIP_ERROR P256Keypair::ECDSA_sign_hash(const uint8_t * hash, const size_t hash_length, P256ECDSASignature & out_signature) { #if defined(MBEDTLS_ECDSA_C) VerifyOrReturnError(mInitialized, CHIP_ERROR_INCORRECT_STATE); VerifyOrReturnError(hash != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(hash_length == kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; mbedtls_mpi r, s; mbedtls_mpi_init(&r); mbedtls_mpi_init(&s); const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); mbedtls_ecdsa_context ecdsa_ctxt; mbedtls_ecdsa_init(&ecdsa_ctxt); result = mbedtls_ecdsa_from_keypair(&ecdsa_ctxt, keypair); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecdsa_sign(&ecdsa_ctxt.CHIP_CRYPTO_PAL_PRIVATE(grp), &r, &s, &ecdsa_ctxt.CHIP_CRYPTO_PAL_PRIVATE(d), Uint8::to_const_uchar(hash), hash_length, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit((mbedtls_mpi_size(&r) <= kP256_FE_Length) || (mbedtls_mpi_size(&s) <= kP256_FE_Length), error = CHIP_ERROR_INTERNAL); // Concatenate r and s to output. Sizes were checked above. result = mbedtls_mpi_write_binary(&r, out_signature.Bytes() + 0u, kP256_FE_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_write_binary(&s, out_signature.Bytes() + kP256_FE_Length, kP256_FE_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(out_signature.SetLength(kP256_ECDSA_Signature_Length_Raw) == CHIP_NO_ERROR, error = CHIP_ERROR_INTERNAL); exit: keypair = nullptr; mbedtls_ecdsa_free(&ecdsa_ctxt); mbedtls_mpi_free(&s); mbedtls_mpi_free(&r); _log_mbedTLS_error(result); return error; #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } CHIP_ERROR P256PublicKey::ECDSA_validate_msg_signature(const uint8_t * msg, const size_t msg_length, const P256ECDSASignature & signature) const { #if defined(MBEDTLS_ECDSA_C) VerifyOrReturnError((msg != nullptr) && (msg_length > 0), CHIP_ERROR_INVALID_ARGUMENT); uint8_t digest[kSHA256_Hash_Length]; memset(&digest[0], 0, sizeof(digest)); ReturnErrorOnFailure(Hash_SHA256(msg, msg_length, &digest[0])); return ECDSA_validate_hash_signature(&digest[0], sizeof(digest), signature); #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } CHIP_ERROR P256PublicKey::ECDSA_validate_hash_signature(const uint8_t * hash, const size_t hash_length, const P256ECDSASignature & signature) const { #if defined(MBEDTLS_ECDSA_C) VerifyOrReturnError(hash != nullptr, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(hash_length == kSHA256_Hash_Length, CHIP_ERROR_INVALID_ARGUMENT); VerifyOrReturnError(signature.Length() == kP256_ECDSA_Signature_Length_Raw, CHIP_ERROR_INVALID_ARGUMENT); CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; mbedtls_mpi r, s; mbedtls_mpi_init(&r); mbedtls_mpi_init(&s); mbedtls_ecp_keypair keypair; mbedtls_ecp_keypair_init(&keypair); mbedtls_ecdsa_context ecdsa_ctxt; mbedtls_ecdsa_init(&ecdsa_ctxt); result = mbedtls_ecp_group_load(&keypair.CHIP_CRYPTO_PAL_PRIVATE(grp), MapECPGroupId(Type())); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); result = mbedtls_ecp_point_read_binary(&keypair.CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair.CHIP_CRYPTO_PAL_PRIVATE(Q), Uint8::to_const_uchar(*this), Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); result = mbedtls_ecdsa_from_keypair(&ecdsa_ctxt, &keypair); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // Read the big nums from the signature result = mbedtls_mpi_read_binary(&r, Uint8::to_const_uchar(signature.ConstBytes()) + 0u, kP256_FE_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_read_binary(&s, Uint8::to_const_uchar(signature.ConstBytes()) + kP256_FE_Length, kP256_FE_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecdsa_verify(&ecdsa_ctxt.CHIP_CRYPTO_PAL_PRIVATE(grp), Uint8::to_const_uchar(hash), hash_length, &ecdsa_ctxt.CHIP_CRYPTO_PAL_PRIVATE(Q), &r, &s); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_SIGNATURE); exit: mbedtls_ecdsa_free(&ecdsa_ctxt); mbedtls_ecp_keypair_free(&keypair); mbedtls_mpi_free(&s); mbedtls_mpi_free(&r); _log_mbedTLS_error(result); return error; #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } CHIP_ERROR P256Keypair::ECDH_derive_secret(const P256PublicKey & remote_public_key, P256ECDHDerivedSecret & out_secret) const { #if defined(MBEDTLS_ECDH_C) CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; size_t secret_length = (out_secret.Length() == 0) ? out_secret.Capacity() : out_secret.Length(); mbedtls_ecp_group ecp_grp; mbedtls_ecp_group_init(&ecp_grp); mbedtls_mpi mpi_secret; mbedtls_mpi_init(&mpi_secret); mbedtls_ecp_point ecp_pubkey; mbedtls_ecp_point_init(&ecp_pubkey); const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); VerifyOrExit(mInitialized, error = CHIP_ERROR_INCORRECT_STATE); result = mbedtls_ecp_group_load(&ecp_grp, MapECPGroupId(remote_public_key.Type())); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecp_point_read_binary(&ecp_grp, &ecp_pubkey, Uint8::to_const_uchar(remote_public_key), remote_public_key.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); result = mbedtls_ecdh_compute_shared(&ecp_grp, &mpi_secret, &ecp_pubkey, &keypair->CHIP_CRYPTO_PAL_PRIVATE(d), CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_write_binary(&mpi_secret, Uint8::to_uchar(out_secret), secret_length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); SuccessOrExit(out_secret.SetLength(secret_length)); exit: keypair = nullptr; mbedtls_ecp_group_free(&ecp_grp); mbedtls_mpi_free(&mpi_secret); mbedtls_ecp_point_free(&ecp_pubkey); _log_mbedTLS_error(result); return error; #else return CHIP_ERROR_NOT_IMPLEMENTED; #endif } void ClearSecretData(uint8_t * buf, size_t len) { mbedtls_platform_zeroize(buf, len); } CHIP_ERROR P256Keypair::Initialize() { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; size_t pubkey_size = 0; Clear(); mbedtls_ecp_group_id group = MapECPGroupId(mPublicKey.Type()); mbedtls_ecp_keypair * keypair = to_keypair(&mKeypair); mbedtls_ecp_keypair_init(keypair); result = mbedtls_ecp_gen_key(group, keypair, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecp_point_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED, &pubkey_size, Uint8::to_uchar(mPublicKey), mPublicKey.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(pubkey_size == mPublicKey.Length(), error = CHIP_ERROR_INVALID_ARGUMENT); keypair = nullptr; mInitialized = true; exit: if (keypair != nullptr) { mbedtls_ecp_keypair_free(keypair); keypair = nullptr; } _log_mbedTLS_error(result); return error; } CHIP_ERROR P256Keypair::Serialize(P256SerializedKeypair & output) const { const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); size_t len = output.Length() == 0 ? output.Capacity() : output.Length(); Encoding::BufferWriter bbuf(output, len); uint8_t privkey[kP256_PrivateKey_Length]; CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; bbuf.Put(mPublicKey, mPublicKey.Length()); VerifyOrExit(bbuf.Available() == sizeof(privkey), error = CHIP_ERROR_INTERNAL); VerifyOrExit(mbedtls_mpi_size(&keypair->CHIP_CRYPTO_PAL_PRIVATE(d)) <= bbuf.Available(), error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(d), Uint8::to_uchar(privkey), sizeof(privkey)); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); bbuf.Put(privkey, sizeof(privkey)); VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_BUFFER_TOO_SMALL); output.SetLength(bbuf.Needed()); exit: ClearSecretData(privkey, sizeof(privkey)); _log_mbedTLS_error(result); return error; } CHIP_ERROR P256Keypair::Deserialize(P256SerializedKeypair & input) { Encoding::BufferWriter bbuf(mPublicKey, mPublicKey.Length()); int result = 0; CHIP_ERROR error = CHIP_NO_ERROR; Clear(); mbedtls_ecp_keypair * keypair = to_keypair(&mKeypair); mbedtls_ecp_keypair_init(keypair); result = mbedtls_ecp_group_load(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), MapECPGroupId(mPublicKey.Type())); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(input.Length() == mPublicKey.Length() + kP256_PrivateKey_Length, error = CHIP_ERROR_INVALID_ARGUMENT); bbuf.Put((const uint8_t *) input, mPublicKey.Length()); VerifyOrExit(bbuf.Fit(), error = CHIP_ERROR_NO_MEMORY); result = mbedtls_ecp_point_read_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), Uint8::to_const_uchar(mPublicKey), mPublicKey.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); { const uint8_t * privkey = Uint8::to_const_uchar(input) + mPublicKey.Length(); result = mbedtls_mpi_read_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(d), privkey, kP256_PrivateKey_Length); VerifyOrExit(result == 0, error = CHIP_ERROR_INVALID_ARGUMENT); } mInitialized = true; exit: _log_mbedTLS_error(result); return error; } void P256Keypair::Clear() { if (mInitialized) { mbedtls_ecp_keypair * keypair = to_keypair(&mKeypair); mbedtls_ecp_keypair_free(keypair); mInitialized = false; } } P256Keypair::~P256Keypair() { Clear(); } CHIP_ERROR P256Keypair::NewCertificateSigningRequest(uint8_t * out_csr, size_t & csr_length) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; size_t out_length; const mbedtls_ecp_keypair * keypair = to_const_keypair(&mKeypair); mbedtls_x509write_csr csr; mbedtls_x509write_csr_init(&csr); mbedtls_pk_context pk; mbedtls_pk_init(&pk); const mbedtls_pk_info_t * pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY); VerifyOrExit(pk_info != nullptr, error = CHIP_ERROR_INTERNAL); VerifyOrExit(mInitialized, error = CHIP_ERROR_INCORRECT_STATE); result = mbedtls_pk_setup(&pk, pk_info); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); memcpy(mbedtls_pk_ec(pk), keypair, sizeof(mbedtls_ecp_keypair)); mbedtls_x509write_csr_set_key(&csr, &pk); mbedtls_x509write_csr_set_md_alg(&csr, MBEDTLS_MD_SHA256); // TODO: mbedTLS CSR parser fails if the subject name is not set (or if empty). // CHIP Spec doesn't specify the subject name that can be used. // Figure out the correct value and update this code. result = mbedtls_x509write_csr_set_subject_name(&csr, ""O=CSR""); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_x509write_csr_der(&csr, out_csr, csr_length, CryptoRNG, nullptr); VerifyOrExit(result > 0, error = CHIP_ERROR_INTERNAL); out_length = (size_t) result; result = 0; VerifyOrExit(out_length <= csr_length, error = CHIP_ERROR_INTERNAL); if (csr_length != out_length) { // mbedTLS API writes the CSR at the end of the provided buffer. // Let's move it to the start of the buffer. size_t offset = csr_length - out_length; memmove(out_csr, &out_csr[offset], out_length); } csr_length = out_length; exit: mbedtls_x509write_csr_free(&csr); // TODO: Figure-out why the next 2 lines are OK. Valgrind complains or crash occurs if either is deleted. // Oddly, the following `mbedtls_ecp_keypair_init` is needed to avoid a double-free // with the following pk_free, which is needed. mbedtls_ecp_keypair_init(mbedtls_pk_ec(pk)); mbedtls_pk_free(&pk); _log_mbedTLS_error(result); return error; } CHIP_ERROR VerifyCertificateSigningRequest(const uint8_t * csr_buf, size_t csr_length, P256PublicKey & pubkey) { #if defined(MBEDTLS_X509_CSR_PARSE_C) // TODO: For some embedded targets, mbedTLS library doesn't have mbedtls_x509_csr_parse_der, and mbedtls_x509_csr_parse_free. // Taking a step back, embedded targets likely will not process CSR requests. Adding this action item to reevaluate // this if there's a need for this processing for embedded targets. CHIP_ERROR error = CHIP_NO_ERROR; size_t pubkey_size = 0; mbedtls_ecp_keypair * keypair = nullptr; P256ECDSASignature signature; MutableByteSpan out_raw_sig_span(signature.Bytes(), signature.Capacity()); mbedtls_x509_csr csr; mbedtls_x509_csr_init(&csr); int result = mbedtls_x509_csr_parse_der(&csr, csr_buf, csr_length); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // Verify the signature algorithm and public key type VerifyOrExit(csr.CHIP_CRYPTO_PAL_PRIVATE(sig_md) == MBEDTLS_MD_SHA256, error = CHIP_ERROR_UNSUPPORTED_SIGNATURE_TYPE); VerifyOrExit(csr.CHIP_CRYPTO_PAL_PRIVATE(sig_pk) == MBEDTLS_PK_ECDSA, error = CHIP_ERROR_WRONG_KEY_TYPE); keypair = mbedtls_pk_ec(csr.CHIP_CRYPTO_PAL_PRIVATE(pk)); // Copy the public key from the CSR result = mbedtls_ecp_point_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED, &pubkey_size, Uint8::to_uchar(pubkey), pubkey.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(pubkey_size == pubkey.Length(), error = CHIP_ERROR_INTERNAL); // Convert DER signature to raw signature error = EcdsaAsn1SignatureToRaw(kP256_FE_Length, ByteSpan{ csr.CHIP_CRYPTO_PAL_PRIVATE(sig).CHIP_CRYPTO_PAL_PRIVATE(p), csr.CHIP_CRYPTO_PAL_PRIVATE(sig).CHIP_CRYPTO_PAL_PRIVATE(len) }, out_raw_sig_span); VerifyOrExit(error == CHIP_NO_ERROR, error = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(out_raw_sig_span.size() == (kP256_FE_Length * 2), error = CHIP_ERROR_INTERNAL); signature.SetLength(out_raw_sig_span.size()); // Verify the signature using the public key error = pubkey.ECDSA_validate_msg_signature(csr.CHIP_CRYPTO_PAL_PRIVATE(cri).CHIP_CRYPTO_PAL_PRIVATE(p), csr.CHIP_CRYPTO_PAL_PRIVATE(cri).CHIP_CRYPTO_PAL_PRIVATE(len), signature); SuccessOrExit(error); exit: mbedtls_x509_csr_free(&csr); _log_mbedTLS_error(result); return error; #else ChipLogError(Crypto, ""MBEDTLS_X509_CSR_PARSE_C is not enabled. CSR cannot be parsed""); return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; #endif } typedef struct Spake2p_Context { mbedtls_ecp_group curve; const mbedtls_md_info_t * md_info; mbedtls_ecp_point M; mbedtls_ecp_point N; mbedtls_ecp_point X; mbedtls_ecp_point Y; mbedtls_ecp_point L; mbedtls_ecp_point Z; mbedtls_ecp_point V; mbedtls_mpi w0; mbedtls_mpi w1; mbedtls_mpi xy; mbedtls_mpi tempbn; } Spake2p_Context; static inline Spake2p_Context * to_inner_spake2p_context(Spake2pOpaqueContext * context) { return SafePointerCast(context); } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::InitInternal(void) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); memset(context, 0, sizeof(Spake2p_Context)); mbedtls_ecp_group_init(&context->curve); result = mbedtls_ecp_group_load(&context->curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); context->md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); VerifyOrExit(context->md_info != nullptr, error = CHIP_ERROR_INTERNAL); mbedtls_ecp_point_init(&context->M); mbedtls_ecp_point_init(&context->N); mbedtls_ecp_point_init(&context->X); mbedtls_ecp_point_init(&context->Y); mbedtls_ecp_point_init(&context->L); mbedtls_ecp_point_init(&context->V); mbedtls_ecp_point_init(&context->Z); M = &context->M; N = &context->N; X = &context->X; Y = &context->Y; L = &context->L; V = &context->V; Z = &context->Z; mbedtls_mpi_init(&context->w0); mbedtls_mpi_init(&context->w1); mbedtls_mpi_init(&context->xy); mbedtls_mpi_init(&context->tempbn); w0 = &context->w0; w1 = &context->w1; xy = &context->xy; tempbn = &context->tempbn; G = &context->curve.G; order = &context->curve.N; return error; exit: _log_mbedTLS_error(result); Clear(); return error; } void Spake2p_P256_SHA256_HKDF_HMAC::Clear() { VerifyOrReturn(state != CHIP_SPAKE2P_STATE::PREINIT); Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); mbedtls_ecp_point_free(&context->M); mbedtls_ecp_point_free(&context->N); mbedtls_ecp_point_free(&context->X); mbedtls_ecp_point_free(&context->Y); mbedtls_ecp_point_free(&context->L); mbedtls_ecp_point_free(&context->Z); mbedtls_ecp_point_free(&context->V); mbedtls_mpi_free(&context->w0); mbedtls_mpi_free(&context->w1); mbedtls_mpi_free(&context->xy); mbedtls_mpi_free(&context->tempbn); mbedtls_ecp_group_free(&context->curve); state = CHIP_SPAKE2P_STATE::PREINIT; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::Mac(const uint8_t * key, size_t key_len, const uint8_t * in, size_t in_len, MutableByteSpan & out_span) { HMAC_sha hmac; VerifyOrReturnError(out_span.size() >= kSHA256_Hash_Length, CHIP_ERROR_BUFFER_TOO_SMALL); ReturnErrorOnFailure(hmac.HMAC_SHA256(key, key_len, in, in_len, out_span.data(), kSHA256_Hash_Length)); out_span = out_span.SubSpan(0, kSHA256_Hash_Length); return CHIP_NO_ERROR; } /** * This function implements constant time memcmp. It's good practice * to use constant time functions for cryptographic functions. */ static inline int constant_time_memcmp(const void * a, const void * b, size_t n) { const uint8_t * A = (const uint8_t *) a; const uint8_t * B = (const uint8_t *) b; uint8_t diff = 0; for (size_t i = 0; i < n; i++) { diff |= (A[i] ^ B[i]); } return diff; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::MacVerify(const uint8_t * key, size_t key_len, const uint8_t * mac, size_t mac_len, const uint8_t * in, size_t in_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; uint8_t computed_mac[kSHA256_Hash_Length]; MutableByteSpan computed_mac_span{ computed_mac }; VerifyOrExit(mac_len == kSHA256_Hash_Length, error = CHIP_ERROR_INVALID_ARGUMENT); SuccessOrExit(error = Mac(key, key_len, in, in_len, computed_mac_span)); VerifyOrExit(computed_mac_span.size() == mac_len, error = CHIP_ERROR_INTERNAL); VerifyOrExit(constant_time_memcmp(mac, computed_mac, kSHA256_Hash_Length) == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FELoad(const uint8_t * in, size_t in_len, void * fe) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; result = mbedtls_mpi_read_binary((mbedtls_mpi *) fe, Uint8::to_const_uchar(in), in_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi((mbedtls_mpi *) fe, (mbedtls_mpi *) fe, (const mbedtls_mpi *) order); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEWrite(const void * fe, uint8_t * out, size_t out_len) { if (mbedtls_mpi_write_binary((const mbedtls_mpi *) fe, Uint8::to_uchar(out), out_len) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEGenerate(void * fe) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); result = mbedtls_ecp_gen_privkey(&context->curve, (mbedtls_mpi *) fe, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::FEMul(void * fer, const void * fe1, const void * fe2) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; result = mbedtls_mpi_mul_mpi((mbedtls_mpi *) fer, (const mbedtls_mpi *) fe1, (const mbedtls_mpi *) fe2); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi((mbedtls_mpi *) fer, (mbedtls_mpi *) fer, (const mbedtls_mpi *) order); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointLoad(const uint8_t * in, size_t in_len, void * R) { Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_point_read_binary(&context->curve, (mbedtls_ecp_point *) R, Uint8::to_const_uchar(in), in_len) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointWrite(const void * R, uint8_t * out, size_t out_len) { memset(out, 0, out_len); size_t mbedtls_out_len = out_len; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_point_write_binary(&context->curve, (const mbedtls_ecp_point *) R, MBEDTLS_ECP_PF_UNCOMPRESSED, &mbedtls_out_len, Uint8::to_uchar(out), out_len) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointMul(void * R, const void * P1, const void * fe1) { Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_mul(&context->curve, (mbedtls_ecp_point *) R, (const mbedtls_mpi *) fe1, (const mbedtls_ecp_point *) P1, CryptoRNG, nullptr) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointAddMul(void * R, const void * P1, const void * fe1, const void * P2, const void * fe2) { Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_muladd(&context->curve, (mbedtls_ecp_point *) R, (const mbedtls_mpi *) fe1, (const mbedtls_ecp_point *) P1, (const mbedtls_mpi *) fe2, (const mbedtls_ecp_point *) P2) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointInvert(void * R) { mbedtls_ecp_point * Rp = (mbedtls_ecp_point *) R; Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_mpi_sub_mpi(&Rp->CHIP_CRYPTO_PAL_PRIVATE(Y), &context->curve.P, &Rp->CHIP_CRYPTO_PAL_PRIVATE(Y)) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointCofactorMul(void * R) { return CHIP_NO_ERROR; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::ComputeL(uint8_t * Lout, size_t * L_len, const uint8_t * w1in, size_t w1in_len) { CHIP_ERROR error = CHIP_NO_ERROR; int result = 0; mbedtls_ecp_group curve; mbedtls_mpi w1_bn; mbedtls_ecp_point Ltemp; mbedtls_ecp_group_init(&curve); mbedtls_mpi_init(&w1_bn); mbedtls_ecp_point_init(&Ltemp); result = mbedtls_ecp_group_load(&curve, MBEDTLS_ECP_DP_SECP256R1); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_read_binary(&w1_bn, Uint8::to_const_uchar(w1in), w1in_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_mpi_mod_mpi(&w1_bn, &w1_bn, &curve.N); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_ecp_mul(&curve, &Ltemp, &w1_bn, &curve.G, CryptoRNG, nullptr); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); memset(Lout, 0, *L_len); result = mbedtls_ecp_point_write_binary(&curve, &Ltemp, MBEDTLS_ECP_PF_UNCOMPRESSED, L_len, Uint8::to_uchar(Lout), *L_len); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); mbedtls_ecp_point_free(&Ltemp); mbedtls_mpi_free(&w1_bn); mbedtls_ecp_group_free(&curve); return error; } CHIP_ERROR Spake2p_P256_SHA256_HKDF_HMAC::PointIsValid(void * R) { Spake2p_Context * context = to_inner_spake2p_context(&mSpake2pContext); if (mbedtls_ecp_check_pubkey(&context->curve, (mbedtls_ecp_point *) R) != 0) { return CHIP_ERROR_INTERNAL; } return CHIP_NO_ERROR; } CHIP_ERROR LoadCertsFromPKCS7(const char * pkcs7, X509DerCertificate * x509list, uint32_t * max_certs) { return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR LoadCertFromPKCS7(const char * pkcs7, X509DerCertificate * x509list, uint32_t n_cert) { return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR GetNumberOfCertsFromPKCS7(const char * pkcs7, uint32_t * n_certs) { return CHIP_ERROR_NOT_IMPLEMENTED; } CHIP_ERROR ValidateCertificateChain(const uint8_t * rootCertificate, size_t rootCertificateLen, const uint8_t * caCertificate, size_t caCertificateLen, const uint8_t * leafCertificate, size_t leafCertificateLen, CertificateChainValidationResult & result) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt certChain; mbedtls_x509_crt rootCert; int mbedResult; uint32_t flags; result = CertificateChainValidationResult::kInternalFrameworkError; VerifyOrReturnError(rootCertificate != nullptr && rootCertificateLen != 0, (result = CertificateChainValidationResult::kRootArgumentInvalid, CHIP_ERROR_INVALID_ARGUMENT)); VerifyOrReturnError(caCertificate != nullptr && caCertificateLen != 0, (result = CertificateChainValidationResult::kICAArgumentInvalid, CHIP_ERROR_INVALID_ARGUMENT)); VerifyOrReturnError(leafCertificate != nullptr && leafCertificateLen != 0, (result = CertificateChainValidationResult::kLeafArgumentInvalid, CHIP_ERROR_INVALID_ARGUMENT)); mbedtls_x509_crt_init(&certChain); mbedtls_x509_crt_init(&rootCert); /* Start of chain */ mbedResult = mbedtls_x509_crt_parse(&certChain, Uint8::to_const_uchar(leafCertificate), leafCertificateLen); VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kLeafFormatInvalid, error = CHIP_ERROR_INTERNAL)); /* Add the intermediate to the chain */ mbedResult = mbedtls_x509_crt_parse(&certChain, Uint8::to_const_uchar(caCertificate), caCertificateLen); VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kICAFormatInvalid, error = CHIP_ERROR_INTERNAL)); /* Parse the root cert */ mbedResult = mbedtls_x509_crt_parse(&rootCert, Uint8::to_const_uchar(rootCertificate), rootCertificateLen); VerifyOrExit(mbedResult == 0, (result = CertificateChainValidationResult::kRootFormatInvalid, error = CHIP_ERROR_INTERNAL)); /* Verify the chain against the root */ mbedResult = mbedtls_x509_crt_verify(&certChain, &rootCert, NULL, NULL, &flags, NULL, NULL); switch (mbedResult) { case 0: VerifyOrExit(flags == 0, (result = CertificateChainValidationResult::kInternalFrameworkError, error = CHIP_ERROR_INTERNAL)); result = CertificateChainValidationResult::kSuccess; break; case MBEDTLS_ERR_X509_CERT_VERIFY_FAILED: result = CertificateChainValidationResult::kChainInvalid; error = CHIP_ERROR_CERT_NOT_TRUSTED; break; default: SuccessOrExit((result = CertificateChainValidationResult::kInternalFrameworkError, error = CHIP_ERROR_INTERNAL)); } exit: _log_mbedTLS_error(mbedResult); mbedtls_x509_crt_free(&certChain); mbedtls_x509_crt_free(&rootCert); #else (void) rootCertificate; (void) rootCertificateLen; (void) caCertificate; (void) caCertificateLen; (void) leafCertificate; (void) leafCertificateLen; (void) result; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } inline bool IsTimeGreaterThanEqual(const mbedtls_x509_time * const timeA, const mbedtls_x509_time * const timeB) { return timeA->CHIP_CRYPTO_PAL_PRIVATE(year) > timeB->CHIP_CRYPTO_PAL_PRIVATE(year) || (timeA->CHIP_CRYPTO_PAL_PRIVATE(year) == timeB->CHIP_CRYPTO_PAL_PRIVATE(year) && timeA->CHIP_CRYPTO_PAL_PRIVATE(mon) > timeB->CHIP_CRYPTO_PAL_PRIVATE(mon)) || (timeA->CHIP_CRYPTO_PAL_PRIVATE(year) == timeB->CHIP_CRYPTO_PAL_PRIVATE(year) && timeA->CHIP_CRYPTO_PAL_PRIVATE(mon) == timeB->CHIP_CRYPTO_PAL_PRIVATE(mon) && timeA->CHIP_CRYPTO_PAL_PRIVATE(day) > timeB->CHIP_CRYPTO_PAL_PRIVATE(day)) || (timeA->CHIP_CRYPTO_PAL_PRIVATE(year) == timeB->CHIP_CRYPTO_PAL_PRIVATE(year) && timeA->CHIP_CRYPTO_PAL_PRIVATE(mon) == timeB->CHIP_CRYPTO_PAL_PRIVATE(mon) && timeA->CHIP_CRYPTO_PAL_PRIVATE(day) == timeB->CHIP_CRYPTO_PAL_PRIVATE(day) && timeA->CHIP_CRYPTO_PAL_PRIVATE(hour) > timeB->CHIP_CRYPTO_PAL_PRIVATE(hour)) || (timeA->CHIP_CRYPTO_PAL_PRIVATE(year) == timeB->CHIP_CRYPTO_PAL_PRIVATE(year) && timeA->CHIP_CRYPTO_PAL_PRIVATE(mon) == timeB->CHIP_CRYPTO_PAL_PRIVATE(mon) && timeA->CHIP_CRYPTO_PAL_PRIVATE(day) == timeB->CHIP_CRYPTO_PAL_PRIVATE(day) && timeA->CHIP_CRYPTO_PAL_PRIVATE(hour) == timeB->CHIP_CRYPTO_PAL_PRIVATE(hour) && timeA->CHIP_CRYPTO_PAL_PRIVATE(min) > timeB->CHIP_CRYPTO_PAL_PRIVATE(min)) || (timeA->CHIP_CRYPTO_PAL_PRIVATE(year) == timeB->CHIP_CRYPTO_PAL_PRIVATE(year) && timeA->CHIP_CRYPTO_PAL_PRIVATE(mon) == timeB->CHIP_CRYPTO_PAL_PRIVATE(mon) && timeA->CHIP_CRYPTO_PAL_PRIVATE(day) == timeB->CHIP_CRYPTO_PAL_PRIVATE(day) && timeA->CHIP_CRYPTO_PAL_PRIVATE(hour) == timeB->CHIP_CRYPTO_PAL_PRIVATE(hour) && timeA->CHIP_CRYPTO_PAL_PRIVATE(min) == timeB->CHIP_CRYPTO_PAL_PRIVATE(min) && timeA->CHIP_CRYPTO_PAL_PRIVATE(sec) >= timeB->CHIP_CRYPTO_PAL_PRIVATE(sec)); } CHIP_ERROR IsCertificateValidAtIssuance(const ByteSpan & referenceCertificate, const ByteSpan & toBeEvaluatedCertificate) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbedReferenceCertificate; mbedtls_x509_crt mbedToBeEvaluatedCertificate; mbedtls_x509_time refNotBeforeTime; mbedtls_x509_time tbeNotBeforeTime; mbedtls_x509_time tbeNotAfterTime; int result; VerifyOrReturnError(!referenceCertificate.empty() && !toBeEvaluatedCertificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); mbedtls_x509_crt_init(&mbedReferenceCertificate); mbedtls_x509_crt_init(&mbedToBeEvaluatedCertificate); result = mbedtls_x509_crt_parse(&mbedReferenceCertificate, Uint8::to_const_uchar(referenceCertificate.data()), referenceCertificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); result = mbedtls_x509_crt_parse(&mbedToBeEvaluatedCertificate, Uint8::to_const_uchar(toBeEvaluatedCertificate.data()), toBeEvaluatedCertificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); refNotBeforeTime = mbedReferenceCertificate.CHIP_CRYPTO_PAL_PRIVATE(valid_from); tbeNotBeforeTime = mbedToBeEvaluatedCertificate.CHIP_CRYPTO_PAL_PRIVATE(valid_from); tbeNotAfterTime = mbedToBeEvaluatedCertificate.CHIP_CRYPTO_PAL_PRIVATE(valid_to); // TODO: Handle PAA/PAI re-issue and enable below time validation // check if referenceCertificate is issued at or after tbeCertificate's notBefore timestamp // VerifyOrExit(IsTimeGreaterThanEqual(&refNotBeforeTime, &tbeNotBeforeTime), error = CHIP_ERROR_CERT_EXPIRED); // check if referenceCertificate is issued at or before tbeCertificate's notAfter timestamp // VerifyOrExit(IsTimeGreaterThanEqual(&tbeNotAfterTime, &refNotBeforeTime), error = CHIP_ERROR_CERT_EXPIRED); exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbedReferenceCertificate); mbedtls_x509_crt_free(&mbedToBeEvaluatedCertificate); #else (void) referenceCertificate; (void) toBeEvaluatedCertificate; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } CHIP_ERROR IsCertificateValidAtCurrentTime(const ByteSpan & certificate) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbedCertificate; int result; VerifyOrReturnError(!certificate.empty(), CHIP_ERROR_INVALID_ARGUMENT); mbedtls_x509_crt_init(&mbedCertificate); result = mbedtls_x509_crt_parse(&mbedCertificate, Uint8::to_const_uchar(certificate.data()), certificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); // check if certificate's notBefore timestamp is earlier than or equal to current time. result = mbedtls_x509_time_is_past(&mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE(valid_from)); VerifyOrExit(result == 1, error = CHIP_ERROR_CERT_EXPIRED); // check if certificate's notAfter timestamp is later than current time. result = mbedtls_x509_time_is_future(&mbedCertificate.CHIP_CRYPTO_PAL_PRIVATE(valid_to)); VerifyOrExit(result == 1, error = CHIP_ERROR_CERT_EXPIRED); exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbedCertificate); #else (void) certificate; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } CHIP_ERROR ExtractPubkeyFromX509Cert(const ByteSpan & certificate, Crypto::P256PublicKey & pubkey) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbed_cert; mbedtls_ecp_keypair * keypair = nullptr; size_t pubkey_size = 0; mbedtls_x509_crt_init(&mbed_cert); int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); keypair = mbedtls_pk_ec(mbed_cert.CHIP_CRYPTO_PAL_PRIVATE(pk)); // Copy the public key from the cert in raw point format result = mbedtls_ecp_point_write_binary(&keypair->CHIP_CRYPTO_PAL_PRIVATE(grp), &keypair->CHIP_CRYPTO_PAL_PRIVATE(Q), MBEDTLS_ECP_PF_UNCOMPRESSED, &pubkey_size, Uint8::to_uchar(pubkey.Bytes()), pubkey.Length()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); VerifyOrExit(pubkey_size == pubkey.Length(), error = CHIP_ERROR_INTERNAL); exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbed_cert); #else (void) certificate; (void) pubkey; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } namespace { CHIP_ERROR ExtractKIDFromX509Cert(bool isSKID, const ByteSpan & certificate, MutableByteSpan & kid) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbed_cert; unsigned char * p; const unsigned char * end; size_t len; constexpr uint8_t sOID_Extension_SubjectKeyIdentifier[] = { 0x55, 0x1D, 0x0E }; constexpr uint8_t sOID_Extension_AuthorityKeyIdentifier[] = { 0x55, 0x1D, 0x23 }; mbedtls_x509_crt_init(&mbed_cert); int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); p = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE(v3_ext).CHIP_CRYPTO_PAL_PRIVATE(p); end = mbed_cert.CHIP_CRYPTO_PAL_PRIVATE(v3_ext).CHIP_CRYPTO_PAL_PRIVATE(p) + mbed_cert.CHIP_CRYPTO_PAL_PRIVATE(v3_ext).CHIP_CRYPTO_PAL_PRIVATE(len); result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); while (p < end) { int is_critical = 0; result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OID); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); bool isRequiredKID = false; if (isSKID) { isRequiredKID = sizeof(sOID_Extension_SubjectKeyIdentifier) == len && memcmp(p, sOID_Extension_SubjectKeyIdentifier, len) == 0; } else { isRequiredKID = sizeof(sOID_Extension_AuthorityKeyIdentifier) == len && memcmp(p, sOID_Extension_AuthorityKeyIdentifier, len) == 0; } if (isRequiredKID) { size_t keyid_skip = isSKID ? 2 : 4; constexpr size_t kid_size = 20; p += len; result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); VerifyOrExit((len - keyid_skip) == kid_size, error = CHIP_ERROR_WRONG_CERT_TYPE); VerifyOrExit((len - keyid_skip) <= kid.size(), error = CHIP_ERROR_BUFFER_TOO_SMALL); memcpy(kid.data(), p + keyid_skip, kid_size); if (kid.size() > kid_size) { kid.reduce_size(kid_size); } break; } p += len; mbedtls_asn1_get_bool(&p, end, &is_critical); result = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_OCTET_STRING); VerifyOrExit(result == 0, error = CHIP_ERROR_WRONG_CERT_TYPE); p += len; } exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbed_cert); #else (void) certificate; (void) kid; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } } // namespace CHIP_ERROR ExtractSKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & skid) { return ExtractKIDFromX509Cert(true, certificate, skid); } CHIP_ERROR ExtractAKIDFromX509Cert(const ByteSpan & certificate, MutableByteSpan & akid) { return ExtractKIDFromX509Cert(false, certificate, akid); } namespace { CHIP_ERROR ExtractDNAttributeFromX509Cert(const uint8_t * oidAttribute, size_t oidAttributeLen, const ByteSpan & certificate, uint16_t & id) { #if defined(MBEDTLS_X509_CRT_PARSE_C) CHIP_ERROR error = CHIP_NO_ERROR; mbedtls_x509_crt mbed_cert; mbedtls_asn1_named_data * dnIterator = nullptr; constexpr size_t dnAttributeSize = 4; constexpr size_t dnAttributeStringSize = dnAttributeSize + 1; char dnAttribute[dnAttributeStringSize] = { 0 }; mbedtls_x509_crt_init(&mbed_cert); int result = mbedtls_x509_crt_parse(&mbed_cert, Uint8::to_const_uchar(certificate.data()), certificate.size()); VerifyOrExit(result == 0, error = CHIP_ERROR_INTERNAL); for (dnIterator = &mbed_cert.CHIP_CRYPTO_PAL_PRIVATE(subject); dnIterator != nullptr; dnIterator = dnIterator->CHIP_CRYPTO_PAL_PRIVATE(next)) { if (dnIterator != nullptr && dnIterator->CHIP_CRYPTO_PAL_PRIVATE(oid).CHIP_CRYPTO_PAL_PRIVATE(p) != nullptr && dnIterator->CHIP_CRYPTO_PAL_PRIVATE(oid).CHIP_CRYPTO_PAL_PRIVATE(len) == oidAttributeLen && memcmp(oidAttribute, dnIterator->CHIP_CRYPTO_PAL_PRIVATE(oid).CHIP_CRYPTO_PAL_PRIVATE(p), dnIterator->CHIP_CRYPTO_PAL_PRIVATE(oid).CHIP_CRYPTO_PAL_PRIVATE(len)) == 0 && dnIterator->CHIP_CRYPTO_PAL_PRIVATE(val).CHIP_CRYPTO_PAL_PRIVATE(p) != nullptr && dnIterator->CHIP_CRYPTO_PAL_PRIVATE(val).CHIP_CRYPTO_PAL_PRIVATE(len) == dnAttributeSize) { // vendor id is of size 4, we should ensure the string is null terminated before passing in to strtoul to avoid // undefined behavior memcpy(dnAttribute, dnIterator->CHIP_CRYPTO_PAL_PRIVATE(val).CHIP_CRYPTO_PAL_PRIVATE(p), dnAttributeSize); dnAttribute[dnAttributeSize] = 0; VerifyOrExit(ArgParser::ParseInt(dnAttribute, id, 16), error = CHIP_ERROR_INTERNAL); break; } } // returning CHIP_ERROR_KEY_NOT_FOUND to indicate that the DN Attribute is not present in the certificate. VerifyOrExit(dnIterator != nullptr, error = CHIP_ERROR_KEY_NOT_FOUND); exit: _log_mbedTLS_error(result); mbedtls_x509_crt_free(&mbed_cert); #else (void) oidAttribute; (void) oidAttributeLen; (void) certificate; (void) id; CHIP_ERROR error = CHIP_ERROR_NOT_IMPLEMENTED; #endif // defined(MBEDTLS_X509_CRT_PARSE_C) return error; } } // namespace CHIP_ERROR ExtractDNAttributeFromX509Cert(MatterOid matterOid, const ByteSpan & certificate, uint16_t & id) { constexpr uint8_t sOID_AttributeType_ChipVendorId[] = { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C, 0x02, 0x01 }; constexpr uint8_t sOID_AttributeType_ChipProductId[] = { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0xA2, 0x7C, 0x02, 0x02 }; switch (matterOid) { case MatterOid::kVendorId: id = VendorId::NotSpecified; return ExtractDNAttributeFromX509Cert(sOID_AttributeType_ChipVendorId, sizeof(sOID_AttributeType_ChipVendorId), certificate, id); case MatterOid::kProductId: id = 0; // PID not specified value return ExtractDNAttributeFromX509Cert(sOID_AttributeType_ChipProductId, sizeof(sOID_AttributeType_ChipProductId), certificate, id); default: return CHIP_ERROR_INVALID_ARGUMENT; } } } // namespace Crypto } // namespace chip ",16311,True,2915.9326278619133,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: petar@google.com (Petar Petrov) #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if PY_MAJOR_VERSION >= 3 #define PyString_FromStringAndSize PyUnicode_FromStringAndSize #define PyString_Check PyUnicode_Check #define PyString_InternFromString PyUnicode_InternFromString #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #if PY_VERSION_HEX < 0x03030000 #error ""Python 3.0 - 3.2 are not supported."" #endif #define PyString_AsStringAndSize(ob, charpp, sizep) \\ (PyUnicode_Check(ob) ? ((*(charpp) = const_cast( \\ PyUnicode_AsUTF8AndSize(ob, (sizep)))) == NULL \\ ? -1 \\ : 0) \\ : PyBytes_AsStringAndSize(ob, (charpp), (sizep))) #endif namespace google { namespace protobuf { namespace python { // Store interned descriptors, so that the same C++ descriptor yields the same // Python object. Objects are not immortal: this map does not own the // references, and items are deleted when the last reference to the object is // released. // This is enough to support the ""is"" operator on live objects. // All descriptors are stored here. std::unordered_map* interned_descriptors; PyObject* PyString_FromCppString(const string& str) { return PyString_FromStringAndSize(str.c_str(), str.size()); } // Check that the calling Python code is the global scope of a _pb2.py module. // This function is used to support the current code generated by the proto // compiler, which creates descriptors, then update some properties. // For example: // message_descriptor = Descriptor( // name='Message', // fields = [FieldDescriptor(name='field')] // message_descriptor.fields[0].containing_type = message_descriptor // // This code is still executed, but the descriptors now have no other storage // than the (const) C++ pointer, and are immutable. // So we let this code pass, by simply ignoring the new value. // // From user code, descriptors still look immutable. // // TODO(amauryfa): Change the proto2 compiler to remove the assignments, and // remove this hack. bool _CalledFromGeneratedFile(int stacklevel) { #ifndef PYPY_VERSION // This check is not critical and is somewhat difficult to implement correctly // in PyPy. PyFrameObject* frame = PyEval_GetFrame(); if (frame == NULL) { return false; } while (stacklevel-- > 0) { frame = frame->f_back; if (frame == NULL) { return false; } } if (frame->f_code->co_filename == NULL) { return false; } char* filename; Py_ssize_t filename_size; if (PyString_AsStringAndSize(frame->f_code->co_filename, &filename, &filename_size) < 0) { // filename is not a string. PyErr_Clear(); return false; } if ((filename_size < 3) || (strcmp(&filename[filename_size - 3], "".py"") != 0)) { // Cython's stack does not have .py file name and is not at global module // scope. return true; } if (filename_size < 7) { // filename is too short. return false; } if (strcmp(&filename[filename_size - 7], ""_pb2.py"") != 0) { // Filename is not ending with _pb2. return false; } if (frame->f_globals != frame->f_locals) { // Not at global module scope return false; } #endif return true; } // If the calling code is not a _pb2.py file, raise AttributeError. // To be used in attribute setters. static int CheckCalledFromGeneratedFile(const char* attr_name) { if (_CalledFromGeneratedFile(0)) { return 0; } PyErr_Format(PyExc_AttributeError, ""attribute is not writable: %s"", attr_name); return -1; } #ifndef PyVarObject_HEAD_INIT #define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size, #endif #ifndef Py_TYPE #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) #endif // Helper functions for descriptor objects. // A set of templates to retrieve the C++ FileDescriptor of any descriptor. template const FileDescriptor* GetFileDescriptor(const DescriptorClass* descriptor) { return descriptor->file(); } template<> const FileDescriptor* GetFileDescriptor(const FileDescriptor* descriptor) { return descriptor; } template<> const FileDescriptor* GetFileDescriptor(const EnumValueDescriptor* descriptor) { return descriptor->type()->file(); } template<> const FileDescriptor* GetFileDescriptor(const OneofDescriptor* descriptor) { return descriptor->containing_type()->file(); } template<> const FileDescriptor* GetFileDescriptor(const MethodDescriptor* descriptor) { return descriptor->service()->file(); } bool Reparse( PyMessageFactory* message_factory, const Message& from, Message* to) { // Reparse message. string serialized; from.SerializeToString(&serialized); io::CodedInputStream input( reinterpret_cast(serialized.c_str()), serialized.size()); input.SetExtensionRegistry(message_factory->pool->pool, message_factory->message_factory); bool success = to->ParseFromCodedStream(&input); if (!success) { return false; } return true; } // Converts options into a Python protobuf, and cache the result. // // This is a bit tricky because options can contain extension fields defined in // the same proto file. In this case the options parsed from the serialized_pb // have unknown fields, and we need to parse them again. // // Always returns a new reference. template static PyObject* GetOrBuildOptions(const DescriptorClass *descriptor) { // Options are cached in the pool that owns the descriptor. // First search in the cache. PyDescriptorPool* caching_pool = GetDescriptorPool_FromPool( GetFileDescriptor(descriptor)->pool()); std::unordered_map* descriptor_options = caching_pool->descriptor_options; if (descriptor_options->find(descriptor) != descriptor_options->end()) { PyObject *value = (*descriptor_options)[descriptor]; Py_INCREF(value); return value; } // Similar to the C++ implementation, we return an Options object from the // default (generated) factory, so that client code know that they can use // extensions from generated files: // d.GetOptions().Extensions[some_pb2.extension] // // The consequence is that extensions not defined in the default pool won't // be available. If needed, we could add an optional 'message_factory' // parameter to the GetOptions() function. PyMessageFactory* message_factory = GetDefaultDescriptorPool()->py_message_factory; // Build the Options object: get its Python class, and make a copy of the C++ // read-only instance. const Message& options(descriptor->options()); const Descriptor *message_type = options.GetDescriptor(); CMessageClass* message_class = message_factory::GetOrCreateMessageClass( message_factory, message_type); if (message_class == NULL) { PyErr_Format(PyExc_TypeError, ""Could not retrieve class for Options: %s"", message_type->full_name().c_str()); return NULL; } ScopedPyObjectPtr value( PyEval_CallObject(message_class->AsPyObject(), NULL)); if (value == NULL) { return NULL; } if (!PyObject_TypeCheck(value.get(), CMessage_Type)) { PyErr_Format(PyExc_TypeError, ""Invalid class for %s: %s"", message_type->full_name().c_str(), Py_TYPE(value.get())->tp_name); return NULL; } CMessage* cmsg = reinterpret_cast(value.get()); const Reflection* reflection = options.GetReflection(); const UnknownFieldSet& unknown_fields(reflection->GetUnknownFields(options)); if (unknown_fields.empty()) { cmsg->message->CopyFrom(options); } else { // Reparse options string! XXX call cmessage::MergeFromString if (!Reparse(message_factory, options, cmsg->message)) { PyErr_Format(PyExc_ValueError, ""Error reparsing Options message""); return NULL; } } // Cache the result. Py_INCREF(value.get()); (*descriptor_options)[descriptor] = value.get(); return value.release(); } // Copy the C++ descriptor to a Python message. // The Python message is an instance of descriptor_pb2.DescriptorProto // or similar. template static PyObject* CopyToPythonProto(const DescriptorClass *descriptor, PyObject *target) { const Descriptor* self_descriptor = DescriptorProtoClass::default_instance().GetDescriptor(); CMessage* message = reinterpret_cast(target); if (!PyObject_TypeCheck(target, CMessage_Type) || message->message->GetDescriptor() != self_descriptor) { PyErr_Format(PyExc_TypeError, ""Not a %s message"", self_descriptor->full_name().c_str()); return NULL; } cmessage::AssureWritable(message); DescriptorProtoClass* descriptor_message = static_cast(message->message); descriptor->CopyTo(descriptor_message); // Custom options might in unknown extensions. Reparse // the descriptor_message. Can't skip reparse when options unknown // fields is empty, because they might in sub descriptors' options. PyMessageFactory* message_factory = GetDefaultDescriptorPool()->py_message_factory; if (!Reparse(message_factory, *descriptor_message, descriptor_message)) { PyErr_Format(PyExc_ValueError, ""Error reparsing descriptor message""); return nullptr; } Py_RETURN_NONE; } // All Descriptors classes share the same memory layout. typedef struct PyBaseDescriptor { PyObject_HEAD // Pointer to the C++ proto2 descriptor. // Like all descriptors, it is owned by the global DescriptorPool. const void* descriptor; // Owned reference to the DescriptorPool, to ensure it is kept alive. PyDescriptorPool* pool; } PyBaseDescriptor; // FileDescriptor structure ""inherits"" from the base descriptor. typedef struct PyFileDescriptor { PyBaseDescriptor base; // The cached version of serialized pb. Either NULL, or a Bytes string. // We own the reference. PyObject *serialized_pb; } PyFileDescriptor; namespace descriptor { // Creates or retrieve a Python descriptor of the specified type. // Objects are interned: the same descriptor will return the same object if it // was kept alive. // 'was_created' is an optional pointer to a bool, and is set to true if a new // object was allocated. // Always return a new reference. template PyObject* NewInternedDescriptor(PyTypeObject* type, const DescriptorClass* descriptor, bool* was_created) { if (was_created) { *was_created = false; } if (descriptor == NULL) { PyErr_BadInternalCall(); return NULL; } // See if the object is in the map of interned descriptors std::unordered_map::iterator it = interned_descriptors->find(descriptor); if (it != interned_descriptors->end()) { GOOGLE_DCHECK(Py_TYPE(it->second) == type); Py_INCREF(it->second); return it->second; } // Create a new descriptor object PyBaseDescriptor* py_descriptor = PyObject_New( PyBaseDescriptor, type); if (py_descriptor == NULL) { return NULL; } py_descriptor->descriptor = descriptor; // and cache it. interned_descriptors->insert( std::make_pair(descriptor, reinterpret_cast(py_descriptor))); // Ensures that the DescriptorPool stays alive. PyDescriptorPool* pool = GetDescriptorPool_FromPool( GetFileDescriptor(descriptor)->pool()); if (pool == NULL) { // Don't DECREF, the object is not fully initialized. PyObject_Del(py_descriptor); return NULL; } Py_INCREF(pool); py_descriptor->pool = pool; if (was_created) { *was_created = true; } return reinterpret_cast(py_descriptor); } static void Dealloc(PyBaseDescriptor* self) { // Remove from interned dictionary interned_descriptors->erase(self->descriptor); Py_CLEAR(self->pool); Py_TYPE(self)->tp_free(reinterpret_cast(self)); } static PyGetSetDef Getters[] = { {NULL} }; PyTypeObject PyBaseDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".DescriptorBase"", // tp_name sizeof(PyBaseDescriptor), // tp_basicsize 0, // tp_itemsize (destructor)Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""Descriptors base class"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext 0, // tp_methods 0, // tp_members Getters, // tp_getset }; } // namespace descriptor const void* PyDescriptor_AsVoidPtr(PyObject* obj) { if (!PyObject_TypeCheck(obj, &descriptor::PyBaseDescriptor_Type)) { PyErr_SetString(PyExc_TypeError, ""Not a BaseDescriptor""); return NULL; } return reinterpret_cast(obj)->descriptor; } namespace message_descriptor { // Unchecked accessor to the C++ pointer. static const Descriptor* _GetDescriptor(PyBaseDescriptor* self) { return reinterpret_cast(self->descriptor); } static PyObject* GetName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->name()); } static PyObject* GetFullName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->full_name()); } static PyObject* GetFile(PyBaseDescriptor *self, void *closure) { return PyFileDescriptor_FromDescriptor(_GetDescriptor(self)->file()); } static PyObject* GetConcreteClass(PyBaseDescriptor* self, void *closure) { // Retuns the canonical class for the given descriptor. // This is the class that was registered with the primary descriptor pool // which contains this descriptor. // This might not be the one you expect! For example the returned object does // not know about extensions defined in a custom pool. CMessageClass* concrete_class(message_factory::GetMessageClass( GetDescriptorPool_FromPool( _GetDescriptor(self)->file()->pool())->py_message_factory, _GetDescriptor(self))); Py_XINCREF(concrete_class); return concrete_class->AsPyObject(); } static PyObject* GetFieldsByName(PyBaseDescriptor* self, void *closure) { return NewMessageFieldsByName(_GetDescriptor(self)); } static PyObject* GetFieldsByCamelcaseName(PyBaseDescriptor* self, void *closure) { return NewMessageFieldsByCamelcaseName(_GetDescriptor(self)); } static PyObject* GetFieldsByNumber(PyBaseDescriptor* self, void *closure) { return NewMessageFieldsByNumber(_GetDescriptor(self)); } static PyObject* GetFieldsSeq(PyBaseDescriptor* self, void *closure) { return NewMessageFieldsSeq(_GetDescriptor(self)); } static PyObject* GetNestedTypesByName(PyBaseDescriptor* self, void *closure) { return NewMessageNestedTypesByName(_GetDescriptor(self)); } static PyObject* GetNestedTypesSeq(PyBaseDescriptor* self, void *closure) { return NewMessageNestedTypesSeq(_GetDescriptor(self)); } static PyObject* GetExtensionsByName(PyBaseDescriptor* self, void *closure) { return NewMessageExtensionsByName(_GetDescriptor(self)); } static PyObject* GetExtensions(PyBaseDescriptor* self, void *closure) { return NewMessageExtensionsSeq(_GetDescriptor(self)); } static PyObject* GetEnumsSeq(PyBaseDescriptor* self, void *closure) { return NewMessageEnumsSeq(_GetDescriptor(self)); } static PyObject* GetEnumTypesByName(PyBaseDescriptor* self, void *closure) { return NewMessageEnumsByName(_GetDescriptor(self)); } static PyObject* GetEnumValuesByName(PyBaseDescriptor* self, void *closure) { return NewMessageEnumValuesByName(_GetDescriptor(self)); } static PyObject* GetOneofsByName(PyBaseDescriptor* self, void *closure) { return NewMessageOneofsByName(_GetDescriptor(self)); } static PyObject* GetOneofsSeq(PyBaseDescriptor* self, void *closure) { return NewMessageOneofsSeq(_GetDescriptor(self)); } static PyObject* IsExtendable(PyBaseDescriptor *self, void *closure) { if (_GetDescriptor(self)->extension_range_count() > 0) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static PyObject* GetExtensionRanges(PyBaseDescriptor *self, void *closure) { const Descriptor* descriptor = _GetDescriptor(self); PyObject* range_list = PyList_New(descriptor->extension_range_count()); for (int i = 0; i < descriptor->extension_range_count(); i++) { const Descriptor::ExtensionRange* range = descriptor->extension_range(i); PyObject* start = PyInt_FromLong(range->start); PyObject* end = PyInt_FromLong(range->end); PyList_SetItem(range_list, i, PyTuple_Pack(2, start, end)); } return range_list; } static PyObject* GetContainingType(PyBaseDescriptor *self, void *closure) { const Descriptor* containing_type = _GetDescriptor(self)->containing_type(); if (containing_type) { return PyMessageDescriptor_FromDescriptor(containing_type); } else { Py_RETURN_NONE; } } static int SetContainingType(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""containing_type""); } static PyObject* GetHasOptions(PyBaseDescriptor *self, void *closure) { const MessageOptions& options(_GetDescriptor(self)->options()); if (&options != &MessageOptions::default_instance()) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static int SetHasOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""has_options""); } static PyObject* GetOptions(PyBaseDescriptor *self) { return GetOrBuildOptions(_GetDescriptor(self)); } static int SetOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_options""); } static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_serialized_options""); } static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) { return CopyToPythonProto(_GetDescriptor(self), target); } static PyObject* EnumValueName(PyBaseDescriptor *self, PyObject *args) { const char *enum_name; int number; if (!PyArg_ParseTuple(args, ""si"", &enum_name, &number)) return NULL; const EnumDescriptor *enum_type = _GetDescriptor(self)->FindEnumTypeByName(enum_name); if (enum_type == NULL) { PyErr_SetString(PyExc_KeyError, enum_name); return NULL; } const EnumValueDescriptor *enum_value = enum_type->FindValueByNumber(number); if (enum_value == NULL) { PyErr_Format(PyExc_KeyError, ""%d"", number); return NULL; } return PyString_FromCppString(enum_value->name()); } static PyObject* GetSyntax(PyBaseDescriptor *self, void *closure) { return PyString_InternFromString( FileDescriptor::SyntaxName(_GetDescriptor(self)->file()->syntax())); } static PyGetSetDef Getters[] = { { ""name"", (getter)GetName, NULL, ""Last name""}, { ""full_name"", (getter)GetFullName, NULL, ""Full name""}, { ""_concrete_class"", (getter)GetConcreteClass, NULL, ""concrete class""}, { ""file"", (getter)GetFile, NULL, ""File descriptor""}, { ""fields"", (getter)GetFieldsSeq, NULL, ""Fields sequence""}, { ""fields_by_name"", (getter)GetFieldsByName, NULL, ""Fields by name""}, { ""fields_by_camelcase_name"", (getter)GetFieldsByCamelcaseName, NULL, ""Fields by camelCase name""}, { ""fields_by_number"", (getter)GetFieldsByNumber, NULL, ""Fields by number""}, { ""nested_types"", (getter)GetNestedTypesSeq, NULL, ""Nested types sequence""}, { ""nested_types_by_name"", (getter)GetNestedTypesByName, NULL, ""Nested types by name""}, { ""extensions"", (getter)GetExtensions, NULL, ""Extensions Sequence""}, { ""extensions_by_name"", (getter)GetExtensionsByName, NULL, ""Extensions by name""}, { ""extension_ranges"", (getter)GetExtensionRanges, NULL, ""Extension ranges""}, { ""enum_types"", (getter)GetEnumsSeq, NULL, ""Enum sequence""}, { ""enum_types_by_name"", (getter)GetEnumTypesByName, NULL, ""Enum types by name""}, { ""enum_values_by_name"", (getter)GetEnumValuesByName, NULL, ""Enum values by name""}, { ""oneofs_by_name"", (getter)GetOneofsByName, NULL, ""Oneofs by name""}, { ""oneofs"", (getter)GetOneofsSeq, NULL, ""Oneofs by name""}, { ""containing_type"", (getter)GetContainingType, (setter)SetContainingType, ""Containing type""}, { ""is_extendable"", (getter)IsExtendable, (setter)NULL}, { ""has_options"", (getter)GetHasOptions, (setter)SetHasOptions, ""Has Options""}, { ""_options"", (getter)NULL, (setter)SetOptions, ""Options""}, { ""_serialized_options"", (getter)NULL, (setter)SetSerializedOptions, ""Serialized Options""}, { ""syntax"", (getter)GetSyntax, (setter)NULL, ""Syntax""}, {NULL} }; static PyMethodDef Methods[] = { { ""GetOptions"", (PyCFunction)GetOptions, METH_NOARGS, }, { ""CopyToProto"", (PyCFunction)CopyToProto, METH_O, }, { ""EnumValueName"", (PyCFunction)EnumValueName, METH_VARARGS, }, {NULL} }; } // namespace message_descriptor PyTypeObject PyMessageDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".MessageDescriptor"", // tp_name sizeof(PyBaseDescriptor), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""A Message Descriptor"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext message_descriptor::Methods, // tp_methods 0, // tp_members message_descriptor::Getters, // tp_getset &descriptor::PyBaseDescriptor_Type, // tp_base }; PyObject* PyMessageDescriptor_FromDescriptor( const Descriptor* message_descriptor) { return descriptor::NewInternedDescriptor( &PyMessageDescriptor_Type, message_descriptor, NULL); } const Descriptor* PyMessageDescriptor_AsDescriptor(PyObject* obj) { if (!PyObject_TypeCheck(obj, &PyMessageDescriptor_Type)) { PyErr_SetString(PyExc_TypeError, ""Not a MessageDescriptor""); return NULL; } return reinterpret_cast( reinterpret_cast(obj)->descriptor); } namespace field_descriptor { // Unchecked accessor to the C++ pointer. static const FieldDescriptor* _GetDescriptor( PyBaseDescriptor *self) { return reinterpret_cast(self->descriptor); } static PyObject* GetFullName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->full_name()); } static PyObject* GetName(PyBaseDescriptor *self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->name()); } static PyObject* GetCamelcaseName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->camelcase_name()); } static PyObject* GetJsonName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->json_name()); } static PyObject* GetFile(PyBaseDescriptor *self, void *closure) { return PyFileDescriptor_FromDescriptor(_GetDescriptor(self)->file()); } static PyObject* GetType(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->type()); } static PyObject* GetCppType(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->cpp_type()); } static PyObject* GetLabel(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->label()); } static PyObject* GetNumber(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->number()); } static PyObject* GetIndex(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->index()); } static PyObject* GetID(PyBaseDescriptor *self, void *closure) { return PyLong_FromVoidPtr(self); } static PyObject* IsExtension(PyBaseDescriptor *self, void *closure) { return PyBool_FromLong(_GetDescriptor(self)->is_extension()); } static PyObject* HasDefaultValue(PyBaseDescriptor *self, void *closure) { return PyBool_FromLong(_GetDescriptor(self)->has_default_value()); } static PyObject* GetDefaultValue(PyBaseDescriptor *self, void *closure) { PyObject *result; if (_GetDescriptor(self)->is_repeated()) { return PyList_New(0); } switch (_GetDescriptor(self)->cpp_type()) { case FieldDescriptor::CPPTYPE_INT32: { int32 value = _GetDescriptor(self)->default_value_int32(); result = PyInt_FromLong(value); break; } case FieldDescriptor::CPPTYPE_INT64: { int64 value = _GetDescriptor(self)->default_value_int64(); result = PyLong_FromLongLong(value); break; } case FieldDescriptor::CPPTYPE_UINT32: { uint32 value = _GetDescriptor(self)->default_value_uint32(); result = PyInt_FromSize_t(value); break; } case FieldDescriptor::CPPTYPE_UINT64: { uint64 value = _GetDescriptor(self)->default_value_uint64(); result = PyLong_FromUnsignedLongLong(value); break; } case FieldDescriptor::CPPTYPE_FLOAT: { float value = _GetDescriptor(self)->default_value_float(); result = PyFloat_FromDouble(value); break; } case FieldDescriptor::CPPTYPE_DOUBLE: { double value = _GetDescriptor(self)->default_value_double(); result = PyFloat_FromDouble(value); break; } case FieldDescriptor::CPPTYPE_BOOL: { bool value = _GetDescriptor(self)->default_value_bool(); result = PyBool_FromLong(value); break; } case FieldDescriptor::CPPTYPE_STRING: { const string& value = _GetDescriptor(self)->default_value_string(); result = ToStringObject(_GetDescriptor(self), value); break; } case FieldDescriptor::CPPTYPE_ENUM: { const EnumValueDescriptor* value = _GetDescriptor(self)->default_value_enum(); result = PyInt_FromLong(value->number()); break; } case FieldDescriptor::CPPTYPE_MESSAGE: { Py_RETURN_NONE; break; } default: PyErr_Format(PyExc_NotImplementedError, ""default value for %s"", _GetDescriptor(self)->full_name().c_str()); return NULL; } return result; } static PyObject* GetCDescriptor(PyObject *self, void *closure) { Py_INCREF(self); return self; } static PyObject *GetEnumType(PyBaseDescriptor *self, void *closure) { const EnumDescriptor* enum_type = _GetDescriptor(self)->enum_type(); if (enum_type) { return PyEnumDescriptor_FromDescriptor(enum_type); } else { Py_RETURN_NONE; } } static int SetEnumType(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""enum_type""); } static PyObject *GetMessageType(PyBaseDescriptor *self, void *closure) { const Descriptor* message_type = _GetDescriptor(self)->message_type(); if (message_type) { return PyMessageDescriptor_FromDescriptor(message_type); } else { Py_RETURN_NONE; } } static int SetMessageType(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""message_type""); } static PyObject* GetContainingType(PyBaseDescriptor *self, void *closure) { const Descriptor* containing_type = _GetDescriptor(self)->containing_type(); if (containing_type) { return PyMessageDescriptor_FromDescriptor(containing_type); } else { Py_RETURN_NONE; } } static int SetContainingType(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""containing_type""); } static PyObject* GetExtensionScope(PyBaseDescriptor *self, void *closure) { const Descriptor* extension_scope = _GetDescriptor(self)->extension_scope(); if (extension_scope) { return PyMessageDescriptor_FromDescriptor(extension_scope); } else { Py_RETURN_NONE; } } static PyObject* GetContainingOneof(PyBaseDescriptor *self, void *closure) { const OneofDescriptor* containing_oneof = _GetDescriptor(self)->containing_oneof(); if (containing_oneof) { return PyOneofDescriptor_FromDescriptor(containing_oneof); } else { Py_RETURN_NONE; } } static int SetContainingOneof(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""containing_oneof""); } static PyObject* GetHasOptions(PyBaseDescriptor *self, void *closure) { const FieldOptions& options(_GetDescriptor(self)->options()); if (&options != &FieldOptions::default_instance()) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static int SetHasOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""has_options""); } static PyObject* GetOptions(PyBaseDescriptor *self) { return GetOrBuildOptions(_GetDescriptor(self)); } static int SetOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_options""); } static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_serialized_options""); } static PyGetSetDef Getters[] = { { ""full_name"", (getter)GetFullName, NULL, ""Full name""}, { ""name"", (getter)GetName, NULL, ""Unqualified name""}, { ""camelcase_name"", (getter)GetCamelcaseName, NULL, ""Camelcase name""}, { ""json_name"", (getter)GetJsonName, NULL, ""Json name""}, { ""file"", (getter)GetFile, NULL, ""File Descriptor""}, { ""type"", (getter)GetType, NULL, ""C++ Type""}, { ""cpp_type"", (getter)GetCppType, NULL, ""C++ Type""}, { ""label"", (getter)GetLabel, NULL, ""Label""}, { ""number"", (getter)GetNumber, NULL, ""Number""}, { ""index"", (getter)GetIndex, NULL, ""Index""}, { ""default_value"", (getter)GetDefaultValue, NULL, ""Default Value""}, { ""has_default_value"", (getter)HasDefaultValue}, { ""is_extension"", (getter)IsExtension, NULL, ""ID""}, { ""id"", (getter)GetID, NULL, ""ID""}, { ""_cdescriptor"", (getter)GetCDescriptor, NULL, ""HAACK REMOVE ME""}, { ""message_type"", (getter)GetMessageType, (setter)SetMessageType, ""Message type""}, { ""enum_type"", (getter)GetEnumType, (setter)SetEnumType, ""Enum type""}, { ""containing_type"", (getter)GetContainingType, (setter)SetContainingType, ""Containing type""}, { ""extension_scope"", (getter)GetExtensionScope, (setter)NULL, ""Extension scope""}, { ""containing_oneof"", (getter)GetContainingOneof, (setter)SetContainingOneof, ""Containing oneof""}, { ""has_options"", (getter)GetHasOptions, (setter)SetHasOptions, ""Has Options""}, { ""_options"", (getter)NULL, (setter)SetOptions, ""Options""}, { ""_serialized_options"", (getter)NULL, (setter)SetSerializedOptions, ""Serialized Options""}, {NULL} }; static PyMethodDef Methods[] = { { ""GetOptions"", (PyCFunction)GetOptions, METH_NOARGS, }, {NULL} }; } // namespace field_descriptor PyTypeObject PyFieldDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".FieldDescriptor"", // tp_name sizeof(PyBaseDescriptor), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""A Field Descriptor"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext field_descriptor::Methods, // tp_methods 0, // tp_members field_descriptor::Getters, // tp_getset &descriptor::PyBaseDescriptor_Type, // tp_base }; PyObject* PyFieldDescriptor_FromDescriptor( const FieldDescriptor* field_descriptor) { return descriptor::NewInternedDescriptor( &PyFieldDescriptor_Type, field_descriptor, NULL); } const FieldDescriptor* PyFieldDescriptor_AsDescriptor(PyObject* obj) { if (!PyObject_TypeCheck(obj, &PyFieldDescriptor_Type)) { PyErr_SetString(PyExc_TypeError, ""Not a FieldDescriptor""); return NULL; } return reinterpret_cast( reinterpret_cast(obj)->descriptor); } namespace enum_descriptor { // Unchecked accessor to the C++ pointer. static const EnumDescriptor* _GetDescriptor( PyBaseDescriptor *self) { return reinterpret_cast(self->descriptor); } static PyObject* GetFullName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->full_name()); } static PyObject* GetName(PyBaseDescriptor *self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->name()); } static PyObject* GetFile(PyBaseDescriptor *self, void *closure) { return PyFileDescriptor_FromDescriptor(_GetDescriptor(self)->file()); } static PyObject* GetEnumvaluesByName(PyBaseDescriptor* self, void *closure) { return NewEnumValuesByName(_GetDescriptor(self)); } static PyObject* GetEnumvaluesByNumber(PyBaseDescriptor* self, void *closure) { return NewEnumValuesByNumber(_GetDescriptor(self)); } static PyObject* GetEnumvaluesSeq(PyBaseDescriptor* self, void *closure) { return NewEnumValuesSeq(_GetDescriptor(self)); } static PyObject* GetContainingType(PyBaseDescriptor *self, void *closure) { const Descriptor* containing_type = _GetDescriptor(self)->containing_type(); if (containing_type) { return PyMessageDescriptor_FromDescriptor(containing_type); } else { Py_RETURN_NONE; } } static int SetContainingType(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""containing_type""); } static PyObject* GetHasOptions(PyBaseDescriptor *self, void *closure) { const EnumOptions& options(_GetDescriptor(self)->options()); if (&options != &EnumOptions::default_instance()) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static int SetHasOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""has_options""); } static PyObject* GetOptions(PyBaseDescriptor *self) { return GetOrBuildOptions(_GetDescriptor(self)); } static int SetOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_options""); } static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_serialized_options""); } static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) { return CopyToPythonProto(_GetDescriptor(self), target); } static PyMethodDef Methods[] = { { ""GetOptions"", (PyCFunction)GetOptions, METH_NOARGS, }, { ""CopyToProto"", (PyCFunction)CopyToProto, METH_O, }, {NULL} }; static PyGetSetDef Getters[] = { { ""full_name"", (getter)GetFullName, NULL, ""Full name""}, { ""name"", (getter)GetName, NULL, ""last name""}, { ""file"", (getter)GetFile, NULL, ""File descriptor""}, { ""values"", (getter)GetEnumvaluesSeq, NULL, ""values""}, { ""values_by_name"", (getter)GetEnumvaluesByName, NULL, ""Enum values by name""}, { ""values_by_number"", (getter)GetEnumvaluesByNumber, NULL, ""Enum values by number""}, { ""containing_type"", (getter)GetContainingType, (setter)SetContainingType, ""Containing type""}, { ""has_options"", (getter)GetHasOptions, (setter)SetHasOptions, ""Has Options""}, { ""_options"", (getter)NULL, (setter)SetOptions, ""Options""}, { ""_serialized_options"", (getter)NULL, (setter)SetSerializedOptions, ""Serialized Options""}, {NULL} }; } // namespace enum_descriptor PyTypeObject PyEnumDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".EnumDescriptor"", // tp_name sizeof(PyBaseDescriptor), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""A Enum Descriptor"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext enum_descriptor::Methods, // tp_methods 0, // tp_members enum_descriptor::Getters, // tp_getset &descriptor::PyBaseDescriptor_Type, // tp_base }; PyObject* PyEnumDescriptor_FromDescriptor( const EnumDescriptor* enum_descriptor) { return descriptor::NewInternedDescriptor( &PyEnumDescriptor_Type, enum_descriptor, NULL); } const EnumDescriptor* PyEnumDescriptor_AsDescriptor(PyObject* obj) { if (!PyObject_TypeCheck(obj, &PyEnumDescriptor_Type)) { PyErr_SetString(PyExc_TypeError, ""Not an EnumDescriptor""); return NULL; } return reinterpret_cast( reinterpret_cast(obj)->descriptor); } namespace enumvalue_descriptor { // Unchecked accessor to the C++ pointer. static const EnumValueDescriptor* _GetDescriptor( PyBaseDescriptor *self) { return reinterpret_cast(self->descriptor); } static PyObject* GetName(PyBaseDescriptor *self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->name()); } static PyObject* GetNumber(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->number()); } static PyObject* GetIndex(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->index()); } static PyObject* GetType(PyBaseDescriptor *self, void *closure) { return PyEnumDescriptor_FromDescriptor(_GetDescriptor(self)->type()); } static PyObject* GetHasOptions(PyBaseDescriptor *self, void *closure) { const EnumValueOptions& options(_GetDescriptor(self)->options()); if (&options != &EnumValueOptions::default_instance()) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static int SetHasOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""has_options""); } static PyObject* GetOptions(PyBaseDescriptor *self) { return GetOrBuildOptions(_GetDescriptor(self)); } static int SetOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_options""); } static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_serialized_options""); } static PyGetSetDef Getters[] = { { ""name"", (getter)GetName, NULL, ""name""}, { ""number"", (getter)GetNumber, NULL, ""number""}, { ""index"", (getter)GetIndex, NULL, ""index""}, { ""type"", (getter)GetType, NULL, ""index""}, { ""has_options"", (getter)GetHasOptions, (setter)SetHasOptions, ""Has Options""}, { ""_options"", (getter)NULL, (setter)SetOptions, ""Options""}, { ""_serialized_options"", (getter)NULL, (setter)SetSerializedOptions, ""Serialized Options""}, {NULL} }; static PyMethodDef Methods[] = { { ""GetOptions"", (PyCFunction)GetOptions, METH_NOARGS, }, {NULL} }; } // namespace enumvalue_descriptor PyTypeObject PyEnumValueDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".EnumValueDescriptor"", // tp_name sizeof(PyBaseDescriptor), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""A EnumValue Descriptor"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext enumvalue_descriptor::Methods, // tp_methods 0, // tp_members enumvalue_descriptor::Getters, // tp_getset &descriptor::PyBaseDescriptor_Type, // tp_base }; PyObject* PyEnumValueDescriptor_FromDescriptor( const EnumValueDescriptor* enumvalue_descriptor) { return descriptor::NewInternedDescriptor( &PyEnumValueDescriptor_Type, enumvalue_descriptor, NULL); } namespace file_descriptor { // Unchecked accessor to the C++ pointer. static const FileDescriptor* _GetDescriptor(PyFileDescriptor *self) { return reinterpret_cast(self->base.descriptor); } static void Dealloc(PyFileDescriptor* self) { Py_XDECREF(self->serialized_pb); descriptor::Dealloc(&self->base); } static PyObject* GetPool(PyFileDescriptor *self, void *closure) { PyObject* pool = reinterpret_cast( GetDescriptorPool_FromPool(_GetDescriptor(self)->pool())); Py_XINCREF(pool); return pool; } static PyObject* GetName(PyFileDescriptor *self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->name()); } static PyObject* GetPackage(PyFileDescriptor *self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->package()); } static PyObject* GetSerializedPb(PyFileDescriptor *self, void *closure) { PyObject *serialized_pb = self->serialized_pb; if (serialized_pb != NULL) { Py_INCREF(serialized_pb); return serialized_pb; } FileDescriptorProto file_proto; _GetDescriptor(self)->CopyTo(&file_proto); string contents; file_proto.SerializePartialToString(&contents); self->serialized_pb = PyBytes_FromStringAndSize( contents.c_str(), contents.size()); if (self->serialized_pb == NULL) { return NULL; } Py_INCREF(self->serialized_pb); return self->serialized_pb; } static PyObject* GetMessageTypesByName(PyFileDescriptor* self, void *closure) { return NewFileMessageTypesByName(_GetDescriptor(self)); } static PyObject* GetEnumTypesByName(PyFileDescriptor* self, void *closure) { return NewFileEnumTypesByName(_GetDescriptor(self)); } static PyObject* GetExtensionsByName(PyFileDescriptor* self, void *closure) { return NewFileExtensionsByName(_GetDescriptor(self)); } static PyObject* GetServicesByName(PyFileDescriptor* self, void *closure) { return NewFileServicesByName(_GetDescriptor(self)); } static PyObject* GetDependencies(PyFileDescriptor* self, void *closure) { return NewFileDependencies(_GetDescriptor(self)); } static PyObject* GetPublicDependencies(PyFileDescriptor* self, void *closure) { return NewFilePublicDependencies(_GetDescriptor(self)); } static PyObject* GetHasOptions(PyFileDescriptor *self, void *closure) { const FileOptions& options(_GetDescriptor(self)->options()); if (&options != &FileOptions::default_instance()) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static int SetHasOptions(PyFileDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""has_options""); } static PyObject* GetOptions(PyFileDescriptor *self) { return GetOrBuildOptions(_GetDescriptor(self)); } static int SetOptions(PyFileDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_options""); } static int SetSerializedOptions(PyFileDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_serialized_options""); } static PyObject* GetSyntax(PyFileDescriptor *self, void *closure) { return PyString_InternFromString( FileDescriptor::SyntaxName(_GetDescriptor(self)->syntax())); } static PyObject* CopyToProto(PyFileDescriptor *self, PyObject *target) { return CopyToPythonProto(_GetDescriptor(self), target); } static PyGetSetDef Getters[] = { { ""pool"", (getter)GetPool, NULL, ""pool""}, { ""name"", (getter)GetName, NULL, ""name""}, { ""package"", (getter)GetPackage, NULL, ""package""}, { ""serialized_pb"", (getter)GetSerializedPb}, { ""message_types_by_name"", (getter)GetMessageTypesByName, NULL, ""Messages by name""}, { ""enum_types_by_name"", (getter)GetEnumTypesByName, NULL, ""Enums by name""}, { ""extensions_by_name"", (getter)GetExtensionsByName, NULL, ""Extensions by name""}, { ""services_by_name"", (getter)GetServicesByName, NULL, ""Services by name""}, { ""dependencies"", (getter)GetDependencies, NULL, ""Dependencies""}, { ""public_dependencies"", (getter)GetPublicDependencies, NULL, ""Dependencies""}, { ""has_options"", (getter)GetHasOptions, (setter)SetHasOptions, ""Has Options""}, { ""_options"", (getter)NULL, (setter)SetOptions, ""Options""}, { ""_serialized_options"", (getter)NULL, (setter)SetSerializedOptions, ""Serialized Options""}, { ""syntax"", (getter)GetSyntax, (setter)NULL, ""Syntax""}, {NULL} }; static PyMethodDef Methods[] = { { ""GetOptions"", (PyCFunction)GetOptions, METH_NOARGS, }, { ""CopyToProto"", (PyCFunction)CopyToProto, METH_O, }, {NULL} }; } // namespace file_descriptor PyTypeObject PyFileDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".FileDescriptor"", // tp_name sizeof(PyFileDescriptor), // tp_basicsize 0, // tp_itemsize (destructor)file_descriptor::Dealloc, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""A File Descriptor"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext file_descriptor::Methods, // tp_methods 0, // tp_members file_descriptor::Getters, // tp_getset &descriptor::PyBaseDescriptor_Type, // tp_base 0, // tp_dict 0, // tp_descr_get 0, // tp_descr_set 0, // tp_dictoffset 0, // tp_init 0, // tp_alloc 0, // tp_new PyObject_Del, // tp_free }; PyObject* PyFileDescriptor_FromDescriptor( const FileDescriptor* file_descriptor) { return PyFileDescriptor_FromDescriptorWithSerializedPb(file_descriptor, NULL); } PyObject* PyFileDescriptor_FromDescriptorWithSerializedPb( const FileDescriptor* file_descriptor, PyObject *serialized_pb) { bool was_created; PyObject* py_descriptor = descriptor::NewInternedDescriptor( &PyFileDescriptor_Type, file_descriptor, &was_created); if (py_descriptor == NULL) { return NULL; } if (was_created) { PyFileDescriptor* cfile_descriptor = reinterpret_cast(py_descriptor); Py_XINCREF(serialized_pb); cfile_descriptor->serialized_pb = serialized_pb; } // TODO(amauryfa): In the case of a cached object, check that serialized_pb // is the same as before. return py_descriptor; } const FileDescriptor* PyFileDescriptor_AsDescriptor(PyObject* obj) { if (!PyObject_TypeCheck(obj, &PyFileDescriptor_Type)) { PyErr_SetString(PyExc_TypeError, ""Not a FileDescriptor""); return NULL; } return reinterpret_cast( reinterpret_cast(obj)->descriptor); } namespace oneof_descriptor { // Unchecked accessor to the C++ pointer. static const OneofDescriptor* _GetDescriptor( PyBaseDescriptor *self) { return reinterpret_cast(self->descriptor); } static PyObject* GetName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->name()); } static PyObject* GetFullName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->full_name()); } static PyObject* GetIndex(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->index()); } static PyObject* GetFields(PyBaseDescriptor* self, void *closure) { return NewOneofFieldsSeq(_GetDescriptor(self)); } static PyObject* GetContainingType(PyBaseDescriptor *self, void *closure) { const Descriptor* containing_type = _GetDescriptor(self)->containing_type(); if (containing_type) { return PyMessageDescriptor_FromDescriptor(containing_type); } else { Py_RETURN_NONE; } } static PyObject* GetHasOptions(PyBaseDescriptor *self, void *closure) { const OneofOptions& options(_GetDescriptor(self)->options()); if (&options != &OneofOptions::default_instance()) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } static int SetHasOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""has_options""); } static PyObject* GetOptions(PyBaseDescriptor *self) { return GetOrBuildOptions(_GetDescriptor(self)); } static int SetOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_options""); } static int SetSerializedOptions(PyBaseDescriptor *self, PyObject *value, void *closure) { return CheckCalledFromGeneratedFile(""_serialized_options""); } static PyGetSetDef Getters[] = { { ""name"", (getter)GetName, NULL, ""Name""}, { ""full_name"", (getter)GetFullName, NULL, ""Full name""}, { ""index"", (getter)GetIndex, NULL, ""Index""}, { ""containing_type"", (getter)GetContainingType, NULL, ""Containing type""}, { ""has_options"", (getter)GetHasOptions, (setter)SetHasOptions, ""Has Options""}, { ""_options"", (getter)NULL, (setter)SetOptions, ""Options""}, { ""_serialized_options"", (getter)NULL, (setter)SetSerializedOptions, ""Serialized Options""}, { ""fields"", (getter)GetFields, NULL, ""Fields""}, {NULL} }; static PyMethodDef Methods[] = { { ""GetOptions"", (PyCFunction)GetOptions, METH_NOARGS }, {NULL} }; } // namespace oneof_descriptor PyTypeObject PyOneofDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".OneofDescriptor"", // tp_name sizeof(PyBaseDescriptor), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""A Oneof Descriptor"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext oneof_descriptor::Methods, // tp_methods 0, // tp_members oneof_descriptor::Getters, // tp_getset &descriptor::PyBaseDescriptor_Type, // tp_base }; PyObject* PyOneofDescriptor_FromDescriptor( const OneofDescriptor* oneof_descriptor) { return descriptor::NewInternedDescriptor( &PyOneofDescriptor_Type, oneof_descriptor, NULL); } namespace service_descriptor { // Unchecked accessor to the C++ pointer. static const ServiceDescriptor* _GetDescriptor( PyBaseDescriptor *self) { return reinterpret_cast(self->descriptor); } static PyObject* GetName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->name()); } static PyObject* GetFullName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->full_name()); } static PyObject* GetFile(PyBaseDescriptor *self, void *closure) { return PyFileDescriptor_FromDescriptor(_GetDescriptor(self)->file()); } static PyObject* GetIndex(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->index()); } static PyObject* GetMethods(PyBaseDescriptor* self, void *closure) { return NewServiceMethodsSeq(_GetDescriptor(self)); } static PyObject* GetMethodsByName(PyBaseDescriptor* self, void *closure) { return NewServiceMethodsByName(_GetDescriptor(self)); } static PyObject* FindMethodByName(PyBaseDescriptor *self, PyObject* arg) { Py_ssize_t name_size; char* name; if (PyString_AsStringAndSize(arg, &name, &name_size) < 0) { return NULL; } const MethodDescriptor* method_descriptor = _GetDescriptor(self)->FindMethodByName(string(name, name_size)); if (method_descriptor == NULL) { PyErr_Format(PyExc_KeyError, ""Couldn't find method %.200s"", name); return NULL; } return PyMethodDescriptor_FromDescriptor(method_descriptor); } static PyObject* GetOptions(PyBaseDescriptor *self) { return GetOrBuildOptions(_GetDescriptor(self)); } static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) { return CopyToPythonProto(_GetDescriptor(self), target); } static PyGetSetDef Getters[] = { { ""name"", (getter)GetName, NULL, ""Name"", NULL}, { ""full_name"", (getter)GetFullName, NULL, ""Full name"", NULL}, { ""file"", (getter)GetFile, NULL, ""File descriptor""}, { ""index"", (getter)GetIndex, NULL, ""Index"", NULL}, { ""methods"", (getter)GetMethods, NULL, ""Methods"", NULL}, { ""methods_by_name"", (getter)GetMethodsByName, NULL, ""Methods by name"", NULL}, {NULL} }; static PyMethodDef Methods[] = { { ""GetOptions"", (PyCFunction)GetOptions, METH_NOARGS }, { ""CopyToProto"", (PyCFunction)CopyToProto, METH_O, }, { ""FindMethodByName"", (PyCFunction)FindMethodByName, METH_O }, {NULL} }; } // namespace service_descriptor PyTypeObject PyServiceDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".ServiceDescriptor"", // tp_name sizeof(PyBaseDescriptor), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""A Service Descriptor"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext service_descriptor::Methods, // tp_methods 0, // tp_members service_descriptor::Getters, // tp_getset &descriptor::PyBaseDescriptor_Type, // tp_base }; PyObject* PyServiceDescriptor_FromDescriptor( const ServiceDescriptor* service_descriptor) { return descriptor::NewInternedDescriptor( &PyServiceDescriptor_Type, service_descriptor, NULL); } const ServiceDescriptor* PyServiceDescriptor_AsDescriptor(PyObject* obj) { if (!PyObject_TypeCheck(obj, &PyServiceDescriptor_Type)) { PyErr_SetString(PyExc_TypeError, ""Not a ServiceDescriptor""); return NULL; } return reinterpret_cast( reinterpret_cast(obj)->descriptor); } namespace method_descriptor { // Unchecked accessor to the C++ pointer. static const MethodDescriptor* _GetDescriptor( PyBaseDescriptor *self) { return reinterpret_cast(self->descriptor); } static PyObject* GetName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->name()); } static PyObject* GetFullName(PyBaseDescriptor* self, void *closure) { return PyString_FromCppString(_GetDescriptor(self)->full_name()); } static PyObject* GetIndex(PyBaseDescriptor *self, void *closure) { return PyInt_FromLong(_GetDescriptor(self)->index()); } static PyObject* GetContainingService(PyBaseDescriptor *self, void *closure) { const ServiceDescriptor* containing_service = _GetDescriptor(self)->service(); return PyServiceDescriptor_FromDescriptor(containing_service); } static PyObject* GetInputType(PyBaseDescriptor *self, void *closure) { const Descriptor* input_type = _GetDescriptor(self)->input_type(); return PyMessageDescriptor_FromDescriptor(input_type); } static PyObject* GetOutputType(PyBaseDescriptor *self, void *closure) { const Descriptor* output_type = _GetDescriptor(self)->output_type(); return PyMessageDescriptor_FromDescriptor(output_type); } static PyObject* GetOptions(PyBaseDescriptor *self) { return GetOrBuildOptions(_GetDescriptor(self)); } static PyObject* CopyToProto(PyBaseDescriptor *self, PyObject *target) { return CopyToPythonProto(_GetDescriptor(self), target); } static PyGetSetDef Getters[] = { { ""name"", (getter)GetName, NULL, ""Name"", NULL}, { ""full_name"", (getter)GetFullName, NULL, ""Full name"", NULL}, { ""index"", (getter)GetIndex, NULL, ""Index"", NULL}, { ""containing_service"", (getter)GetContainingService, NULL, ""Containing service"", NULL}, { ""input_type"", (getter)GetInputType, NULL, ""Input type"", NULL}, { ""output_type"", (getter)GetOutputType, NULL, ""Output type"", NULL}, {NULL} }; static PyMethodDef Methods[] = { { ""GetOptions"", (PyCFunction)GetOptions, METH_NOARGS, }, { ""CopyToProto"", (PyCFunction)CopyToProto, METH_O, }, {NULL} }; } // namespace method_descriptor PyTypeObject PyMethodDescriptor_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) FULL_MODULE_NAME "".MethodDescriptor"", // tp_name sizeof(PyBaseDescriptor), // tp_basicsize 0, // tp_itemsize 0, // tp_dealloc 0, // tp_print 0, // tp_getattr 0, // tp_setattr 0, // tp_compare 0, // tp_repr 0, // tp_as_number 0, // tp_as_sequence 0, // tp_as_mapping 0, // tp_hash 0, // tp_call 0, // tp_str 0, // tp_getattro 0, // tp_setattro 0, // tp_as_buffer Py_TPFLAGS_DEFAULT, // tp_flags ""A Method Descriptor"", // tp_doc 0, // tp_traverse 0, // tp_clear 0, // tp_richcompare 0, // tp_weaklistoffset 0, // tp_iter 0, // tp_iternext method_descriptor::Methods, // tp_methods 0, // tp_members method_descriptor::Getters, // tp_getset &descriptor::PyBaseDescriptor_Type, // tp_base }; PyObject* PyMethodDescriptor_FromDescriptor( const MethodDescriptor* method_descriptor) { return descriptor::NewInternedDescriptor( &PyMethodDescriptor_Type, method_descriptor, NULL); } const MethodDescriptor* PyMethodDescriptor_AsDescriptor(PyObject* obj) { if (!PyObject_TypeCheck(obj, &PyMethodDescriptor_Type)) { PyErr_SetString(PyExc_TypeError, ""Not a MethodDescriptor""); return NULL; } return reinterpret_cast( reinterpret_cast(obj)->descriptor); } // Add a enum values to a type dictionary. static bool AddEnumValues(PyTypeObject *type, const EnumDescriptor* enum_descriptor) { for (int i = 0; i < enum_descriptor->value_count(); ++i) { const EnumValueDescriptor* value = enum_descriptor->value(i); ScopedPyObjectPtr obj(PyInt_FromLong(value->number())); if (obj == NULL) { return false; } if (PyDict_SetItemString(type->tp_dict, value->name().c_str(), obj.get()) < 0) { return false; } } return true; } static bool AddIntConstant(PyTypeObject *type, const char* name, int value) { ScopedPyObjectPtr obj(PyInt_FromLong(value)); if (PyDict_SetItemString(type->tp_dict, name, obj.get()) < 0) { return false; } return true; } bool InitDescriptor() { if (PyType_Ready(&PyMessageDescriptor_Type) < 0) return false; if (PyType_Ready(&PyFieldDescriptor_Type) < 0) return false; if (!AddEnumValues(&PyFieldDescriptor_Type, FieldDescriptorProto::Label_descriptor())) { return false; } if (!AddEnumValues(&PyFieldDescriptor_Type, FieldDescriptorProto::Type_descriptor())) { return false; } #define ADD_FIELDDESC_CONSTANT(NAME) AddIntConstant( \\ &PyFieldDescriptor_Type, #NAME, FieldDescriptor::NAME) if (!ADD_FIELDDESC_CONSTANT(CPPTYPE_INT32) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_INT64) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_UINT32) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_UINT64) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_DOUBLE) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_FLOAT) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_BOOL) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_ENUM) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_STRING) || !ADD_FIELDDESC_CONSTANT(CPPTYPE_MESSAGE)) { return false; } #undef ADD_FIELDDESC_CONSTANT if (PyType_Ready(&PyEnumDescriptor_Type) < 0) return false; if (PyType_Ready(&PyEnumValueDescriptor_Type) < 0) return false; if (PyType_Ready(&PyFileDescriptor_Type) < 0) return false; if (PyType_Ready(&PyOneofDescriptor_Type) < 0) return false; if (PyType_Ready(&PyServiceDescriptor_Type) < 0) return false; if (PyType_Ready(&PyMethodDescriptor_Type) < 0) return false; if (!InitDescriptorMappingTypes()) return false; // Initialize globals defined in this file. interned_descriptors = new std::unordered_map; return true; } } // namespace python } // namespace protobuf } // namespace google ",16285,True,3689.8434501914594,median "= v1beta1.Role {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. == 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:
rules:
- apiGroups:
- - [string]:
nonResourceURLs:
- [string]:
resourceNames:
- [string]:
resources:
- [string]:
verbs:
- [string]:
++++ == Operations [[Post-apis-rbac.authorization.k8s.io-v1beta1-namespaces-namespace-roles]] === Create a Role in a namespace Create a Role ==== HTTP request ---- POST /apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""Role"", ""apiVersion"": ""rbac.authorization.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles <<'EOF' { ""kind"": ""Role"", ""apiVersion"": ""rbac.authorization.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.Role |=== ==== 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|v1beta1.Role |201 Created|v1beta1.Role |202 Accepted|v1beta1.Role |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-rbac.authorization.k8s.io-v1beta1-namespaces-namespace-roles-name]] === Get a Role in a namespace Read the specified Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles/$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/apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Role |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|v1beta1.Role |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-rbac.authorization.k8s.io-v1beta1-roles]] === Get all Roles List or watch objects of kind Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1beta1/roles 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/apis/rbac.authorization.k8s.io/v1beta1/roles ---- ==== 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|v1beta1.RoleList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1beta1-namespaces-namespace-roles]] === Get all Roles in a namespace List or watch objects of kind Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles 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/apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles ---- ==== 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|v1beta1.RoleList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1beta1-watch-namespaces-namespace-roles-name]] === Watch a Role in a namespace Watch changes to an object of kind Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1beta1/watch/namespaces/$NAMESPACE/roles/$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/apis/rbac.authorization.k8s.io/v1beta1/watch/namespaces/$NAMESPACE/roles/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Role |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-apis-rbac.authorization.k8s.io-v1beta1-watch-roles]] === Watch all Roles Watch individual changes to a list of Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1beta1/watch/roles 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/apis/rbac.authorization.k8s.io/v1beta1/watch/roles ---- ==== 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-apis-rbac.authorization.k8s.io-v1beta1-watch-namespaces-namespace-roles]] === Watch all Roles in a namespace Watch individual changes to a list of Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1beta1/watch/namespaces/$NAMESPACE/roles 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/apis/rbac.authorization.k8s.io/v1beta1/watch/namespaces/$NAMESPACE/roles ---- ==== 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-apis-rbac.authorization.k8s.io-v1beta1-namespaces-namespace-roles-name]] === Update a Role in a namespace Replace the specified Role ==== HTTP request ---- PUT /apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""Role"", ""apiVersion"": ""rbac.authorization.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles/$NAME <<'EOF' { ""kind"": ""Role"", ""apiVersion"": ""rbac.authorization.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.Role |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Role |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|v1beta1.Role |201 Created|v1beta1.Role |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-rbac.authorization.k8s.io-v1beta1-namespaces-namespace-roles-name]] === Patch a Role in a namespace Partially update the specified Role ==== HTTP request ---- PATCH /apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles/$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/apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles/$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 Role |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|v1beta1.Role |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-apis-rbac.authorization.k8s.io-v1beta1-namespaces-namespace-roles-name]] === Delete a Role in a namespace Delete a Role ==== HTTP request ---- DELETE /apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles/$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/apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles/$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 Role |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-apis-rbac.authorization.k8s.io-v1beta1-namespaces-namespace-roles]] === Delete all Roles in a namespace Delete collection of Role ==== HTTP request ---- DELETE /apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles 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/apis/rbac.authorization.k8s.io/v1beta1/namespaces/$NAMESPACE/roles ---- ==== 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 ",12319,False,2388.576253185273,median "#include ""sprites.h"" #include using namespace std; namespace cello { bool Sprite::drawLines = false; // Some time put this in the renderer, perhaps. Renderer* Mesh::renderer = NULL; Mat4Property::Mat4Property() {} Mat4Property::Mat4Property(const Mat4& v) : Mat4(v) {} std::string Mat4Property::serialize(std::string indent) const { VectorProperty v; const double* p = ptr(); for( int i = 0; i < 16; i++ ) v.push_back(p[i]); return flattenWhitespace(v.serialize(indent).c_str()); } void Mat4Property::initWithParseNode(const parse::Node* n) { VectorProperty v; v.initWithParseNode(n); double* ptr = (double*)(&m00); int size = v.size(); for( int i = 0; i < 16; i++ ) if( size > 0 ) ptr[i] = v[i](); } Vec2Property::Vec2Property() {} Vec2Property::Vec2Property(const Vec2& v) : Vec2(v) {} std::string Vec2Property::serialize(std::string indent) const { VectorProperty v; v.push_back(x); v.push_back(y); return flattenWhitespace(v.serialize(indent).c_str()); } void Vec2Property::initWithParseNode(const parse::Node* n) { VectorProperty v; v.initWithParseNode(n); if( v.size() > 0 ) x = v[0](); if( v.size() > 1 ) y = v[1](); } Vec3Property::Vec3Property() {} Vec3Property::Vec3Property(const Vec3& v) : Vec3(v) {} std::string Vec3Property::serialize(std::string indent) const { VectorProperty v; v.push_back(x); v.push_back(y); v.push_back(z); return flattenWhitespace(v.serialize(indent).c_str()); } void Vec3Property::initWithParseNode(const parse::Node* n) { VectorProperty v; v.initWithParseNode(n); if( v.size() > 0 ) x = v[0](); if( v.size() > 1 ) y = v[1](); if( v.size() > 2 ) z = v[2](); } ColorProperty::ColorProperty() {} ColorProperty::ColorProperty(const Color& c) : Color(c) {} std::string ColorProperty::serialize(std::string indent) const { VectorProperty v; v.push_back(r); v.push_back(g); v.push_back(b); v.push_back(a); return flattenWhitespace(v.serialize(indent).c_str()); } void ColorProperty::initWithParseNode(const parse::Node* n) { VectorProperty v; v.initWithParseNode(n); if( v.size() > 0 ) r = v[0](); if( v.size() > 1 ) g = v[1](); if( v.size() > 2 ) b = v[2](); if( v.size() > 3 ) a = v[3](); } Sampler::Sampler() { type = ""Sampler""; addProperty(""file"", file); } Sampler::~Sampler() { } Mat4 Sampler::getOffsetMatrix(int frame, double x, double y, double k) const { double w = getWidth(frame), h = getHeight(frame); Vec2 offset(x, y); if( getCenter(frame) ) offset -= 0.5 * k * Vec2(w, h); return Mat4( k*w, 0.0, 0.0, 0.0, 0.0, k*h, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, offset.x, offset.y, 0.0, 1.0); } Rectangle::Rectangle() : x0(0.0) , y0(0.0) , x1(1.0) , y1(1.0) { } Rectangle::Rectangle(double x0, double y0, double x1, double y1) : x0(x0) , y0(y0) , x1(x1) , y1(y1) { } Rectangle::~Rectangle() { } std::string Rectangle::serialize(std::string indent) const { VectorProperty v; v.push_back(x0); v.push_back(y0); v.push_back(x1); v.push_back(y1); return flattenWhitespace(v.serialize(indent).c_str()); } void Rectangle::initWithParseNode(const parse::Node* n) { VectorProperty v; v.initWithParseNode(n); if( v.size() > 0 ) x0 = v[0](); if( v.size() > 1 ) y0 = v[1](); if( v.size() > 2 ) x1 = v[2](); if( v.size() > 3 ) y1 = v[3](); } Sprite::Sprite() : numberOfRows(1) , numberOfColumns(1) , center(false) , flipRows(false) { type = ""Sprite""; addProperty(""numberOfRows"", numberOfRows); addProperty(""numberOfColumns"", numberOfColumns); addProperty(""center"", center); addProperty(""flipRows"", flipRows); addProperty(""polygon"", polygon); } Sprite::~Sprite() { } Mat3 Sprite::getTexMatrix(int frame) const { int c = numberOfColumns(); int r = numberOfRows(); double i = (frame % c + c) % c, j = ((frame / c) % r + r) % r; if( flipRows() ) j = numberOfRows() - j - 1; return Mat3( 1.0 / c, 0.0 , 0.0, 0.0, 1.0 / r, 0.0, i / c, j / r, 1.0); } double Sprite::getWidth(int frame) const { return width / numberOfColumns(); } double Sprite::getHeight(int frame) const { return height / numberOfRows(); } bool Sprite::getCenter(int frame) const { return center; } Polygon Sprite::getCollisionPolygon(int frame) const { return polygon; } void Sprite::handleChild(const parse::Node* n) { string n_name = n->data.s; // parse::Node* value = n->data.value; Serializable::handleChild(n); } string Sprite::serializeElements(string indent) const { string r = Serializable::serializeElements(indent); return r; } Atlas::Atlas() { type = ""Atlas""; addProperty(""rectangles"", rectangles); } Atlas::~Atlas() { } Mat3 Atlas::getTexMatrix(int frame) const { int n = rectangles.size(); if( n == 0 ) { celloerror(""Atlas used with no rectangles. Returning idenitity matrix.""); return Mat3(); } frame = ( ( frame % n ) + n ) % n; const Rectangle& rectangle( rectangles[frame] ); // Matrix that transforms the unit square to the rectangle // in texture [0,0,1,1] coordinates. Mat3 result( (rectangle.x1 - rectangle.x0) / width, 0.0, 0.0, 0.0, (rectangle.y1 - rectangle.y0) / height, 0.0, rectangle.x0 / width, rectangle.y0 / height, 1.0); return result; } double Atlas::getWidth(int frame) const { int n = rectangles.size(); if( n == 0 ) { celloerror(""Atlas used with no rectangles. Returning width 10.""); return 10.0; } frame = ( ( frame % n ) + n ) % n; const Rectangle& rectangle( rectangles[frame] ); return fabs(rectangle.x1 - rectangle.x0); } double Atlas::getHeight(int frame) const { int n = rectangles.size(); if( n == 0 ) { celloerror(""Atlas used with no rectangles. Returning height 10.""); return 10.0; } frame = ( ( frame % n ) + n ) % n; const Rectangle& rectangle( rectangles[frame] ); return fabs(rectangle.y1 - rectangle.y0); } bool Atlas::getCenter(int frame) const { return center; } Polygon Atlas::getCollisionPolygon(int frame) const { int n = rectangles.size(); if( n == 0 ) { celloerror(""Atlas used with no rectangles. Returning width empty polygon.""); return Polygon(); } frame = ( ( frame % n ) + n ) % n; return polygons[frame]; } Font::Font() : widths(128), lineHeight(32.0), lineBottom(16.0), widthScale(1.0), spacing(0.0), baseChar(' ') { type = ""Font""; for(int i = 0; i < 128; i++) widths[i] = 32.0; } double Font::charWidth(char c) const { int index = c-baseChar; int n = widths.size(); if( index < 0 || index >= n ) { celloerror( ""charWidth: Attempt to access off "" ""the edge of widths array: %d\\n"", c ); exit(0); } return widthScale * (widths[index] + spacing); } double Font::charLeft(char c) const { int index = c-baseChar; int n = lefts.size(); if( index < 0 || index >= n ) return 0.0; return widthScale * lefts[index]; } double Font::lineWidth(double k, const char* s, int startIndex) const { double width = 0; char c = 0; for(int i = startIndex; (c=s[i]); i++) { if( c == '\\n' || c == '\\r' ) break; width += charWidth(c); } return k * width; } vector > Font::lineIndices(const char* s) const { vector > v; int first = 0; int i=0; char c=0; for(; (c=s[i]); i++) { if( c == '\\n' || c == '\\r' ) { v.push_back(pair(first, i)); first = i+1; } } // If there's just a newline character with nothing else // act like there isn't a last line. if(first != i) v.push_back(pair(first, i)); return v; } void Font::drawString(const Mat4& M, const Color& color, double x, double y, double k, const char* s, const string& justification) const { double startX = x; vector > v = lineIndices(s); for(vector >::const_iterator itr = v.begin(); itr!=v.end(); itr++) { double w = lineWidth(k, s, itr->first); x = startX; if( justification == ""right"" ) x -= w; if( justification == ""center"" ) x -= 0.5 * w; for(int i=itr->first; isecond; i++) { char c = s[i]; double l = k * charLeft(c); Mat4 matrix(M * getOffsetMatrix(c-baseChar, x-l, y, k)); Mat3 texMatrix(getTexMatrix(c-baseChar)); Mesh::renderer->drawMesh(NULL, matrix, texMatrix, color, this); x += k * charWidth(c); } y -= k * lineHeight; } } Polygon Font::stringRectangle(double k, const char* s, const string& justification) const { double left = 0.0, right = 0.0, bottom = 0.0, top = k * (lineHeight + lineBottom); vector > v = lineIndices(s); bool firstline = true; for(vector >::const_iterator itr = v.begin(); itr!=v.end(); itr++) { double w = lineWidth(k, s, itr->first); double x = 0; if( justification == ""right"" ) x -= w; if( justification == ""center"" ) x -= 0.5 * w; left = min(left, x); right = max(right, x+w); if( !firstline ) bottom -= k * lineHeight; firstline = false; } Polygon R; R.add(left, bottom).add(right, bottom).add(right, top).add(left, top); R.setDrawType(Polygon::kOutline); return R; } void Font::getWidthsFromBitmap(const Bitmap& bitmap) { const uint8_t* data = bitmap.getData(); double width = bitmap.getWidth(); double height = bitmap.getHeight(); int bitsPerPixel = bitmap.getBitsPerPixel(); double w = 1.0 * width / numberOfColumns; double h = 1.0 * height / numberOfRows; if( bitsPerPixel != 32 ) { cellolog(""Attempt to generate widths, not from 32 bit data.""); return; } widths.clear(); lefts.clear(); double threshold = 255.0; if( numberOfRows == 1 && numberOfColumns == 1 ) { cellolog(""Attempt to generate widths with"" "" numberOfRows = numberOfColumns = 1.\\n""); } vector sums((int)(w+1)); for( int j = 0; j < numberOfRows; j++ ) for( int i = 0; i < numberOfColumns; i++ ) { int x0 = min((int)((i)*w), width); int x1 = min((int)((i+1)*w), width); int y0 = min((int)(j*h), height); int y1 = min((int)((j+1)*h), height); /* iterate through find the first column the sum of whose alpha is greater than threshold and the last that is less */ for( int x = x0; x < x1; x++ ) { double sum = 0; for( int y = y0; y < y1; y++ ) { int index = (bitsPerPixel / 8) * (width * y + x); uint8_t a = data[index + 3]; sum += 1.0 * a; } sums[x-x0] = sum; } double right = w / 2; double left = 0; for( int x = x0; x < x1; x++ ) { if(sums[x-x0] > threshold) { left = x-x0; break; } } for( int x = x1-1; x >= x0; x-- ) { if(sums[x-x0] > threshold) { right = x-x0; break; } } widths.push_back(right - left); lefts.push_back(left); } spacing = 3; } string Font::serializeElements(string indent) const { string r = Sprite::serializeElements(indent); r += TAB + indent + ""\\""lineHeight\\"" : "" + floatToString(lineHeight) + "",\\n""; r += TAB + indent + ""\\""lineBottom\\"" : "" + floatToString(lineBottom) + "",\\n""; if( widthScale!=1.0 ) r += TAB + indent + ""\\""widthScale\\"" : "" + floatToString(widthScale) + "",\\n""; if( spacing ) r += TAB + indent + ""\\""spacing\\"" : "" + floatToString(spacing) + "",\\n""; string s; int n = 0; n = widths.size(); s = ""[""; for(int i = 0; i < n; i++) { if( i % numberOfColumns() == 0 ) s += ""\\n"" + TAB + TAB + TAB + indent; s += floatToString(widths[i]); if( i!=n-1 ) s += "", ""; } s += ""\\n"" + TAB + TAB + indent + ""]""; r += TAB + indent + ""\\""widths\\"" : "" + s + string("",\\n""); n = lefts.size(); s = ""[""; for(int i = 0; i < n; i++) { if( i % numberOfColumns() == 0 ) s += ""\\n"" + TAB + TAB + TAB + indent; s += floatToString(lefts[i]); if( i!=n-1 ) s += "", ""; } s += ""\\n"" + TAB + TAB + indent + ""]""; r += TAB + indent + ""\\""lefts\\"" : "" + s + string("",\\n""); if(baseChar!=' ') { char c[2] = {baseChar, 0}; r += TAB + indent + ""\\""baseChar\\"" : \\"""" + string(c) + ""\\"",\\n""; } return r; } void Font::handleChild(const parse::Node* n) { Sprite::handleChild(n); string n_name = n->data.s; parse::Node* value = n->data.value; if(n_name == ""widths"") { widths.clear(); for(vector::const_iterator itr = value->children.begin(); itr!=value->children.end(); itr++) { widths.push_back((*itr)->data.x); } } if(n_name == ""lefts"") { lefts.clear(); for(vector::const_iterator itr = value->children.begin(); itr!=value->children.end(); itr++) { lefts.push_back((*itr)->data.x); } } if(n_name == ""lineHeight"") { lineHeight = value->data.x; } if(n_name == ""lineBottom"") { lineBottom = value->data.x; } if(n_name == ""widthScale"") { widthScale = value->data.x; } if(n_name == ""spacing"") { spacing = value->data.x; } if(n_name == ""baseChar"") { baseChar = value->data.s[0]; } } Node::Node() : visible(true), parent(NULL), tookMouseDown(false) { type = ""Node""; addProperty(""visible"", visible); addProperty(""children"", children); } Node::~Node() { for(vector::iterator itr = children.begin(); itr!=children.end(); itr++) delete *itr; } void Node::add(Node* t) { children.push_back(t); t->parent = this; } void Node::addAtIndex(Node* t, int index) { assert(t); int n = children.size(); if(index < 0) index = 0; if(index > n) index = n; children.resize(n+1); int i = n; for(;i>index; i--) children[i] = children[i-1]; children[i] = t; t->parent = this; } int Node::indexOf(const Node* t) const { int n = children.size(); for(int i = 0; i < n; i++) if( children[i]==t ) return i; return -1; } void Node::remove(Node* t) { int n = children.size(); int j = 0; for(int i = 0; i < n; i++) { if(children[i] != t) { children[j] = children[i]; j++; } } children.resize(j); t->parent = NULL; } void Node::clear() { children.clear(); } void Node::removeAndDelete(Node* t) { remove(t); delete t; } void Node::removeSampler(const Sampler* sampler) { for(vector::const_iterator itr = children.begin(); itr!=children.end(); itr++) (*itr)->removeSampler(sampler); } Node* Node::findChild(const string& name) const { for(vector::const_iterator itr = children.begin(); itr!=children.end(); itr++) { if( (*itr)->name == name ) return *itr; } cellolog( ""WARNING: child %s of node %s not found.\\n"", name.c_str(), this->name.c_str() ); return NULL; } void Node::draw() const { if( visible() ) { drawInTree(getState()); } } void Node::drawInTree(const NodeState& cumulativeState) const { for(vector::const_iterator itr = children.begin(); itr!=children.end(); itr++) { Node* node = *itr; if( node->visible() ) { NodeState newState = cumulativeState * node->getState(); newState.makeCurrent(); node->drawInTree(newState); } } } void Node::handleChild(const parse::Node* n) { const parse::Node* value = n->data.value; string n_name = n->data.s; if( n_name == ""children"" ) { for(vector::const_iterator itr = value->children.begin(); itr!=value->children.end(); itr++) { string type = getType(*itr); Node* newNode = NULL; if(type==""Node"" || type=="""") newNode = new Node(); else if(type == ""World"") newNode = new World(); else if(type == ""Layer"") newNode = new Layer(); else if(type == ""Actor"") newNode = new Actor(); else if(type == ""Button"") newNode = new Button(); else if(type == ""String"" || type == ""Text"") // String is deprecated. newNode = new Text(); else if(type == ""Integer"") newNode = new Integer(); else if(type == ""Polygon"") newNode = new Polygon(); if(newNode) { newNode->initWithParseNode(*itr); add(newNode); deleteMe.push_back(newNode); } } } else Serializable::handleChild(n); } void Node::clearChildren() { for( vector::iterator itr = children.begin(); itr != children.end(); itr++ ) { (*itr)->clearChildren(); } children.clear(); for( vector::iterator itr = deleteMe.begin(); itr!=deleteMe.end(); itr++) { delete *itr; } deleteMe.clear(); } bool Node::vectorInside(const Mat4& /*worldMatrix*/, const Vec2& /*V*/) const { return true; } void Node::keyboard(unsigned char inkey) { if( delegate ) delegate->keyboard(inkey); else { for(vector::reverse_iterator itr = children.rbegin(); itr!=children.rend(); itr++) { Node* node = *itr; if( node->listening ) { (*itr)->keyboard(inkey); } } } } bool Node::mouseDown(const Vec2& C) { return mouseDown(getMatrix(), C); } bool Node::mouseDown(const Mat4& worldMatrix, const Vec2& C) { if( !visible() ) return false; if( delegate && vectorInside(worldMatrix, C) ) { Vec4 v = worldMatrix.inverse() * Vec4(C.x, C.y, 0.0, 1.0); v /= v.w; bool result = delegate->mouseDown(Vec2(v.x, v.y)); if( result ) tookMouseDown = true; return result; } else { for(vector::reverse_iterator itr = children.rbegin(); itr!=children.rend(); itr++) { Node* node = *itr; if(node->listening) { if( node->mouseDown(worldMatrix * node->getMatrix(), C) ) { tookMouseDown = true; return true; } } } return false; } } void Node::mouseDragged(const Vec2& C) { mouseDragged(getMatrix(), C); } void Node::mouseDragged(const Mat4& worldMatrix, const Vec2& C) { if(!tookMouseDown) return; if( delegate ) { Vec4 v = worldMatrix.inverse()*Vec4(C.x, C.y, 0, 1); v /= v.w; delegate->mouseDragged(Vec2(v.x, v.y)); } else { for(vector::reverse_iterator itr = children.rbegin(); itr!=children.rend(); itr++) { Node* node = *itr; if(node->listening) node->mouseDragged(worldMatrix * node->getMatrix(), C); } } } void Node::mouseUp(const Vec2& C) { // Default behavior same as mouseDragged. mouseDragged(C); } void Node::mouseUp(const Mat4& worldMatrix, const Vec2& C) { if(!tookMouseDown) return; if( delegate ) { Vec4 v = worldMatrix.inverse()*Vec4(C.x, C.y, 0, 1); v /= v.w; delegate->mouseUp(Vec2(v.x, v.y)); } else { for(vector::reverse_iterator itr = children.rbegin(); itr!=children.rend(); itr++) { Node* node = *itr; if(node->listening) { (*itr)->mouseUp(worldMatrix * node->getMatrix(), C); } } } } Mat4 Node::getMatrix() const { return Mat4(); } Color Node::getColor() const { return color; } NodeState Node::getState() const { return NodeState(getMatrix(), getColor()); } Mat4 Node::getWorldMatrix() const { if(parent) return parent->getWorldMatrix() * getMatrix(); return Mat4(); } Color Node::getWorldColor() const { if(parent) return parent->getWorldColor() * getColor(); return Color(1.0, 1.0, 1.0, 1.0); } Actor* Node::actorInClick(const Mat4& worldMatrix, const Vec2& C) { if(!visible()) return NULL; for(vector::reverse_iterator itr = children.rbegin(); itr!=children.rend(); itr++) { Actor* n = (*itr)->actorInClick(worldMatrix * getMatrix(), C); if( n ) return n; } return NULL; } void Node::clearTookMouseDown() { tookMouseDown = false; for(vector::iterator itr = children.begin(); itr!=children.end(); itr++) (*itr)->clearTookMouseDown(); } Mesh::Mesh() : elementType(kTriangles) { } Mesh::~Mesh() { } void Mesh::resize(int inNumberOfVertices, int inNumberOfElements) { int sd = 3; if( elementType == kLines ) sd = 2; positions.resize(inNumberOfVertices * 3); indices.resize(inNumberOfElements * sd); } int Mesh::numberOfVertices() const { return positions.size() / 3; } int Mesh::numberOfElements() const { int sd = 3; if( elementType == kLines ) sd = 2; return indices.size() / sd; } Renderer::Renderer() { quad = new Mesh; quad->elementType = Mesh::kTriangles; const float temp_positions[] = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0 }; const unsigned short temp_indices[] = { 0, 1, 2, 0, 2, 3 }; for(int i = 0; i < sizeof(temp_positions)/sizeof(float); i++) quad->positions.push_back(temp_positions[i]); for(int i = 0; i < sizeof(temp_indices)/sizeof(unsigned short); i++) quad->indices.push_back(temp_indices[i]); } Renderer::~Renderer() { delete quad; } RendererGL2::RendererGL2() : initialized(false) , program(0) , vertexShader(0) , fragmentShader(0) , defaultTexture(NULL) { } RendererGL2::~RendererGL2() { if( program ) glDeleteProgram(program); if( vertexShader ) glDeleteShader(vertexShader); if( fragmentShader ) glDeleteShader(fragmentShader); if( defaultTexture ) delete defaultTexture; } void RendererGL2::init() { glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(float), &(quad->positions[0]), GL_STREAM_DRAW); glGenBuffers(1, &indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned short), &(quad->indices[0]), GL_STREAM_DRAW); glGenBuffers(1, &polygonBuffer); glGenBuffers(1, &polygonIndexBuffer); const char* vertexCode = ""\\n"" "" attribute vec3 position;\\n"" "" uniform mat4 matrix;\\n"" "" uniform mat3 texMatrix;\\n"" "" varying vec2 v_texcoord;\\n"" "" void main() {\\n"" "" vec3 t = texMatrix * vec3(position.xy, 1.0);\\n"" "" v_texcoord = t.xy / t.z;\\n"" "" gl_Position = matrix * vec4(position, 1.0);\\n"" "" }\\n""; const char* fragmentCode = ""\\n"" ""#ifdef GL_ES\\nprecision highp float;\\n#endif\\n"" "" uniform vec4 color;\\n"" "" uniform sampler2D texture;\\n"" "" varying vec2 v_texcoord;\\n"" "" void main() {\\n"" "" gl_FragColor = color * texture2D(texture, v_texcoord);\\n"" "" }\\n""; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexCode, NULL); glCompileShader(vertexShader); GLint logLength; glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &logLength); if( logLength > 0 ) { GLchar *log = (GLchar *)malloc(logLength); glGetShaderInfoLog(vertexShader, logLength, &logLength, log); cellolog(""Shader compile log:\\n%s"", log); free(log); } GLint status; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); if( status == 0 ) { glDeleteShader(vertexShader); exit(0); } fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentCode, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &logLength); if( logLength > 0 ) { GLchar *log = (GLchar *)malloc(logLength); glGetShaderInfoLog(fragmentShader, logLength, &logLength, log); cellolog(""Shader compile log:\\n%s"", log); free(log); } glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status); if( status == 0 ) { glDeleteShader(fragmentShader); exit(0); } program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &status); if( status == 0 ) { celloerror( ""Shader program did not link.\\n"" ); exit(0); } positionLocation = glGetAttribLocation(program, ""position""); matrixLocation = glGetUniformLocation(program, ""matrix""); colorLocation = glGetUniformLocation(program, ""color""); textureLocation = glGetUniformLocation(program, ""texture""); texMatrixLocation = glGetUniformLocation(program, ""texMatrix""); defaultTexture = new Texture2D; GLubyte data[] = {255, 255, 255, 255}; defaultTexture->initWithImageData(data, 1, 1, 32); initialized = true; } void RendererGL2::drawMesh( const Mesh* mesh, const Mat4& matrix, const Mat3& texMatrix, const Color& color, const Texture* texture) const { if( !initialized ) { celloerror( ""RendererGL2 draw called before initialization.\\n"" ); exit(0); } if( !mesh ) mesh = quad; if( mesh == quad ) { glBindBuffer(GL_ARRAY_BUFFER, buffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer); } else { glBindBuffer(GL_ARRAY_BUFFER, polygonBuffer); glBufferData(GL_ARRAY_BUFFER, mesh->numberOfVertices()*3*sizeof(float), &(mesh->positions[0]), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, polygonIndexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh->numberOfElements()*3*sizeof(unsigned short), &(mesh->indices[0]), GL_STREAM_DRAW); } glUseProgram(program); glEnableVertexAttribArray(positionLocation); glVertexAttribPointer(positionLocation, 3, GL_FLOAT, false, 0, 0); Mat4 M = projection * matrix; for(int i = 0; i < 16; i++) fv[i] = (GLfloat)(M.ptr()[i]); glUniformMatrix4fv(matrixLocation, 1, false, fv); for(int i = 0; i < 9; i++) fv[i] = (GLfloat)(texMatrix.ptr()[i]); glUniformMatrix3fv(texMatrixLocation, 1, false, fv); const GLfloat cf[] = {(GLfloat)color.r, (GLfloat)color.g, (GLfloat)color.b, (GLfloat)color.a}; glUniform4fv(colorLocation, 1, cf); if(!texture) texture = defaultTexture; glActiveTexture(GL_TEXTURE0 + texture->getUnit()); glBindTexture(GL_TEXTURE_2D, texture->getIndex()); glUniform1i(textureLocation, texture->getUnit()); GLuint gltype = GL_TRIANGLES; int dimension = 3; if( mesh->elementType == Mesh::kLines ) { gltype = GL_LINES; dimension = 2; } glDrawElements(gltype, mesh->numberOfElements()*dimension, GL_UNSIGNED_SHORT, 0); glDisableVertexAttribArray(positionLocation); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE0); glUseProgram(0); } Polygon::Polygon() : drawType(kSolid), valid(false), mesh(NULL) { type = ""Polygon""; addProperty(""vertices"", vertices); addProperty(""color"", color); addProperty(""matrix"", matrix); } Polygon::Polygon(const Polygon& P) : drawType(kSolid), valid(false), mesh(NULL) { type = ""Polygon""; this->operator=(P); } Polygon::~Polygon() { if( mesh ) delete mesh; } Mat4 Polygon::getMatrix() const { return matrix; } Polygon& Polygon::operator=(const Polygon& P) { vertices = P.vertices; this->Node::operator=(P); this->mesh = NULL; this->valid = false; return *this; } Polygon& Polygon::add( const Vec2& V ) { vertices.push_back(V); return *this; } Polygon& Polygon::add( double x, double y ) { vertices.push_back(Vec2(x,y)); return *this; } Polygon& Polygon::operator += (const Vec2& V) { for( VectorProperty::iterator itr=vertices.begin(); itr!=vertices.end(); itr++ ) *itr+=V; return *this; } Polygon& Polygon::operator -= (const Vec2& V) { for( VectorProperty::iterator itr=vertices.begin(); itr!=vertices.end(); itr++ ) *itr-=V; return *this; } Polygon& Polygon::operator *= (double k) { for( VectorProperty::iterator itr=vertices.begin(); itr!=vertices.end(); itr++ ) *itr*=k; return *this; } Polygon& Polygon::operator /= (double k) { for( VectorProperty::iterator itr=vertices.begin(); itr!=vertices.end(); itr++ ) *itr/=k; return *this; } Polygon Polygon::operator+ (const Vec2& V) const { return Polygon(*this)+=V; } Polygon Polygon::operator- (const Vec2& V) const { return Polygon(*this)-=V; } Polygon Polygon::operator* (double k) const { return Polygon(*this)*=k; } Polygon Polygon::operator/ (double k) const { return Polygon(*this)/=k; } Polygon operator * (const Mat4& M, const Polygon& P) { Polygon R; R.drawType = P.drawType; int n = P.size(); vector r(n); for( int i = 0; i < n; i++) { Vec4 v = M * Vec4(P.vertices[i], 0.0, 1.0); r[i] = (Vec2(v.x, v.y) / v.w); } R.setVertices(r); return R; } void Polygon::drawInTree(const NodeState& cumulativeState) const { if( size() < 3 ) return; update(); if( Mesh::renderer && mesh ) Mesh::renderer->drawMesh(mesh, cumulativeState.matrix, Mat3(), cumulativeState.color, NULL); else { celloerror( ""Attempt to draw polygon with no renderer.\\n"" ); exit(0); } } vector::size_type Polygon::size() const { return vertices.size(); } bool Polygon::empty() const { return vertices.empty(); } void Polygon::rotate(double theta) { double s = sin(theta), c = cos(theta); for(VectorProperty::iterator itr = vertices.begin(); itr!= vertices.end(); itr++) *itr = Mat2(c, s, -s, c) * (*itr); } double angleAToB(const Vec2& A, const Vec2& B) { double det = B.y*A.x-B.x*A.y; double sgn = 0.0; if(det < 0.0) sgn = -1.0; if(det > 0.0) sgn = 1.0; return sgn * acos(A.dot(B)/(A.mag()*B.mag())); } bool Polygon::vectorInside(const Mat4& worldMatrix, const Vec2& V) const { Vec4 tmp = worldMatrix * Vec4(V.x, V.y, 0.0, 1.0); Vec2 tv = Vec2( tmp.x, tmp.y ) / tmp.w; double theta = 0; int n = size(); for( int i=0; i 1 || theta < -1 ); } void Polygon::update() const { if( valid ) return; if( !mesh ) mesh = new Mesh; int n = size(); switch(drawType) { case kSolid: mesh->elementType = Mesh::kTriangles; mesh->resize(n, max(0, n-2)); break; case kOutline: mesh->elementType = Mesh::kLines; mesh->resize(n, n); break; default: celloerror( ""drawtype unknown: %d\\n"", drawType ); exit(0); break; } int i = 0; for( VectorProperty::const_iterator itr = vertices.begin(); itr!=vertices.end(); itr++ ) { mesh->positions[i++] = (float)(itr->x); mesh->positions[i++] = (float)(itr->y); mesh->positions[i++] = 0.0; } switch( drawType ) { case kSolid: triangulate(); break; case kOutline: for( int i = 0; i < n; i++ ) { mesh->indices[2*i] = (unsigned short)i; mesh->indices[2*i + 1] = (unsigned short)((i+1)%n); } break; default: celloerror( ""drawtype unknown: %d\\n"", drawType ); exit(0); break; } valid = true; } void Polygon::triangulate() const { // This algorithm runs in worst case O(n^3). int n = size(); vector p(n); int i = 0, k = 0; // Cache the indices of the polygon. for( i = 0; i < n; i++ ) p[i] = i; // Iterate through the indices. for( i = 0; i < n && n > 2; i++ ) { // Consider triangle i, i+1, i+2 candidate for being an ear. const Vec2 &a(vertices[p[i]]), &b(vertices[p[(i+1) % n]]), &c(vertices[p[(i+2) % n]]); Mat2 T(b-a, c-a); // If it's going clockwise, it's not an ear. if( T.det() < 0.0 ) continue; // If another point of the polygon is inside, it's not an ear. bool empty = true; for( int j = (i+3)%n; j!=i; j=(j+1)%n ) { Vec2 v = T.inverse() * (vertices[p[j]] - a); if( v.x > 0.0 && v.y > 0.0 && v.y + v.x < 1.0 ) { empty = false; break; } } // If empty is true, at this point, it is an ear, and we remove the // middle point from p, and add the triangle to indices. if( empty ) { mesh->indices[k++] = (unsigned short)(p[i]); mesh->indices[k++] = (unsigned short)(p[(i+1)%n]); mesh->indices[k++] = (unsigned short)(p[(i+2)%n]); for( int j = (i+1)%n; j < n-1; j++ ) p[j] = p[j+1]; i = -1; // Recall i++ happens at the end of the loop-body. n--; } } } vector Polygon::getTriangleIndices() const { vector indices; // This algorithm runs in worst case O(n^3). int n = size(); vector p(n); int i = 0; // Cache the indices of the polygon. for( i = 0; i < n; i++ ) p[i] = i; // Iterate through the indices. for( i = 0; i < n && n > 2; i++ ) { // Consider triangle i, i+1, i+2 candidate for being an ear. const Vec2 &a(vertices[p[i]]), &b(vertices[p[(i+1) % n]]), &c(vertices[p[(i+2) % n]]); Mat2 T(b-a, c-a); // If it's going clockwise, it's not an ear. if( T.det() < 0.0 ) continue; // If another point of the polygon is inside, it's not an ear. bool empty = true; for( int j = (i+3)%n; j!=i; j=(j+1)%n ) { Vec2 v = T.inverse() * (vertices[p[j]] - a); if( v.x > 0.0 && v.y > 0.0 && v.y + v.x < 1.0 ) { empty = false; break; } } // If empty is true, at this point, it is an ear, and we remove the // middle point from p, and add the triangle to indices. if( empty ) { indices.push_back( p[i] ); indices.push_back( p[(i+1)%n] ); indices.push_back( p[(i+2)%n] ); for( int j = (i+1)%n; j < n-1; j++ ) p[j] = p[j+1]; i = -1; // Recall i++ happens at the end of the loop-body. n--; } } return indices; } void Polygon::handleChild(const parse::Node* n) { Node::handleChild(n); const parse::Node* value = n->data.value; string n_name = n->data.s; if(n_name == ""vertices"") { for(vector::const_iterator itr = value->children.begin(); itr!=value->children.end(); itr++) { vertices.push_back(Vec2((*itr)->children[0]->data.x, (*itr)->children[1]->data.x)); } } } string Polygon::serializeElements(string indent) const { string r = Node::serializeElements(indent); return r; } void Polygon::reverse() { vector r; int n = size(); for( int i = 0; i < n; i++ ) r.push_back(vertices[n-i-1]); setVertices(r); } void Polygon::setVertices(const vector& v) { vertices.clear(); for( vector::const_iterator itr = v.begin(); itr != v.end(); itr++ ) { vertices.push_back(*itr); } valid = false; } vector Polygon::getVertices() const { vector r; for(VectorProperty::const_iterator itr = vertices.begin(); itr != vertices.end(); itr++ ) { r.push_back(*itr); } return r; } void Polygon::setDrawType(DrawType inDrawType) { drawType = inDrawType; valid = false; } Polygon::DrawType Polygon::getDrawType() const { return drawType; } Actor::Actor() : sampler(NULL) , mesh(NULL) , sprite(sampler) , x(position.x) , y(position.y) { init(); } Actor::Actor(Sampler* insampler) : mesh(NULL) , sprite(sampler) , x(position.x) , y(position.y) { sampler = insampler; init(); } Actor::~Actor() { } void Actor::init() { frame = 0; k = 1.0; visible = true; listening = true; type = ""Actor""; addProperty(""position"", position); addProperty(""k"", k); addProperty(""rotation"", rotation); addProperty(""frame"", frame); addProperty(""color"", color); addProperty(""samplerName"", samplerName); } Mat4 Actor::getMatrix() const { double c = k*cos(rotation); double s = k*sin(rotation); return Mat4( c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, x, y, 0, 1); } void Actor::removeSampler(const Sampler* s) { if( sampler == s ) sampler = NULL; Node::removeSampler(s); } void Actor::drawInTree(const NodeState& cumulativeState) const { Mat4 matrix(cumulativeState.matrix); Mat3 texMatrix; if( sampler ) { matrix = matrix * sampler->getOffsetMatrix(frame(), 0.0, 0.0, 1.0); texMatrix = sampler->getTexMatrix(frame()); } if( !Mesh::renderer ) { celloerror( ""Attempt to draw Actor with no renderer. Actor: %s\\n"", name.c_str() ); exit(0); } Mesh::renderer->drawMesh(mesh, matrix, texMatrix, cumulativeState.color, sampler); if( Sprite::drawLines ) collisionPolygon().drawInTree(cumulativeState); } static map gActorToSamplerName; static map gTextToFontName; void Actor::handleChild(const parse::Node* n) { Node::handleChild(n); string n_name = n->data.s; parse::Node* value = n->data.value; if(value) { if(n_name == ""samplerName"") gActorToSamplerName[this] = value->data.s; } } Polygon Actor::collisionPolygon() const { Polygon R; if( !polygon.empty() ) { R = k() * polygon + position; } else if( sampler ) { double w = k() * sampler->getWidth(frame), h = k() * sampler->getHeight(frame); Polygon samplerPoly( sampler->getCollisionPolygon(frame) ); if( !samplerPoly.empty() ) { R = k() * samplerPoly + position; if( sampler->getCenter() ) R -= 0.5 * Vec2(w, h); } else { double x0 = position.x, x1 = position.x+w, y0 = position.y, y1 = position.y+h; R.add(x0, y0).add(x1, y0).add(x1, y1).add(x0, y1); if( sampler->getCenter() ) R -= 0.5 * Vec2(w, h); } } R.setDrawType(Polygon::kOutline); return R; } bool Actor::vectorInside(const Mat4& worldMatrix, const Vec2& C) const { return collisionPolygon().vectorInside(worldMatrix, Vec2(C.x, C.y)); } Actor* Actor::actorInClick(const Mat4& worldMatrix, const Vec2& C) { if(!visible()) return NULL; if( vectorInside(worldMatrix * getMatrix(), C) ) return this; return NULL; } Button::Button() : baseFrame(0) , depressed(false) , handler(NULL) , enabled(true) { type = ""Button""; } Button::Button(Sampler* insampler) : Actor(insampler) , baseFrame(0) , depressed(false) , handler(NULL) , enabled(true) { type = ""Button""; frame = 0; } Button::Button(Sampler* insampler, int baseFrame) : Actor(insampler) , baseFrame(baseFrame) , depressed(false) , handler(NULL) , enabled(true) { type = ""Button""; frame = baseFrame; } void Button::drawInTree(const NodeState& cumulativeState) const { if( !sampler ) { celloerror( ""Button %s drawing with null sampler.\\n"", name.c_str() ); exit(0); } Actor::drawInTree(cumulativeState); if( Sprite::drawLines ) collisionPolygon().drawInTree(cumulativeState); } bool Button::mouseDown(const Mat4& worldMatrix, const Vec2& C) { if( !visible() || !enabled ) return false; frame = baseFrame; if( vectorInside(worldMatrix, C) ) { frame = frame() + 1; depressed = true; if( handler ) handler->down(this); return true; } return false; } void Button::mouseDragged(const Mat4& worldMatrix, const Vec2& C) { if( !visible() || !enabled ) return; frame = baseFrame; if( vectorInside(worldMatrix, C) ) { frame = frame() + 1; } else { if( depressed ) { depressed = false; if( handler ) handler->up(this); } } } void Button::mouseUp(const Mat4& worldMatrix, const Vec2& C) { if( !visible() || !enabled ) return; if( vectorInside(worldMatrix, C) ) { if( handler ) handler->click(this); else cellolog( ""WARNING: button %s with no handler.\\n"", name.c_str() ); } if( depressed ) { depressed = false; if( handler ) handler->up(this); } frame = baseFrame; } void Button::handleChild(const parse::Node* n) { Actor::handleChild(n); string n_name = n->data.s; parse::Node* value = n->data.value; if(value) { if(n_name == ""baseFrame"") baseFrame = value->data.i; } } string Button::serializeElements(string indent) const { string r = Actor::serializeElements(indent); if( baseFrame ) r += TAB + indent + ""\\""baseFrame\\"" : "" + intToString(baseFrame) + "",\\n""; return r; } ButtonHandler::ButtonHandler() {} ButtonHandler::~ButtonHandler() {} void ButtonHandler::down(Button* /*button*/) {} void ButtonHandler::up(Button* /*button*/) {} Text::Text() : font(NULL), justification(""left""), drawPipe(false) { type = ""Text""; } Text::Text(Font* infont) : Actor(infont), font(infont), justification(""left""), drawPipe(false) { type = ""Text""; } void Text::drawInTree(const NodeState& cumulativeState) const { if( font ) { string news = s+(drawPipe?""|"":""""); font->drawString( cumulativeState.matrix, cumulativeState.color, position.x, position.y, k(), news.c_str(), justification); if( Sprite::drawLines ) collisionPolygon().drawInTree(cumulativeState); } else { celloerror( ""Attempt to draw string with no font.\\n"" ); celloerror( ""string = %s fontName = %s\\n"", s.c_str(), fontName.c_str() ); exit(0); } } string Text::serializeElements(string indent) const { string r = Actor::serializeElements(indent); if( font ) r += TAB + indent + ""\\""fontName\\"" : "" + string(""\\"""") + font->name + ""\\"",\\n""; if( s != """" ) r += TAB + indent + ""\\""s\\"" : \\"""" + s + ""\\"",\\n""; if( justification != ""left"" ) r += TAB + indent + ""\\""justification\\"" : \\"""" + justification + ""\\"",\\n""; return r; } void Text::handleChild(const parse::Node* n) { Actor::handleChild(n); string n_name = n->data.s; parse::Node* value = n->data.value; if(value) { if( n_name == ""fontName"" ) { fontName = value->data.s; gTextToFontName[this] = value->data.s; } if( n_name == ""s"" ) s = value->data.s; if( n_name == ""justification"" ) justification = value->data.s; } } Polygon Text::collisionPolygon() const { Polygon R; if( !polygon.empty() ) { R = polygon + position; } if( font ) { R = (font->stringRectangle(k, s.c_str(), justification) + position); } else { celloerror( ""Attempt to compute string rectangle with no font.\\n"" ); exit(0); } R.setDrawType(Polygon::kOutline); return R; } void Text::keyboard(unsigned char inkey) { if( delegate ) delegate->keyboard(inkey); } Integer::Integer() : ptr(NULL) { type = ""Integer""; } Integer::Integer(Font* infont, int* inptr) : Text(infont) , ptr(inptr) { type = ""Integer""; } void Integer::drawInTree(const NodeState& cumulativeState) const { if( ptr ) { font->drawString( cumulativeState.matrix, cumulativeState.color, position.x, position.y, k, intToStringWithCommas(*ptr).c_str(), justification); } else Text::drawInTree(cumulativeState); } NodeState::NodeState() { } NodeState::NodeState(const Mat4& matrix, const Vec4& color) : matrix(matrix) , color(color) { } NodeState::~NodeState() { } void NodeState::mergeMode(const NodeState& state) { for( map::const_iterator itr = state.mode.begin(); itr!=state.mode.end(); itr++ ) mode[itr->first] = itr->second; } NodeState NodeState::operator*(const NodeState& state) const { NodeState newState( matrix * state.matrix, color * state.color); newState.mode = mode; newState.mergeMode(state); return newState; } void NodeState::makeCurrent() const { for( map::const_iterator itr = mode.begin(); itr != mode.end(); itr++ ) { if( itr->first == ""alpha"" ) { if( itr->second ) glEnable(GL_ALPHA); else glDisable(GL_ALPHA); } } } Layer::Layer() { type = ""Layer""; addProperty(""matrix"", matrix); addProperty(""color"", color); } Mat4 Layer::getMatrix() const { return matrix; } World::World() : bank(NULL), soundInitted(false) { player = new AudioPlayer(); context = new Context(player); context->makeCurrent(); destroySoundQueue(); type = ""World""; addProperty(""samplers"", samplers); addProperty(""sounds"", sounds); } World::~World() { if( !soundInitted ) delete player; delete context; for(vector::iterator itr = samplers.begin(); itr!=samplers.end(); itr++) delete *itr; for(vector::iterator itr = sounds.begin(); itr!=sounds.end(); itr++) delete *itr; } void World::initSound(AudioPlayer* inAudioPlayer) { if( soundInitted ) { celloerror(""Sound intted for world twice""); exit(0); } // Throw away the stub player/context. delete context; delete player; player = inAudioPlayer; context = new Context(player); context->makeCurrent(); soundInitted = true; // Only allow once. } Actor* World::actorInClick(const Vec2& V) { return Node::actorInClick(getMatrix(), V); } void World::drawInTree(const NodeState& cumulativeState) const { if( !Mesh::renderer ) { celloerror( ""Attempt to draw World with no renderer. World: %s\\n"", name.c_str() ); exit(0); } Node::drawInTree(cumulativeState * NodeState(getMatrix(), getColor())); } void World::resize(int width, int height) { if( !Mesh::renderer ) { celloerror( ""Attempt to resize with no renderer world: %s\\n"", name.c_str() ); exit(0); } Mesh::renderer->projection = Mat4( 2.0 / width, 0.0, 0.0, 0.0, 0.0, 2.0 / height, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -1.0, -1.0, 0.0, 1.0); } void World::addSampler(Sampler* sampler) { samplers.push_back(sampler); } void World::removeSampler(const Sampler* sampler) { int n = samplers.size(); int j = 0; for(int i = 0; i < n; i++) if(samplers[i] != sampler) { samplers[j] = samplers[i]; j++; } samplers.resize(j); Node::removeSampler(sampler); } bool World::mouseDown(const Vec2& C) { clearTookMouseDown(); return Node::mouseDown(getMatrix(), C); } void World::initWithPath(const char* path) { if(bank) bank->initSerializableWithPath(this, path); else { celloerror( ""World initiailzied with no bank.\\n"" ); exit(0); } } void World::initWithParseNode(const parse::Node* n) { gActorToSamplerName.clear(); gTextToFontName.clear(); Node::initWithParseNode(n); updateSamplerMap(); updateSoundMap(); updateNodeMap(); for(map::iterator itr = gActorToSamplerName.begin(); itr != gActorToSamplerName.end(); itr++) { const string& samplerName(itr->second); if( samplerName != """" ) { map::iterator mitr = samplerMap.find(samplerName); if( mitr != samplerMap.end() ) itr->first->sampler = mitr->second; else { celloerror( ""Actor %s requested sampler not found: %s\\n"", itr->first->name.c_str(), samplerName.c_str() ); exit(0); } } } for(map::iterator itr = gTextToFontName.begin(); itr != gTextToFontName.end(); itr++) { const string& fontName(itr->second); if( fontName != """" ) { map::iterator mitr = samplerMap.find(fontName); if( mitr != samplerMap.end() ) itr->first->font = (Font*)(mitr->second); } } } void World::updateSamplerMap() { samplerMap.clear(); for(vector::iterator itr = samplers.begin(); itr!=samplers.end(); itr++) { Sampler* sampler = *itr; samplerMap[sampler->name] = sampler; } } void World::updateSoundMap() { soundMap.clear(); for(vector::iterator itr = sounds.begin(); itr!=sounds.end(); itr++) { Sound* sound = *itr; soundMap[sound->name] = sound; } } void World::updateNodeMap(Node* node) { if( !node ) node = this; nodeMap[node->name] = node; for(vector::iterator itr = node->children.begin(); itr!=node->children.end(); itr++) updateNodeMap(*itr); } void World::handleChild(const parse::Node* n) { string n_name = n->data.s; parse::Node* value = n->data.value; bool handled = false; if( value ) { if( n_name == ""samplers"" ) { for(vector::const_iterator itr = value->children.begin(); itr!=value->children.end(); itr++) { string type = getType(*itr); Sampler* sampler = NULL; if(type==""Sprite"") { sampler = new Sprite(); } else if(type == ""Font"") { sampler = new Font(); } else { celloerror(""Object in sampler list must be type Sprite or Font.\\n""); exit(0); } if( sampler ) { sampler->initWithParseNode(*itr); samplers.push_back(sampler); deleteResources.push_back(sampler); bank->initTextureWithPath(sampler, sampler->file().c_str()); } } handled = true; } if( n_name == ""sounds"" ) { for(vector::const_iterator itr = value->children.begin(); itr!=value->children.end(); itr++) { string type = getType(*itr); Sound* sound = NULL; if(type==""Sound"") sound = new Sound(); else { celloerror(""Object in sound list must be type Sound.\\n""); exit(0); } if( sound ) { sound->initWithParseNode(*itr); sounds.push_back(sound); deleteResources.push_back(sound); bank->initSoundWithPath(sound, sound->file.c_str()); } } handled = true; } } if( !handled ) { Layer::handleChild(n); } } void World::clear() { clearChildren(); samplers.clear(); sounds.clear(); for( vector::iterator itr = deleteResources.begin(); itr != deleteResources.end(); itr++ ) { delete *itr; } deleteResources.clear(); } int gTimes = 0; std::string gLastName; void World::playSound(const std::string& name, double gain) const { if( sources.empty() ) initSoundQueue(); map::const_iterator sound_itr = soundMap.find(name); if( sound_itr!=soundMap.end() ) { Sound* sound = sound_itr->second; for(vector::iterator itr = sources.begin(); itr!=sources.end(); itr++) { Source* source = *itr; if( !source->isPlaying() ) { sound->source = source; sound->play(gain); break; } } } } Sound* World::getSound(const string& name) { map::iterator itr = soundMap.find(name); if( itr != soundMap.end() ) return itr->second; return NULL; } Node* World::getNode(const string& name) { map::iterator itr = nodeMap.find(name); if( itr != nodeMap.end() ) return itr->second; return NULL; } Sampler* World::getSampler(const string& name) { map::iterator itr = samplerMap.find(name); if( itr != samplerMap.end() ) return itr->second; return NULL; } void World::initSoundQueue() const { context->makeCurrent(); sources.resize(8); for(vector::iterator itr = sources.begin(); itr!=sources.end(); itr++) *itr = new Source; } void World::destroySoundQueue() const { for(vector::iterator itr = sources.begin(); itr!=sources.end(); itr++) delete *itr; } Animator::Animator() : eventStoppedCounter(0) { animationsAdded = 0; animationsRemoved = 0; animationsRemovedNotInList = 0; } Animator::~Animator() { } void Animator::add(Animation* a) { animationsAdded++; retain(a); S.insert(a); if(a->stopsEvents) { if( eventStoppedCounter==0 ) { for(vector::iterator itr = listeners.begin(); itr!=listeners.end(); itr++) { (*itr)->listening = false; } } eventStoppedCounter++; } } void Animator::retain(Animation* a) { a->referenceCounter++; } bool Animator::release(Animation* a) { assert(a->referenceCounter > 0); a->referenceCounter--; if( a->referenceCounter <= 0 ) { delete a; return true; } return false; } void Animator::remove(Animation* a) { set::iterator itr = S.find(a); if(itr!=S.end()) { animationsRemoved++; if(a->stopsEvents) { eventStoppedCounter--; if(eventStoppedCounter<=0) { for(vector::iterator itr = listeners.begin(); itr!=listeners.end(); itr++) { (*itr)->listening = true; } } if(eventStoppedCounter < 0) { celloerror( ""Animator event stopped counter dropped below 0.\\n"" ); exit(0); } } S.erase(itr); release(a); } else { animationsRemovedNotInList++; } } class AnimationContainer { public: double t; int i; Animation* a; AnimationContainer(double t, int i, Animation* a) : t(t), i(i), a(a) {} bool operator<(const AnimationContainer& c) const { return t < c.t || (t == c.t && i < c.i); } }; void Animator::step(double t) { set beginMe, advanceMe, endMe; int index = 0; for(set::iterator itr = S.begin(); itr!= S.end(); itr++) { Animation* a = *itr; if(t > a->start) { if(!a->running) beginMe.insert(AnimationContainer(a->start, index, a)); advanceMe.insert(AnimationContainer(a->start, index, a)); } if(!a->forever && t > a->start + a->duration) endMe.insert(AnimationContainer(a->start + a->duration, index, a)); index++; } for(set::iterator itr = beginMe.begin(); itr!= beginMe.end(); itr++) { Animation* a = itr->a; a->begin(); a->running = true; } for(set::iterator itr = advanceMe.begin(); itr!= advanceMe.end(); itr++) { Animation* a = itr->a; a->advance(t); a->last = t; } for(set::iterator itr = endMe.begin(); itr!= endMe.end(); itr++) { Animation* a = itr->a; a->end(); remove(a); } } void Animator::end() { vector endMe; for(set::iterator itr = S.begin(); itr!= S.end(); itr++) { endMe.push_back(*itr); } for(vector::iterator itr = endMe.begin(); itr!= endMe.end(); itr++) { Animation* a = *itr; a->end(); remove(a); } } void Animator::clear() { vector deleteMe; for(set::iterator itr = S.begin(); itr!= S.end(); itr++) { Animation* a = *itr; deleteMe.push_back(a); } for(vector::iterator itr = deleteMe.begin(); itr!= deleteMe.end(); itr++) { Animation* a = *itr; remove(a); } assert(S.size() == 0); } Animation::Animation(double instart) : stopsEvents(false), running(false), forever(true), duration(0.0), referenceCounter(0) { last = start = currentTime() + instart; } Animation::Animation(double instart, double induration) : stopsEvents(false), running(false), forever(false), referenceCounter(0) { last = start = currentTime() + instart; duration = induration; } Animation::~Animation() { } void Animation::advance(double t) { double scaled_t = 0.0; if( duration ) { scaled_t = (t - start) / (duration); if( scaled_t < 0.0 ) scaled_t = 0.0; if( scaled_t > 1.0 ) scaled_t = 1.0; } step(scaled_t); } void Animation::begin() { } void Animation::step(double /*t*/) { } void Animation::end() { } void Animation::print() const { cellolog( ""start: %f duration: %f stopsEvents: %d"", start, duration, stopsEvents ); } void Animation::display() const { print(); cellolog( ""\\n"" ); } } // end namespace ",16129,True,2568.394984292501,median "[[netty-http-component]] = Netty HTTP Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-netty-http/src/main/docs/netty-http-component.adoc :docTitle: Netty HTTP :artifactId: camel-netty-http :description: Netty HTTP server and client using the Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/netty-http.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Netty HTTP component is an extension to xref:netty-component.adoc[Netty] component to facilitiate HTTP transport with xref:netty-component.adoc[Netty]. [NOTE] ==== *Stream* Netty is stream based, which means the input it receives is submitted to Camel as a stream. That means you will only be able to read the content of the stream *once*. If you find a situation where the message body appears to be empty or you need to access the data multiple times (eg: doing multicasting, or redelivery error handling) you should use Stream caching or convert the message body to a `String` which is safe to be re-read multiple times. Notice Netty HTTP reads the entire stream into memory using `io.netty.handler.codec.http.HttpObjectAggregator` to build the entire full http message. But the resulting message is still a stream based message which is readable once. ==== Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-netty-http x.x.x ------------------------------------------------------------ == URI format The URI scheme for a netty component is as follows ------------------------------------------- netty-http:http://0.0.0.0:8080[?options] ------------------------------------------- [NOTE] ==== *Query parameters vs endpoint options* You may be wondering how Camel recognizes URI query parameters and endpoint options. For example you might create endpoint URI as follows: `netty-http:http//example.com?myParam=myValue&compression=true` . In this example `myParam` is the HTTP parameter, while `compression` is the Camel endpoint option. The strategy used by Camel in such situations is to resolve available endpoint options and remove them from the URI. It means that for the discussed example, the HTTP request sent by Netty HTTP producer to the endpoint will look as follows: `http//example.com?myParam=myValue`, because `compression` endpoint option will be resolved and removed from the target URL. Keep also in mind that you cannot specify endpoint options using dynamic headers (like `CamelHttpQuery`). Endpoint options can be specified only at the endpoint URI definition level (like `to` or `from` DSL elements). ==== [IMPORTANT] ==== *A lot more options* This component inherits all the options from xref:netty-component.adoc[Netty], so make sure to look at the xref:netty-component.adoc[Netty] documentation as well. Notice that some options from xref:netty-component.adoc[Netty] is not applicable when using this Netty HTTP component, such as options related to UDP transport. ==== // 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 Netty HTTP component supports 76 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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}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. There are 6 enums and 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. There are 6 enums and 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 | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | 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 | *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 | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *headerFilterStrategy* (advanced) | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers. | | HeaderFilterStrategy | *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 | *nettyHttpBinding* (advanced) | To use a custom org.apache.camel.component.netty.http.NettyHttpBinding for binding to/from Netty and Camel Message API. | | NettyHttpBinding | *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. There are 2 enums and 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 | *securityConfiguration* (security) | Refers to a org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration for configuring secure web resources. | | NettyHttpSecurityConfiguration | *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 == Endpoint Options The Netty HTTP endpoint is configured using URI syntax: ---- netty-http:protocol://host:port/path ---- with the following path and query parameters: === Path Parameters (4 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which is either http, https or proxy - a consumer only option. There are 2 enums and the value can be one of: http, https | | String | *host* | *Required* The local hostname such as localhost, or 0.0.0.0 when being a consumer. The remote HTTP server hostname when using producer. | | String | *port* | The host port number | | int | *path* | Resource path | | String |=== === Query Parameters (80 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *bridgeEndpoint* (common) | If the option is true, the producer will ignore the Exchange.HTTP_URI header, and use the endpoint's URI for request. You may also set the throwExceptionOnFailure to be false to let the producer send all the fault response back. The consumer working in the bridge mode will skip the gzip compression and WWW URL form encoding (by adding the Exchange.SKIP_GZIP_ENCODING and Exchange.SKIP_WWW_FORM_URLENCODED headers to the consumed exchange). | false | boolean | *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 | *matchOnUriPrefix* (consumer) | Whether or not Camel should try to find a target consumer by matching the URI prefix if no exact match is found. | false | boolean | *muteException* (consumer) | If enabled and an Exchange failed processing on the consumer side the response's body won't contain the exception's stack trace. | false | boolean | *send503whenSuspended* (consumer) | Whether to send back HTTP status code 503 when the consumer has been suspended. If the option is false then the Netty Acceptor is unbound when the consumer is suspended, so clients cannot connect anymore. | true | boolean | *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 | *chunkedMaxContentLength* (consumer) | Value in bytes the max content length per chunked frame received on the Netty HTTP server. | 1048576 | int | *compression* (consumer) | Allow using gzip/deflate for compression on the Netty HTTP server if the client supports it from the HTTP headers. | false | boolean | *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. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *httpMethodRestrict* (consumer) | To disable HTTP methods on the Netty HTTP consumer. You can specify multiple separated by comma. | | String | *logWarnOnBadRequest* (consumer) | Whether Netty HTTP server should log a WARN if decoding the HTTP request failed and a HTTP Status 400 (bad request) is returned. | true | boolean | *mapHeaders* (consumer) | If this option is enabled, then during binding from Netty to Camel Message then the headers will be mapped as well (eg added as header to the Camel Message as well). You can turn off this option to disable this. The headers can still be accessed from the org.apache.camel.component.netty.http.NettyHttpMessage message with the method getHttpRequest() that returns the Netty HTTP request io.netty.handler.codec.http.HttpRequest instance. | true | boolean | *maxHeaderSize* (consumer) | The maximum length of all headers. If the sum of the length of each header exceeds this value, a io.netty.handler.codec.TooLongFrameException will be raised. | 8192 | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *nettySharedHttpServer* (consumer) | To use a shared Netty HTTP server. See Netty HTTP Server Example for more details. | | NettySharedHttpServer | *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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}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. There are 6 enums and 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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *traceEnabled* (consumer) | Specifies whether to enable HTTP TRACE for this Netty HTTP consumer. By default TRACE is turned off. | false | boolean | *urlDecodeHeaders* (consumer) | If this option is enabled, then during binding from Netty to Camel Message then the header values will be URL decoded (eg %20 will be a space character. Notice this option is used by the default org.apache.camel.component.netty.http.NettyHttpBinding and therefore if you implement a custom org.apache.camel.component.netty.http.NettyHttpBinding then you would need to decode the headers accordingly to this option. | false | boolean | *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 | *cookieHandler* (producer) | Configure a cookie handler to maintain a HTTP session | | CookieHandler | *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 | *throwExceptionOnFailure* (producer) | Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code. | true | boolean | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *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 | *okStatusCodeRange* (producer) | The status codes which are considered a success response. The values are inclusive. Multiple ranges can be defined, separated by comma, e.g. 200-204,209,301-304. Each range must be a single number or from-to with the dash included. The default range is 200-299 | 200-299 | String | *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 | *useRelativePath* (producer) | Sets whether to use a relative path in HTTP requests. | true | boolean | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | 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 | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *configuration* (advanced) | To use a custom configured NettyHttpConfiguration for configuring this endpoint. | | NettyHttpConfiguration | *disableStreamCache* (advanced) | Determines whether or not the raw input stream from Netty HttpRequest#getContent() or HttpResponset#getContent() is cached or not (Camel will read the stream into a in light-weight memory based Stream caching) cache. By default Camel will cache the Netty input stream to support reading it multiple times to ensure it Camel can retrieve all data from the stream. However you can set this option to true when you for example need to access the raw stream, such as streaming it directly to a file or other persistent store. Mind that if you enable this option, then you cannot read the Netty stream multiple times out of the box, and you would need manually to reset the reader index on the Netty raw stream. Also Netty will auto-close the Netty stream when the Netty HTTP server/HTTP client is done processing, which means that if the asynchronous routing engine is in use then any asynchronous thread that may continue routing the org.apache.camel.Exchange may not be able to read the Netty stream, because Netty has closed it. | false | boolean | *headerFilterStrategy* (advanced) | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers. | | HeaderFilterStrategy | *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 | *nettyHttpBinding* (advanced) | To use a custom org.apache.camel.component.netty.http.NettyHttpBinding for binding to/from Netty and Camel Message API. | | NettyHttpBinding | *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 | false | boolean | *transferException* (advanced) | If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type. On the producer side the exception will be deserialized and thrown as is, instead of the HttpOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk. | 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 | *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 | *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 | *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 | *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 | *securityConfiguration* (security) | Refers to a org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration for configuring secure web resources. | | NettyHttpSecurityConfiguration | *securityOptions* (security) | To configure NettyHttpSecurityConfiguration using key/value pairs from the map | | Map | *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 == Message Headers The following headers can be used on the producer to control the HTTP request. [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Name |Type |Description |`CamelHttpMethod` |`String` |Allow to control what HTTP method to use such as GET, POST, TRACE etc. The type can also be a `io.netty.handler.codec.http.HttpMethod` instance. |`CamelHttpQuery` |`String` |Allows to provide URI query parameters as a `String` value that overrides the endpoint configuration. Separate multiple parameters using the & sign. For example: `foo=bar&beer=yes`. |`CamelHttpPath` |`String` |Allows to provide URI context-path and query parameters as a `String` value that overrides the endpoint configuration. This allows to reuse the same producer for calling same remote http server, but using a dynamic context-path and query parameters. |`Content-Type` |`String` |To set the content-type of the HTTP body. For example: `text/plain; charset=""UTF-8""`. |`CamelHttpResponseCode` |`int` |Allows to set the HTTP Status code to use. By default 200 is used for success, and 500 for failure. |======================================================================= The following headers is provided as meta-data when a route starts from an Netty HTTP endpoint: The description in the table takes offset in a route having: `from(""netty-http:http:0.0.0.0:8080/myapp"")...` [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Name |Type |Description |`CamelHttpMethod` |`String` |The HTTP method used, such as GET, POST, TRACE etc. |`CamelHttpUrl` |`String` |The URL including protocol, host and port, etc: `\\http://0.0.0.0:8080/myapp` |`CamelHttpUri` |`String` |The URI without protocol, host and port, etc: `/myapp` |`CamelHttpQuery` |`String` |Any query parameters, such as `foo=bar&beer=yes` |`CamelHttpRawQuery` |`String` |Any query parameters, such as `foo=bar&beer=yes`. Stored in the raw form, as they arrived to the consumer (i.e. before URL decoding). |`CamelHttpPath` |`String` |Additional context-path. This value is empty if the client called the context-path `/myapp`. If the client calls `/myapp/mystuff`, then this header value is `/mystuff`. In other words its the value after the context-path configured on the route endpoint. |`CamelHttpCharacterEncoding` |`String` |The charset from the content-type header. |`CamelHttpAuthentication` |`String` |If the user was authenticated using HTTP Basic then this header is added with the value `Basic`. |`Content-Type` |`String` |The content type if provided. For example: `text/plain; charset=""UTF-8""`. |======================================================================= == Access to Netty types This component uses the `org.apache.camel.component.netty.http.NettyHttpMessage` as the message implementation on the Exchange. This allows end users to get access to the original Netty request/response instances if needed, as shown below. Mind that the original response may not be accessible at all times. [source,java] ---------------------------------------------------------------------------------------------------------- io.netty.handler.codec.http.HttpRequest request = exchange.getIn(NettyHttpMessage.class).getHttpRequest(); ---------------------------------------------------------------------------------------------------------- == Examples In the route below we use Netty HTTP as a HTTP server, which returns back a hardcoded ""Bye World"" message. [source,java] ----------------------------------------------- from(""netty-http:http://0.0.0.0:8080/foo"") .transform().constant(""Bye World""); ----------------------------------------------- And we can call this HTTP server using Camel also, with the ProducerTemplate as shown below: [source,java] ------------------------------------------------------------------------------------------------------------ String out = template.requestBody(""netty-http:http://0.0.0.0:8080/foo"", ""Hello World"", String.class); System.out.println(out); ------------------------------------------------------------------------------------------------------------ And we get back ""Bye World"" as the output. === How do I let Netty match wildcards By default Netty HTTP will only match on exact uri's. But you can instruct Netty to match prefixes. For example [source,java] ----------------------------------------------------------- from(""netty-http:http://0.0.0.0:8123/foo"").to(""mock:foo""); ----------------------------------------------------------- In the route above Netty HTTP will only match if the uri is an exact match, so it will match if you enter + `\\http://0.0.0.0:8123/foo` but not match if you do `\\http://0.0.0.0:8123/foo/bar`. So if you want to enable wildcard matching you do as follows: [source,java] --------------------------------------------------------------------------------- from(""netty-http:http://0.0.0.0:8123/foo?matchOnUriPrefix=true"").to(""mock:foo""); --------------------------------------------------------------------------------- So now Netty matches any endpoints with starts with `foo`. To match *any* endpoint you can do: [source,java] ----------------------------------------------------------------------------- from(""netty-http:http://0.0.0.0:8123?matchOnUriPrefix=true"").to(""mock:foo""); ----------------------------------------------------------------------------- === Using multiple routes with same port In the same CamelContext you can have multiple routes from Netty HTTP that shares the same port (eg a `io.netty.bootstrap.ServerBootstrap` instance). Doing this requires a number of bootstrap options to be identical in the routes, as the routes will share the same `io.netty.bootstrap.ServerBootstrap` instance. The instance will be configured with the options from the first route created. The options the routes must be identical configured is all the options defined in the `org.apache.camel.component.netty.NettyServerBootstrapConfiguration` configuration class. If you have configured another route with different options, Camel will throw an exception on startup, indicating the options is not identical. To mitigate this ensure all options is identical. Here is an example with two routes that share the same port. *Two routes sharing the same port* [source,java] ----------------------------------------------- from(""netty-http:http://0.0.0.0:{{port}}/foo"") .to(""mock:foo"") .transform().constant(""Bye World""); from(""netty-http:http://0.0.0.0:{{port}}/bar"") .to(""mock:bar"") .transform().constant(""Bye Camel""); ----------------------------------------------- And here is an example of a mis configured 2nd route that do not have identical `org.apache.camel.component.netty.NettyServerBootstrapConfiguration` option as the 1st route. This will cause Camel to fail on startup. *Two routes sharing the same port, but the 2nd route is misconfigured and will fail on starting* [source,java] -------------------------------------------------------------------------------------- from(""netty-http:http://0.0.0.0:{{port}}/foo"") .to(""mock:foo"") .transform().constant(""Bye World""); // we cannot have a 2nd route on same port with SSL enabled, when the 1st route is NOT from(""netty-http:http://0.0.0.0:{{port}}/bar?ssl=true"") .to(""mock:bar"") .transform().constant(""Bye Camel""); -------------------------------------------------------------------------------------- === Reusing same server bootstrap configuration with multiple routes By configuring the common server bootstrap option in an single instance of a `org.apache.camel.component.netty.NettyServerBootstrapConfiguration` type, we can use the `bootstrapConfiguration` option on the Netty HTTP consumers to refer and reuse the same options across all consumers. [source,xml] ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- And in the routes you refer to this option as shown below [source,xml] ---------------------------------------------------------------------------------------------------------- ... ... ... ---------------------------------------------------------------------------------------------------------- === Reusing same server bootstrap configuration with multiple routes across multiple bundles in OSGi container See the Netty HTTP Server Example for more details and example how to do that. === Implementing a reverse proxy Netty HTTP component can act as a reverse proxy, in that case `Exchange.HTTP_SCHEME`, `Exchange.HTTP_HOST` and `Exchange.HTTP_PORT` headers are populated from the absolute URL received on the request line of the HTTP request. Here's an example of a HTTP proxy that simply transforms the response from the origin server to uppercase. [source,java] ------------------------------------------------------------------------------------------ from(""netty-http:proxy://0.0.0.0:8080"") .toD(""netty-http:"" + ""${headers."" + Exchange.HTTP_SCHEME + ""}://"" + ""${headers."" + Exchange.HTTP_HOST + ""}:"" + ""${headers."" + Exchange.HTTP_PORT + ""}"") .process(this::processResponse); void processResponse(final Exchange exchange) { final NettyHttpMessage message = exchange.getIn(NettyHttpMessage.class); final FullHttpResponse response = message.getHttpResponse(); final ByteBuf buf = response.content(); final String string = buf.toString(StandardCharsets.UTF_8); buf.resetWriterIndex(); ByteBufUtil.writeUtf8(buf, string.toUpperCase(Locale.US)); } ------------------------------------------------------------------------------------------ == Using HTTP Basic Authentication The Netty HTTP consumer supports HTTP basic authentication by specifying the security realm name to use, as shown below [source,java] ------------------------------------------------------------------------------------------ ... ------------------------------------------------------------------------------------------ The realm name is mandatory to enable basic authentication. By default the JAAS based authenticator is used, which will use the realm name specified (karaf in the example above) and use the JAAS realm and the JAAS \\{\\{LoginModule}}s of this realm for authentication. End user of Apache Karaf / ServiceMix has a karaf realm out of the box, and hence why the example above would work out of the box in these containers. === Specifying ACL on web resources The `org.apache.camel.component.netty.http.SecurityConstraint` allows to define constrains on web resources. And the `org.apache.camel.component.netty.http.SecurityConstraintMapping` is provided out of the box, allowing to easily define inclusions and exclusions with roles. For example as shown below in the XML DSL, we define the constraint bean: [source,xml] ------------------------------------------------------------------------------------------------- /public/* ------------------------------------------------------------------------------------------------- The constraint above is define so that * access to /* is restricted and any roles is accepted (also if user has no roles) * access to /admin/* requires the admin role * access to /guest/* requires the admin or guest role * access to /public/* is an exclusion which means no authentication is needed, and is therefore public for everyone without logging in To use this constraint we just need to refer to the bean id as shown below: [source,xml] ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ... ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- include::{page-component-version}@camel-spring-boot::page$netty-http-starter.adoc[] ",12325,False,2482.960753975234,median "= DiaManT Custom Module Development Guide :revnumber: 1.1 :revdate: June 03, 2020 :source-highlighter: highlightjs :toc: macro :toclevels: 5 :sectanchors: true :sectnums: :sectnumlevels: 5 :includedir: ../../styles :title-page: :productname: DiaManT :productversion: 9.5.x - 9.12 :experimental: :classification: CONFIDENTIAL :icons: font :data-uri: :imagesdir: toc::[] <<< ifdef::backend-pdf[] :numbered!: == Document revision [options=""header""] |=== | Version | Date | Notes | 1.0 | May 2020 | Initial version | 1.1 | June 2020 | Editorial updates |=== <<< include::{includedir}/preface.adoc[] <<< endif::[] <<< :numbered: == Introduction === About this guide The purpose of this document is to introduce the reader to the DiaManT API. Eventually, the reader should be able to create their own implementation for a DiaManT application’s back-end. This implementation is also known as the *Custom Module* and is required in most applications that do more than simple call routing. In chapter <> the CustomModule Archetype is presented - a structured way to get you started with an Omilia back-end implementation. === Introduction to Custom Module The typical architecture of an Application is shown in the next figure: .Custom Module architecture image::images/diam_cust_mod_3.png[Custom Module architecture] A Custom Module is actually the back-end of the Application. The Custom Module (DiaManT API implementation) is responsible for implementing the necessary back-end logic and aims to serve the Front-end’s needs. Its tasks include but are not limited to the following: * Integrate with the back-end Systems. * Implement Complex Business Logic. * Create Dynamic Announcements (Realizers). * Prepare and supply other systems with call Data (CTI Data Handling). * Perform N-Best Validation on user input. === Definitions, Abbreviations, and Acronyms Before we get into the coding details, let’s introduce a few concepts : [horizontal] DiaManT:: Dialog Management Technology. The dialog manager is responsible for delivering a human-like interaction. It handles the conversation with the user by evaluating the dialog context and deciding what the next appropriate action is. Application:: A DiaManT application. The reader should be familiar with a DiaManT application’s structure and configuration before continuing on with this document. Dialog:: An incoming call to the Application. Custom Module:: An implementation of the DiaManT API. Also used as a way to describe the final package (_.jar_) that will contain this implementation. App Config:: Every Application contains a configuration file that is called _DiaManT_App_Config.xml_. This file dictates rules about the dialog flow and communicates with the Custom Module via DiaManT in order to: * Perform back-end actions (for example, call web services). * Validate caller Input. * Create complex announcements Custom Config:: Optionally, an Application can include a configuration file that is to be paired with the Custom Module. The filename is DiaManT_Custom_Config.xml. Realizers:: An optional part of the Custom Module. A FieldRealizer or Realizer is a Java Class that performs Natural Language Generation, i.e. binding prompts dynamically in order to create an announcement that will be voiced to the caller. Methods:: In this document, Java methods are going to be referred to as methods. Each word that is followed by parentheses () in this document refers to a Java method. This same notation is going to be used for methods both with and without parameters. == Application and dialog lifecycle During the application’s lifetime there are callback invocations in a specific order. There are two types of callbacks: * Platform callbacks: `onApplicationStart()`, `onApplicationClose()`, `getCopy()`, `onDialogStart()`, `onDialogClose()`, `getTransferData()`. * Application callbacks: `applyCustomAction()`, `applyInference()`, `nBestValidate()`. All these methods belong to `CustomModuleAdaptor` class which is the class that a Custom Module must extend in order to work within an Application. Below is a brief description of the most important class’s methods. === onApplicationStart() Called once when the application starts. [source,java] ---- public boolean onApplicationStart(Map properties) ---- This method is overloaded by having an instance of Application as an additional parameter. [source,java] ---- public boolean onApplicationStart(Map properties, Application app) ---- It is recommended that all resources shared among Dialogs are initialized here. The `properties` parameter is a map that stores automatically-parsed properties from the _DiaManT_Custom_Config.xml_. In order for these properties to be automatically parsed, the Custom Config should look like this: [source,xml] ---- ---- .Example **** [source,java] ---- @Override public boolean onApplicationStart(Map properties) { GenericLogger logger = DialogManager.getInstance().getLogger(); logger.log(""Application is starting. Parsing properties from file.""); prop1 = (String) properties.get(""property1""); prop2 = (String) properties.get(""property2""); return true; } ---- **** === onApplicationClose() A callback to when the Application is about to stop. Any cleanup functions should be performed here. .Example **** [source,java] ---- public boolean onApplicationClose() { // cleanupFunction(); return true; } ---- **** === getCopy() A callback for each new Dialog, in order to initialize the Custom Module. This method will create a new instance of custom module for each call. For instance, assuming that five people call the telephone center of a company that uses Omilia’s technology. The `getCopy()` method will be called 5 times, one per each call. One instance of custom module will be created per caller in order to handle each caller’s dialog needs. This method ensures that the API user can create their own constructor with their own arguments as needed. .Example **** [source,java] ---- @Override public DataPooler getCopy() { return new CustomerNameModule(); } ---- **** === onDialogStart() Called every time a new dialog is started. [source,java] ---- boolean onDialogStart(FieldsContainer fieldsContainer) ---- Any resource in the scope of a single dialog should be initialized here. From here on the consumer can log in individual Dialog Log Files, via the `logger` member. The `fieldsContainer` is a DiaManT’s inner class instance that holds all the Fields as declared in the `FieldList` in App Config. .Example **** [source,java] ---- @Override public boolean onDialogStart(FieldsContainer fieldList) { logger.log(""CustomModule instance initialized.""); //get some fields field1 = fieldList.getField(""field1""); field2 = fieldList.getField(""field2""); return true; } ---- **** === onDialogClose() Called when a dialog ends. [source,java] ---- boolean onDialogClose() ---- All resources for the specific dialog should be closed now. .Example **** [source,java] ---- @Override public boolean onDialogClose() { // clearDialogResources(); logger.log("" CustomModule instance closed.""); return true; } ---- **** === getTransferData() Called just before a call gets transferred away from the Omilia system. [source,java] ---- String getTransferData(FieldsContainer fieldsContainer) ---- Its purpose is to create outgoing CTI data. With the `fieldsContainer` parameter, the consumer here can read the values and statuses from all Fields, and create a String that will be returned to DiaManT and sent as attached (CTI) data along with the call. Depending on the application’s _TransferModule_, the format of the String that needs to be returned by `getTransferData()` might differ. You can trace your `TransferModule`’s name inside the application’s _DiaManT_System_Config.xml_. [source,xml] ---- ---- For the `basicOmIVR` and `D_SUBDIALOG` TransferModule, the CTI String must be of this format: [source,java] ---- key1:value1;key2:value2;key3:value3 ---- .Example **** [source,java] ---- public String getTransferData(FieldsContainer fieldsContainer) { //read fields from fieldContainer //create a string of any attached data String attachedData = ""key1:value1;key2:value2""; return attachedData; } ---- **** For other TransferModules, the separator changes from semicolon _;_ to comma _,_ and the CTI String must be of this format: [source,java] ---- key1:value1,key2:value2,key3:value3 ---- NOTE: The class that extends the `CustomModuleAdaptor` class should always have a default constructor. === The order of callbacks All the callbacks described above are invoked in a specific order which is presented in the following table. [options=""header""] |=== |Timestamp| Method called a|The application starts . A new dialog starts . Application Callbacks . The call is ready to be transferred . The dialog is closing The application is closing a|onApplicationStart() . getCopy() {empty}+ onDialogStart() . Back-end actions, inferences, nBestValidation... . getTransferData() . onDialogClose() onApplicationStop() |=== == Custom module features - functionality === Back-end calls Back-end calls are methods that have been declared in the _DiaManT_App_Config.xml_, and now, it’s the Custom Module’s job to implement these methods. A Back-end Call can: . Call a back-end system (Web Service, Database, API) in order to get information like: * Caller identification data (date of birth, VAT, telephone numbers, list of cards, list of accounts, and so on) * A banking product’s monetary balance (card/account) * Airline miles, reward points, and so on . Perform an offline action - for example, compute a sum before a payment or lookup a file in the file system or any other business logic. In order to perform a BackEndCall, DiaManT calls the `applyCustomAction()` method of Custom Module. This can be considered as a method that “generates” all the `BackEndCall` functions needed from the front-end, and thus it’s this method that decides what actions should be performed according to the name of the `BackEndCall` function. .Example implementation **** A typical example of a BackendCall, from the Front-end’s perspective, follows below. [source,xml] ---- ---- **** This `BackEndCall` points to a function named `GetAuthorisationToken`, with two input parameters (CardNumber and PIN), and one output (`AuthenticateOut`). On the back-end’s side, the above-mentioned block of code is going to call the method applyCustomAction() with 2 parameters. The first parameter is the function’s name and the second one is a Map with the input parameters of the function (the CardNumber and the PIN number). [source,java] ---- //applyCustomAction Method @Override public Map applyCustomAction(String function, Map input) ---- On completion of the method’s process, it will return a Map to DiaManT with all the output values that the front-end requested. In the next example, the `applyCustomAction()` serves three different BackEndCalls. [source,java] ---- @Override public Map applyCustomAction(String function, Map inputParams) { Map outputParams = null; switch (function) { case ""GetAuthorisationToken"": //all the processes of authentication, and fill the //outputParams break; case ""GetCardBalance"": //all the processes to get the card balance, and fill the //outputParams break; case ""MakePayment"": //all the processes to make a payment and fill the //outputParams break; default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Action name "" + actionName +"" not found. Please check for typos.""); } return outputParams; } ---- === Inferences Inferences are used for inferring the value of fields based on: . the value of one or more fields. . external knowledge implemented and/or accessed in the custom code. For example, the system can infer a city based on a zip code. So whenever the ZipCode Field gets a value the inference rule is automatically triggered inferring the City Field’s value. In order to perform an inference, DiaManT calls the `applyInference()` method of Custom Module. Similar to applyCustomAction(), the `applyInference()` method decides which inference should be executed according to the name of the inference. Inferences are very similar to BackEndCalls, but two notable differences are: . The inference Output Map is pre-filled, and the Custom Module just updates its values. . DiaManT triggers an inference when at least one of its input fields is updated during the dialog. .Example implementation **** In the next example, an inference called ZipToState is declared in the _DiaManT_App_Config.xml_. [source,xml] ---- ---- The ZipCode inference has one input parameter (ZipCode) and expects one output (the State to which this ZipCode belongs). This inference will be triggered by DiaManT when the ZipCode’s status becomes DEFINED, and the `applyInference()` method is called. [source,java] ---- //applyInference Method @Override public void applyInference(String name, Map inputFields, Map inferredFields) ---- Similarly to BackEndCalls the `applyInference()` method works as a “generator” of inference functions that serves the front-end needs. In the next example, the `applyInference()` serves two2 different Inferences. [source,java] ---- @Override public void applyInference(String name, Map inputFields, Map inferredFields) { switch (name) { //First Inference case ""getBankAcountNumber"": //code to implement the logic of getBankAccountNumber //inference and update the inference inferredFields Map break; //Second Inference case ""ZipToState"": //code to implement the logic of ZipToState //inference and update the inference inferredFields Map break; default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Inference name "" + name + "" not found. Please check for typos.""); } } ---- **** === N – Best Validation There are cases where the caller’s voice input is ambiguous. DiaManT offers a way for the Application to define which Fields might be ambiguous, and instruct the ASR to return N (N = integer) possible recognition results each time one of these Fields is updated. These results are sorted by recognition confidence. The CustomModule receives a callback and performs validation in order to select the first best result out of what was recognized. For example, during a dialog, the last five numbers of a credit card are asked. Then, the client replied: _“thirty four fifty one”_. The client might have meant _“34 51”_, _“30 4 51”_, _“30 4 50 1”_ or _“34 50 1”_. In order to overcome this ambiguity, DiaManT generates all possible combinations and provides the CustomModule with a List of all possible answers. The only thing that is necessary now, is a “rule” that can determine which one is correct. Here's the rule in our example: For every credit card in this Bank, the second to last digit must always be 0. Now we can assume that the client said _34501_ because it is a five-digit number and also has the digit zero in the second to last place. The field that needs N-Best Validations is declared in the _DiaManT_App_Config.xml_. [source,xml] ---- ---- When the _CreditCardLast5_ is triggered, DiaManT calls the `nBestValidate()` method. [source,java] ---- @Override public DiamantEntity nBestValidate(String method, List diamantEntities) ---- The `nBestValidate()` method needs two parameters. The first one is the name of the method, which will determine the operations that `nBestValidate()` will perform, and the second parameter is the List with all recognized values. `nBestValidate()` will return the first value that is valid. .Example implementation **** In the next example, the `nBestValidate()` serves 2 different `ValidateNBest` methods. [source,java] ---- @Override public DiamantEntity nBestValidate(String method, List diamantEntities) { switch (method) { case ""BankAccountNumberValidation"": logger.logInfo(CUSTOMER_NAME_MODULE +""Calling "" + methodName); for (DiamantEntity entity : diamantEntities) { String nbestResult = entity.getFirstInstanceValue(); if (isEmpty(nbestResult)) { logger.logWarning(CUSTOMER_NAME_MODULE+""Empty result""); } else { //all the necessary processes for the BankAccountNumberValidation // NOTE: Read the Notes below the block of code bankAccountNumberStatus.updateInstanceValue(""valid""); return entity; } } logger.logWarning(CUSTOMER_NAME_MODULE + nbestResult + ""is not a valid Bank Account number.""); //NOTE: Read the Notes below the block of code bankAccountNumberStatus.updateInstanceValue(""invalid""); return diamantEntities.get(0); case ""CreditCardLast5"": logger.logInfo(CUSTOMER_NAME_MODULE + ""Calling "" + methodName ); for (DiamantEntity entity : diamantEntities) { String nbestResult = entity.getFirstInstanceValue(); if (isEmpty(nbestResult)) { logger.logWarning(CUSTOMER_NAME_MODULE+""Empty result""); } else { //all the processes for the CreditCardLast5 //NOTE: Read the Notes below the block of code cardStatus.updateInstanceValue(""valid""); return entity; } } logger.logWarning(CUSTOMER_NAME_MODULE + nbestResult + ""is not a valid Credit Card number.""); //NOTE: Read the Notes below the block of code cardStatus.updateInstanceValue(""invalid""); return diamantEntities.get(0); default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Validation name "" + methodName +"" not found. Please check for typos.""); } //NOTE: Read the Notes below the block of code return diamantEntities.get(0); } ---- NOTE: The `bankAccountNumberStatus` and the `cardStatus` are fields in the `FieldList` that are loaded on the `onDialogStart`. This practice has to be applied in agreement with the front-end developer, and thus the front-end will be supplied with valuable information if the nBestValidation succeeded or failed. This approach is used by Omilia, but it’s not mandatory. **** === Natural Language Generation (NLG) / Dynamic Announcements Natural Language Generation (NLG) is a process of generating natural language from any representation. For example, the natural language generation of money representation 25.40$ would be _“twenty-five dollars and forty cents”_. Audio files are combined to produce the generated utterance. ==== Audio files configuration All audio files that will be used in the application must be declared in a separate file named _DiaManT_Audio_Config.xml_. In this file, each audio file is associated with an utterance. These utterances, when combined by the realizers, are building a whole announcement. An example of a _DiaManT_Audio_Config_ file is shown below: .Example implementation **** [source,xml] ---- ---- **** ==== FieldRealizer A Class that implements this interface is called Custom FieldRealizer or Custom Realizer. Realizer’s job is to generate natural language from a Field’s value. Below is a brief description of the interface’s methods: - `registerPrompts()` is called when the Application starts. The implementer must register the individual text Prompts that will be used from the Realizer. For example, a `MonetaryRealizer` should declare the text for each number _0-99_ like this: _“one”_, _“two”_, _“three”_ and so on, and some various prompts like _“dollars”_, _“cents”_. The `promptLibrary` provides a method to register text to DiaManT. After this method is called, DiaManT will match the registered text from the Realizer with the registered audio file from the _DiaManT_Audio_Config.xml_ configuration file. [source,java] ---- void registerPrompts(PromptLibrary promptLibrary, String realizerName) ---- .Example implementation **** An example of registering some prompts is shown below : [source,java] ---- @Override public void registerPrompts(PromptLibrary promptLibrary, String realizerName){ String[] numbers = {""zero"", ""one"", ""two"", ""three"", ""four"", ""five"", ""six"", ""seven"", ""eight"", ""nine"",""ten""}; for (int i = 0; i <=10 ; i++) { numberPromptsID.put( String.valueOf(i), promptLibrary.registerFlaggedPrompt(Locale.EN_US, numbers[i], ""Digit Prompt"", false)); } variousPromptsID.put( ""dollars"", promptLibrary.registerFlaggedPrompt(Locale.EN_US, ""dollars"", ""Various Prompt"", false)); variousPromptsID.put( ""cents"", promptLibrary.registerFlaggedPrompt(Locale.EN_US, ""cents"", ""Various Prompt"", false)); variousPromptsID.put( ""and"", promptLibrary.registerFlaggedPrompt(Locale.EN_US, ""and"", ""Various Prompt"", false)); } ---- **** - `realizeValue()` is called when a Field is part of a dynamic announcement. The first parameter, `type`, is an optional instruction for the method call on how to synthesize the result `Prompt`. The `value` parameter is the value of the `Field` in question. The `fieldsContainer` parameter is the Application’s `FieldList` as provided in the Custom Module’s `onDialogStart()`. The logger parameter is the Dialog’s logger instance. [source,java] ---- PromptID realizeValue(String type, String value, FieldsContainer fieldsContainer, DialogLogger logger) ---- This method is the one responsible to compose and return a dynamic announcement. The return type is `PromptID`. This class represents one, or many prompts tied together. An example of the `realizeValue()` implementation for a simple monetary realizer is shown below. This realizer will turn the money representation 5.10$ to `“five dollars and ten cents”`. .Example implementation **** [source,java] ---- @Override public PromptID realizeValue(String type, String value, FieldsContainer fieldList, DialogLogger logger) { this.logHelper = new LogHelper(logger, MoneyRealizer.class.getSimpleName()); this.logHelper.log(""Realizing value: {0} with realizeType: {1}"", new LogParameter(value, true), new LogParameter(type, false)); try { PromptID pid = new PromptID(); String[] splitValue = value.split(""\\\\.""); String dollarsAmount = splitValue[0]; String centsAmount = splitValue[1]; pid.postAdd(numberPromptsID.get(dollarsAmount), true); pid.postAdd(variousPromptsID.get(""dollars""), true); pid.postAdd(variousPromptsID.get(""and""), true); pid.postAdd(numberPromptsID.get(centsAmount), true); pid.postAdd(variousPromptsID.get(""cents""), true); return pid; } catch (Exception e) { e.printStackTrace(); logHelper.logError(""Exception: {0}"", new LogParameter(e, false)); return new PromptID(); } } ---- **** - `getCopy()` method is treated as a constructor and is called at the start of each Dialog in order to initialize the implementer. [source,java] ---- FieldRealizer getCopy() ---- NOTE: A class that implements FieldRealizer should always have a default constructor. ==== Declare your custom realizers The implemented realizers have to be declared in the _DiaManT_App_Config.xml_ as shown below: [source,xml] ---- ---- [source,xml] ---- ---- And the announcement looks like this: [source,xml] ---- Your current balance is #TY01_currentBalance# ---- == Logging There are two logger instances that can be used: a. the `GenericLogger`. b. the `DialogLogger`. The `GenericLogger` is to be used only outside the scope of a Dialog, which is `onApplicationStart()` and `onApplicationClose()`. Here’s how to access it: [source,java] ---- DialogManager.getInstance().getLogger(); ---- .Example of `GenericLogger` record on server logs image::images/diam_cust_mod_8.png[Example of `GenericLogger` record on server logs] The `DialogLogger` is used everywhere else, and the way to access it is via the logger member in the main Custom Module class (the one that extends the `CustomModuleAdaptor`). An important difference in usage between the two loggers is that the first one writes in the Server Logs and the second writes in the Dialog Log. The Server Logs are accessible through the Dashboard’s DiaManT administration page. The Dialog Log is accessible through the DRT (select a call and then select DiaManT log file). Each Dialog has its own log file, so every call’s events are traceable in a single place, without other calls’ events interference. Below is the table of supported Log Levels, the corresponding method in the Loggers, and the message color: .Supported log levels [options=""header""] |=== |Log Level |Method Signature |Message Color |TRACE |log(String message) |WHITE/GRAY |INFO |logInfo(String message) |YELLOW |WARNING |logWarning(String message) |ORANGE |ERROR |logError(String message) |RED |=== Each one of these levels of logging appears in different colors in the dialog log file. Plain log messages are white/gray, information messages are yellow, warning messages are orange and error messages are red. Log messages have a hierarchy of systems. Each system is separated from a subsystem by using the :> delimiter at the end of the system name, for example : [source,java] ---- logInfo(""CustomModule :> Custom Module instance created.""); ---- According to the next dialog, the corresponding Dialog Logs are presented. .Dialog Logs example image::images/diam_cust_mod_1.png[Dialog Logs example] Firstly, the method `onDialogStart()` is called as shown below. .`onDialogStart()` method called image::images/diam_cust_mod_4.png[`onDialogStart()` method called] Next, the `applyCustomAction()` is called that triggers the associated action and Handler Classes. .`applyCustomAction()` method called image::images/diam_cust_mod_9.png[`applyCustomAction()` method called] The values that returned from the Web Service need to be realized in order to be announced to the client. Thus, the `FXRealizer` is called. .`FXRealizer` called image::images/diam_cust_mod_2.png[`FXRealizer` called] In the end, the Application says Goodbye to the client, and the `onDialogClose()` method is called, as shown below. .`onDialogClose()` method called image::images/diam_cust_mod_5.png[`onDialogClose()` method called] == Omilia archetype === Introduction In order to standardize the Custom Module and make code modular and more readable, Omilia has created its own archetype. In this chapter, Omilia’s patterns are presented. As a prerequisite, you should install JDK 1.8, and IntelliJ IDEA CE. Both can be downloaded from the official Web Sites (for IntelliJ select the Community edition). Lastly, Omilia’s archetype encourages the use of Maven as the project building tool. === Adding DiaManT dependency on local maven repository In order to add the DiaManT _.jar_ file, you need to create a folder path under the _.m2/ repository/_ folder. The _.m2_ folder can be found under the user’s home folder. Navigate to the _m2/ repository/_ folder. In this folder, you will need to create the following folder structure: _com/omilia/diamant/diamant-core/_. After the creation of the folders, you should place the DiaManT _.jar_ file in the _diamant-core_ folder you created. The DiaManT _.jar_ file has to be renamed to _diamant-core-.jar_. Maven looks for a dependency in the _.m2/repository_ folder according to the dependency declaration in the following way: `` and `` describe the folder structure (like the one you created before). Then Maven will look for a _jar_ name the content of the artifactId, followed by a dash, followed by the version. For example, for the following dependency, maven will look for a _jar_ named _diamant-core-9.5.0.jar_ under _.m2/ repository/com/omilia/diamant/diamant-core/_. Now, you can use DiaManT with maven by adding the following to your _pom.xml_: [source,xml] ---- com.omilia.diamant diamant-core 9.5.0 provided ---- === Project structure This is a typical Maven project structure. Here is a short description of each package. .Maven project structure image::images/diam_cust_mod_10.png[float=""left"", Maven project structure] actions:: contains every action. Actions are built by extending `AbstractAction` which partially implements Action interface. constants:: package for all the constants. inferences:: contains all the inferences. Inferences are built by extending the `AbstractInference`. nbestvalidation:: contains all the `nBestValidations`. `nBestValidations` are built by extending the `AbstractNBestValidation` class. properties:: Miscellaneous project properties. realizers:: contain all the realizers and realizer related sub-packages like prompts which contain a `PromptCollection` class for each realizer. utils:: Miscellaneous helper classes for the project. webservices.handlers:: All handlers for accessing web services. Handlers are built by extending the `AbstractHandler` class. webservices.requests:: contains all requests needed for calling the web services. webservice.responses:: all the expected responses from web services. resources.prompts.en_US:: the package of all JSON files which contains English prompts and will be used by realizers. === Data source access When the Custom Module needs data from any data source, the common architecture that is followed is to create three classes for each data call. These classes are : * A Request class. * A Handlers class * A Response class. ==== Requests Request classes model the back-ends system’s request into an Object and follow the next pattern: * Each class exists in the package requests. * Each class’s name ends in “_....Request”_. * Each class extends the Request class. * Each class has setters for all the class members. .Example implementation **** Assuming that our Application requires to call a RESTFUL web service in order to obtain a token, named `GetToken`. Here’s an example request: [source,java] ---- { ""cardNumber"": ""4735339478512110"", ""pin"": ""1234"" } ---- In order to call the mentioned web service, firstly we have to create the `GetTokenRequest` class that extends the Request, and have setters for all the class members. [source,java] ---- public class GetTokenRequest extends Request { private String cardNumber; private String pin; public GetTokenRequest() { } public void setCardNumber(String cardNumber) { this.cardNumber = cardNumber; } public void setPin(String pin) { this.pin = pin; } } ---- **** ==== Handlers Handlers are classes that have the responsibility to call the Web Service and to create the Response object. Every handler follows the next pattern. * Each class exists in the package handlers. * Each class’s name ends in “_....Handler_”. * Each class extends the AbstractHandler class and has to implement all the inherited abstract methods. * Each class has a request as input. * Each class creates a response object. .Example implementation **** Now we have to create the `GetTokenHandler` that extends the `AbstractHandler`, sets the request, executes the post Request and creates the Response Object. [source,java] ---- public class GetTokenHandler extends AbstractHandler { private GetTokenRequest request = new GetTokenRequest(); public GetTokenHandler(DialogLogger logger, String endpoint) { super(logger, endpoint, GetTokenHandler.class.getSimpleName()); } public void setRequest(GetTokenRequest request) { this.request = request; } @Override public boolean initialize() { log(""GetTokenHandler initialized."", LogParameter.noParams()); return true; } @Override public Response getResponse() { log(""Preparing to call the WebService for GetAuthorisationToken with request {0}"", new LogParameter(request, true)); //call the Web Service String output = WebUtilities.sendPostRequest(request, getEndpoint()); if (isNull(output)) { log(""The web service did not respond"", LogParameter.noParams()); return getErrorResponse(); } //Web Service Responded log(""WebService call was successful "", LogParameter.noParams()); log(""Parsing String {0} to POJO "", new LogParameter(output, true)); //Handling the web service's output, and create the necessary Response //object. This can be different according to your needs. Response response = WebUtilities.gson.fromJson(output, GetTokenResponse.class); //Web Service Status is everything but Successful if (!ResponseObjects.SUCCESS.equals(response.getStatusCode())) { log(""Response status code is {0}."", new LogParameter(response.getStatusCode(),false)); return new Response(response.getStatusCode(), response.getStatusMsg()); } //Web Service call returned Success log(""Response status code is SUCCESS"", LogParameter.noParams()); return response; } @Override public Response getErrorResponse() { return new Response(ResponseObjects.ERROR, ResponseObjects.ERROR_MSG); } } ---- **** ==== Responses Response classes model the back-end system response into an Object and follow the pattern below: * Each class exists in the package responses. * Each class’s name ends in “_....Response_”. * Each class extends the Response class. * Each class has getters for all the class members. .Example implementation **** In the previous example, the response of the web service is the following : [source,java] ---- { ""statusCode"": ""SUCCESS"", ""statusMsg"": ""Request Processed successfully"", ""token"": ""50CF18DC2B30E4CDA6B40C2C4E0F8337"" } ---- In order to model the mentioned response, we have to create the `GetTokenResponse` class that extends the Response, with all arguments constructor and getter for the class variable. [source,java] ---- public class GetTokenResponse extends Response { private String token; public GetTokenResponse(String returnCode, String statusMsg, String token) { super(returnCode, statusMsg); this.token = token; } public String getToken() { return token; } } ---- **** === Actions In the process of keeping the code clean and modular, each `BackEndCall` is associated with one action class. Action classes implement all the business logic that App Config requires, and thus, the `applyCustomAction()` method creates the necessary actions objects according to the input function name. The goal is to avoid having any business logic inside this method. Every action follows the next pattern: * Each class’s name ends in “_...Action_” or “_...Call_”. * Each class extends the AbstractAction. * An action can have many Handler class members. * Each class has a constructor,that sets the input from DiaManT (as defined in the App Config). * Each class has a method named process(), that : ** Reads the input fields. ** Applies pre-processing business logic. ** Calls the Web Services / DB / back-end Systems through Handlers. ** Applies post-processing business logic. ** Stores output fields. .Example implementation **** Following the previous example, a `BackEndCall` follows: [source,xml] ---- ---- Below you will find the implementation of the `AuthenticateAction`. [source,java] ---- public class AuthenticateAction extends AbstractAction { private String token; public String getToken() { return token; } public AuthenticateAction(Map input, DialogLogger logger) { super(input, logger, AuthenticateAction.class.getSimpleName()); } @Override public void process() { if (isNull(input.get(Inputs.CARD_NUMBER))||isNull(input.get(Inputs.PIN))) { addToMap(output, OutputNames.AUTHENTICATE_OUT, OutputValues.ERROR); logError(""Missing request element. Action output field \\"""" + OutputNames.AUTHENTICATE_OUT + ""\\"" is {0}"",new LogParameter(output.get(OutputNames.AUTHENTICATE_OUT).getValue(), false)); return; } //create and initialize the getTokenHandler GetTokenHandler handler = new GetTokenHandler(logger, Endpoints.BASE_URL + Endpoints.GET_TOKEN); handler.initialize(); //create request - read input fields GetTokenRequest request = new GetTokenRequest(input.get(Inputs.CARD_NUMBER) .getValue(), input.get(Inputs.PIN).getValue()); //set the request to handler handler.setRequest(request); //Call Web Service Response response = handler.getResponse(); String result; //check response status code switch (response.getStatusCode()) { case ResponseObjects.SUCCESS: result = OutputValues.SUCCESS; //Add token to input map in order to be available to other actions GetTokenResponse tokenResponse = (GetTokenResponse) response; this.token = tokenResponse.getToken(); break; case ResponseObjects.NOT_FOUND: result = OutputValues.FAIL; break; default: result = OutputValues.ERROR; } //Store output fields addToMap(output, OutputNames.AUTHENTICATE_OUT, result); log(""Action output field \\"""" + OutputNames.AUTHENTICATE_OUT + ""\\"" is {0}"", new LogParameter(result, false)); } } ---- Now the `applyCustomAction()` method looks like the following. [source,java] ---- @Override public Map applyCustomAction(String actionName, Map inputParams) { Map outputParams = null; switch (actionName) { case ""authenticateOut"": //create the action object AuthenticateAction authenticateAction = new AuthenticateAction(inputParams, logger); //call the process authenticateAction.process(); //store the output fields outputParams = authenticateAction.getOutput(); //set the class variable token this.token = authenticateAction.getToken(); break; //example of another action case ""anotherAction"": AnotherAction anotherAction = new AnotherAction(inputParams, logger); anotherAction.process(); outputParams = anotherAction.getOutput(); break; default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Action name "" + actionName + "" not found. Please check for typos.""); } return outputParams; } ---- **** === Inferences Similar to actions, inferences go to their own package. Create one class per inference, so that the `applyInference()` method has to create the appropriate inference object, and call the `inferFields()` method. Every inference follows the next pattern: * One class per inference (as defined in the App Config). * Each class’s name ends in “_...Inference_”. * Each class extends the AbstractInference class. * Each inference class has a constructor that sets the input from DiaManT (as Defined in the App Config). * Each class has a method named inferFields, that: ** Reads the input fields. ** Applies pre-processing business logic. ** Calls the Web Services / DB / back-end Systems through Handlers. ** Applies post-processing business logic. ** Stores results in the PRE-FILLED inferredFields map. .Example implementation **** In the next example, an implementation of an inference class is presented. In this example, the input is a List with all the Bank Accounts that a client has, and a 3 digit string. The inference must find the Bank Account with the number that ends in the provided 3 digit string. The next block of code presents the declaration of this inference in the _DiaManT_App_Config.xml_. [source,xml] ---- ---- Bellow, you can see the implementation of the `FullBankAccountInference`: [source,java] ---- public class GetFullBankAccountNumberInference extends AbstractInference { private List openAccountList; //constructor public GetFullBankAccountNumberInference(Map inputFields, Map inferredFields, List openAccountList, DialogLogger logger) { super(inputFields, inferredFields, logger, GetFullBankAccountNumberInference.class.getSimpleName()); this.openAccountList = openAccountList; } @Override public void inferFields() { log(""GetFullBankAccountNumberInference"",LogParameter.noParams()) //Read input fields String bankAccountLast3 = inputFields.get(“AccountLastThree”).getValue() //check all the list for the correct bank account and the first one that //matches is returned for (BankAccount current : openAccountList) { String last3 = StringUtils.substring(current.getBankAccountNumber(), -3); if (bankAccountLast3.equals(last3)) { log(""Bank account inferred: {0}"", new LogParameter(current.getBankAccountNumber(), false)); //store results in the PRE-FILLED inferredFields map defineApiField(inferredFields.get(“FullBankAccountNumber”), current.getBankAccountNumber()); return; } } //Didn't find the bank account log(""Could not find the bank account. "", LogParameter.noParams()); //Apply post-processing business logic and store results in the // inferredFields map inferredFields.get(“AccountLastThree”).setStatus(FieldStatus.UNDEFINED); log(""The status of the field AccountLastThree is {0} "", new LogParameter(inferredFields.get(“AccountLastThree”).getStatus(),false)); inferredFields.get(“FullBankAccountNumber”).setValue(""error""); log(""The value of the field FullBankAccountNumber is {0} "", new LogParameter(inferredFields.get(“FullBankAccountNumber”).getValue(), false)); } } ---- Now, the `applyInference` method looks like this: [source,java] ---- @Override public void applyInference(String name, Map inputFields,Map inferredFields) { switch (name) { case ""getFullBankAccountNumber"": //create the inference object GetFullBankAccountNumberInference getFullBankAccountNumberInference = new GetFullBankAccountNumberInference(inputFields, inferredFields, openAccountList, logger); //call the inferfields method getFullBankAccountNumberInference.inferFields(); break; //example of another inference case ""anotherInference"": AnotherInference anotherInference = new AnotherInference(inputFields, inferredFields, anotherCollection, logger); anotherInference.inferFields(); break; default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Inference name "" + name + "" not found. Please check for typos.""); } } ---- **** === NBestValidation For each `nBestValidation`, one Validation class has to be created. Then, the `nBestValidate()` method has to create the appropriate validate object, that calls its `validate()` method. Every nBestValidation follow the next pattern: * One class per nBestValidation. * Each class’s name ends in “_...Validation_”. * Each class extends the AbstractNBestValidation. * Each class has a constructor, that sets the input from DiaManT. The input is a list of `DiamantEntities ( List diamantEntities)`. * Each class has a method called `validate()`, that: ** Iterates through the List of DiaManT Entities. ** Applies business logic. ** Returns a `DiamantEntity`. .Example implementation **** In the next example, an implementation of an `nBestValidation` is presented. The purpose of this `nBestValidation` is to validate whether the given number is a valid bank number or not. The declaration of this `nBestValidation` in the _DiaManT_App_Config.xml_ is the following: [source,xml] ---- ---- It is assumed that a static method named `isValid()` is implemented in the `BankAccountUtils` class. [source,java] ---- public class BankAccountNumberValidation extends AbstractNBestValidation { private Field bankAccountNumberStatus; public BankAccountNumberValidation (DialogLogger logger, List diamantEntities, Field bankAccountNumberStatus) { super(logger, ExampleNBestValidation.class.getSimpleName(), diamantEntities); this.bankAccountNumberStatus = bankAccountNumberStatus; } @Override public DiamantEntity validate() { for (DiamantEntity entity : diamantEntities) { String nbestResult = entity.getFirstInstanceValue(); if (isEmpty(nbestResult)) { logWarning(CUSTOMMODULE + ""N-best result is empty Ignoring..."", LogParameter.noParams()); //A specific method is implemented in the CreditCardUtils // class to validate if a card number is valid } else if (!BankAccountUtils.isValid(nbestResult)) { logWarning(CUSTOMMODULE + nbestResult + ""is not a valid value"", LogParameter.noParams()); } else { //inform that a valid field is returned bankAccountNumberStatus.updateInstanceValue(""valid""); //sanitize nbestResult = deleteWhitespace(nbestResult); //return DiamantEntity with sanitized value return createDiamantEntity(entity.getEntityName(), nbestResult); } } //There is not a valid DiamantEntity in the given diamantEntities logWarning(CUSTOMMODULE + ""No valid value in the diamantEntities"", LogParameter.noParams()); //inform the front end that the returned entity is not valid, by updating a // field bankAccountNumberStatus.updateInstanceValue(""invalid""); //return the first return diamantEntities.get(0); } } ---- NOTE: The `bankAccountNumberStatus` is a field in the `FiledList` that is loaded in the `onDialogStart()` method. This practice has to be applied in agreement with the front-end developer, and thus the front-end will be supplied with valuable information if the `nBestValidation` succeeded or failed. This approach is used by Omilia, but it’s not mandatory. The `nBestValidate()` method looks like the next one. [source,java] ---- @Override public DiamantEntity nBestValidate(String methodName, List diamantEntities) { switch (methodName) { case ""bankAccountNumberValidation"": logger.logInfo(CUSTOMER_NAME_MODULE + ""Calling "" + methodName ); BankAccountNumberValidation validation = new BankAccountNumberValidation(logger, diamantEntities, bankAccountNumberStatus); return validation.validate(); default: logger.logWarning(CUSTOMER_NAME_MODULE + ""Validation name "" + methodName +"" not found. Please check for typos.""); } return diamantEntities.get(0); } ---- **** === Registering Prompts Omilia’s strategy about registering prompts is to store all prompts related to a specific realizer in a separated JSON file. This file is stored under the resources folder and in a package named as _pass:c[prompts.{local}]_ where local is a specific language code. The naming convention for this file is _pass:c[{RealizerName}Prompts.json]_. For example, all the English prompts that will be used in a DigitRealizer, will be found in the file _resources/prompts.en_us/DigitPrompts.json_ The JSON file must have the form shown below. [source,java] ---- { ""Digit Prompts"": { ""Single Digit Prompts"": { ""0"": ""zero"", ""1"": ""one"", ""2"": ""two"", ""3"": ""three"", ""4"": ""four"", ""5"": ""five"", ""6"": ""six"", ""7"": ""seven"", ""8"": ""eight"", ""9"": ""nine"" }, ""Other Category Prompts"": { ... } } } ---- Then the prompts JSON file has to be parsed and each prompt has to be registered. This is a standard procedure so Omilia’s archetype provides the `AbstractPromptsCollection` class which implements some of the methods of `PromptCollection` interface. The unimplemented methods have to be implemented by all subclasses of `AbstractPromptCollection` class. Every realizer must have its own `PromptCollection` object. A `JsonUtilities` class is also provided in order to parse the json file. Below is the `DigitPrompts` class which implements the register method and is used to create the `PromptCollection` object of `DigitRealizer`. .Example implementation **** [source,java] ---- @Getter public class DigitPrompts extends AbstractPromptCollection { private Map digitPromptsID; private Map digitPrompts; public DigitPrompts(Locale locale) { super(locale); String jsonPath = MessageFormat.format(""/prompts/{0}_US/DigitPrompts.json"", getLanguageCode(locale)); //parse json file Map parsedJson = JsonUtilities.loadJson(jsonPath, ""Digit Prompts""); digitPrompts = JsonUtilities.loadPromptMap(parsedJson, ""Single Digit Prompts""); } @Override public void register(PromptLibrary promptLibrary) { digitPromptsID = register(digitPrompts, ""Single Digit Prompts"", promptLibrary, """"); } @Override public void registerForTest() { digitPromptsID = registerForTest(digitPrompts, """"); } } ---- From this point, it is easy registering all the prompts as calling the register method of `DigitPrompts` class from registerPrompts method of `DigitRealizer` class. [source,java] ---- public class DigitsRealizer implements FieldRealizer { //create the PromptCollection object private static final DigitPrompts english = new DigitPrompts(Locale.EN_US); @Override public void registerPrompts(PromptLibrary promptLibrary, String realizerName){ english.register(promptLibrary); } ... } ---- **** === Environment One major advantage of Custom Module is the ability to perform differently according to the environment that is set up, without any modifications in the source code. The environment should be set up in the method `onApplicationStart()`, according to the developer’s or project’s needs. The developer is free to create their own configuration file, or to use the _Custom_Config.xml_, in order to declare the value of the environment. The environment types are declared in the Environment class, inside the package properties. In the Omillia’s Archetype three environments exist. The LAB environment which is used as the local development environment, the UAT which is the testing environment of the client, and lastly you will find the PROD environment, which stands for the production environment. The developer is encouraged to extend this enum according to their needs, and add more environments, for example, UAT-A, UAT-B, and so on. === Logging API The Omilia’s archetype offers a built-in `LogHelper` class, which can be extended. Any class that extends the `LogHelper` is able to log with the `DialogLogger`. The logging is similar to `printf()` and can log data dynamically. Example 1:: [source,java] ---- log(""This logging example does not have parameters "", LogParameter.noParams()); ---- Example 2:: [source,java] ---- log(""Example value is {0}"", new LogParameter(exampleValue, isSensitive)); ---- The second parameter (`isSensitive`) can mask in the production environment (PROD) any data that is sensitive (for example, a card number, a pin number, and so on). If the value of this parameter is true, the data will be masked and logged with asterisks (pass:c[*]). However in a testing environment (LAB, UAT) the data will not be masked. You can modify the logic that masks the sensitive data from the LogHelper class. == Getting Finished After the development of a Custom Module, a _.jar_ file should be created and included in the folder that contains all the Application’s files. In order to build a _.jar_ file, Intellij's Maven tool window can be used. In the up-right corner of the window, a Maven button can be found. Then, the user has to select the Lifecycle folder and execute the package option. .Intellij's Maven tool window image::images/diam_cust_mod_7.png[Intellij's Maven tool window] When the build finishes, the _.jar_ file will have been created, and the user can find it in the target folder. It is also necessary to declare the Custom Module in the App Config, as follows. [source,xml] ---- ---- The attribute `name` in the tag ``, refers to the class that extends the `CustomModuleAdaptor`. ",12247,False,2104.0113294061284,median "--- title: Элементы архитектуры системы виртуальной памяти во FreeBSD authors: - author: Matthew Dillon email: dillon@apollo.backplane.com trademarks: [""freebsd"", ""linux"", ""microsoft"", ""opengroup"", ""general""] --- = Элементы архитектуры системы виртуальной памяти во FreeBSD :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :images-path: articles/vm-design/ ifdef::env-beastie[] ifdef::backend-html5[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] :imagesdir: ../../../images/{images-path} endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [.abstract-title] Аннотация Название статьи говорит лишь о том, что я попытаюсь описать в целом VM-систему понятным языком. Последний год я сосредоточил усилия в работе над несколькими основными подсистемами ядра FreeBSD, среди которых подсистемы VM и подкачки были самыми интересными, а NFS оказалась ""необходимой рутиной"". Я переписал лишь малую часть кода. Что касается VM, то я единственным большим обновлением, которое я сделал, является переделка подсистемы подкачки. Основная часть моей работы заключалась в зачистке и поддержке кода, с единственной заметной переделкой кода и без значительной переделки алгоритмов в VM-подсистеме. В основном теоретическая база работы VM-подсистемы осталась неизменной, а большинство благодарностей за современных нововведения за последние несколько лет принадлежат John Dyson и David Greenman. Не являясь историком, как Керк, я не буду пытаться связать различные возможности системы с именами, потому что обязательно ошибусь. ''' toc::[] [[introduction]] == Введение Перед тем, как перейти непосредственно к существующей архитектуре, потратим немного времени на рассмотрение вопроса о необходимости поддержки и модернизации любого длительно живущего кода. В мире программирования алгоритмы становятся более важными, чем код, и именно из-за академических корней BSD изначально большое внимание уделялось проработке алгоритмов. Внимание, уделенное архитектуре, в общем отражается на ясности и гибкости кода, который может быть достаточно легко изменен, расширен или с течением времени заменен. Хотя некоторые считают BSD ""старой"" операционной системой, те их нас, кто работает над ней, видят ее скорее системой со ""зрелым"" кодом с различными компонентами, которые были заменены, расширены или изменены современным кодом. Он развивается, и FreeBSD остается передовой системой, вне зависимости от того, насколько старой может быть часть кода. Это важное отличие, которое, к сожалению, не всеми понимается. Самой большой ошибкой, которую может допустить программист, является игнорирование истории, и это именно та ошибка, которую сделали многие другие современные операционные системы. Самым ярки примером здесь является Windows NT(R), и последствия ужасны. Linux также в некоторой степени совершил эту ошибку-достаточно, чтобы мы, люди BSD, по крайней мере по разу отпустили по этому поводу шутку. Проблема Linux заключается просто в отсутствии опыта и истории для сравнения идей, проблема, которая легко и быстро решается сообществом Linux точно так же, как она решается в сообществе BSD-постоянной работой над кодом. Разработчики Windows NT(R), с другой стороны, постоянно совершают те же самые ошибки, что были решены в UNIX(R) десятки лет назад, а затем тратят годы на их устранение. Снова и снова. Есть несколько случаев ""проработка архитектуры отсутствует"" и ""мы всегда правы, потому что так говорит наш отдел продаж"". Я плохо переношу тех, кого не учит история. Большинство очевидной сложности архитектуры FreeBSD, особенно в подсистеме VM/Swap, является прямым следствием того, что она решает серьезные проблемы с производительностью, которые проявляются при различных условиях. Эти проблемы вызваны не плохой проработкой алгоритмов, а возникают из окружающих факторов. В любом прямом сравнении между платформами эти проблемы проявляются, когда системные ресурсы начинают истощаться. Так как я описываю подсистему VM/Swap во FreeBSD, то читатель должен всегда иметь в виду два обстоятельства: . Самым важным аспектом при проектировании производительности является то, что называется ""оптимизацией критического маршрута"". Часто случается, что оптимизация производительности дает прирост объема кода ради того, чтобы критический маршрут работал быстрее. . Четкость общей архитектуры оказывается лучше сильно оптимизированной архитектуры с течением времени. Когда как обобщенная архитектура может быть медленнее, чем оптимизированная архитектура, при первой реализации, при обобщенной архитектуре легче подстраиваться под изменяющиеся условия и чрезмерно оптимизированная архитектура оказывается непригодной. Любой код, который должен выжить и поддаваться поддержке годы, должен поэтому быть тщательно продуман с самого начала, даже если это стоит потери производительности. Двадцать лет назад были те, кто отстаивал преимущество программирования на языке ассемблера перед программированием на языке высокого уровня, потому что первый генерировал в десять раз более быстрый код. В наши дни ошибочность этого аргумента очевидна - можно провести параллели с построением алгоритмов и обобщением кода. [[vm-objects]] == Объекты VM Лучше всего начать описание VM-системы FreeBSD с попытки взглянуть на нее с точки зрения пользовательского процесса. Каждый пользовательский процесс имеет единое, принадлежащее только ему и неразрывное адресное пространство VM, содержащее несколько типов объектов памяти. Эти объекты имеют различные характеристики. Код программы и ее данные являются единым файлом, отображаемым в память (это выполняющийся двоичный файл), однако код программы доступен только для чтения, когда как данные программы размещаются в режиме копирования-при-записи. BSS программы представляет собой всего лишь выделенную область памяти, заполненную, если это требовалось, нулями, что называется обнулением страниц памяти по требованию. Отдельные файлы могут также отображаться в адресное пространство, именно так работают динамические библиотеки. Такие отображения требуют изменений, чтобы оставаться принадлежащими процессу, который их выполнил. Системный вызов fork добавляет переводит проблему управления VM полностью в новую плоскость, вдобавок к уже имеющимся сложностям. Иллюстрирует сложность страница данных двоичной программы (которая является страницей копируемой-при-записи). Двоичная программа содержит секцию предварительно инициализированных данных, которая первоначально отображается непосредственно из файла программы. Когда программа загружается в Vm-пространство процесса, эта область сначала отображается в память и поддерживается бинарным файлом программы, позволяя VM-системе освобождать/повторно использовать страницу, а потом загружать ее снова из бинарного файла. Однако в момент, когда процесс изменяет эти данные, VM-система должна сделать копию страницы, принадлежащую только этому процессу. Так как эта копия была изменена, то VM-система не может больше освобождать эту страницу, так как впоследствии ее невозможно будет восстановить. Вы тут же заметите, что то, что сначала было простым отображением файла в память, становится гораздо более сложным предметом. Данные могут модифицироваться постранично, когда как отображение файла выполняется для многих страниц за раз. Сложность еще более увеличивается, когда процесс выполняет вызов fork. При этом порождаются два процесса-каждый со с собственным адресным пространством, включающим все изменения, выполненные исходным процессом до вызова функции `fork()`. Было бы глупо для VM-системы делать полную копию данных во время вызова `fork()`, так как весьма вероятно, что один из двух процессов будет нужен только для чтения из той страницы, что позволяет использование исходной страницы. То, что было страницей, принадлежащей только процессу, сделается снова страницей, копируемой при записи, так как каждый из процессов (и родитель, и потомок) полагают, что их собственные изменения после разветвления будут принадлежать только им, и не затронут родственный процесс. FreeBSD управляет всем этим при помощи многоуровневой модели VM-объектов. Исходный файл с двоичной программой переносится на самый нижний уровень объектов VM. Уровень страниц, копируемых при записи, находится выше него, и хранит те страницы, которые были скопированы из исходного файла. Если программа модифицирует страницы данных, относящиеся к исходному файлу, то система VM обнаруживает это и переносит копию этой страницы на более высокий уровень. Когда процесс разветвляется, добавляются новые уровни VM-объектов. Это можно показать на простом примере. Функция `fork()` является общей операцией для всех систем *BSD, так что в этом примере будет рассматриваться программа, которая запускается, а затем разветвляется. Когда процесс запускается, VM-система создает некоторый уровень объектов, обозначим его A: image::fig1.png[Рисунок] A соответствует файлу-по необходимости страницы памяти могут высвобождаться и подгружаться с носителя файла. Подгрузка с диска может потребоваться программе, однако на самом деле мы не хотим, чтобы она записывалась обратно в файл. Поэтому VM-система создает второй уровень, B, который физически поддерживается дисковым пространством подкачки: image::fig2.png[] При первой записи в страницу после выполнения этой операции, в B создается новая страница, содержимое которой берется из A. Все страницы в B могут сбрасываться и считываться из устройства подкачки. Когда программа ветвится, VM-система создает два новых уровня объектов-C1 для порождающего процесса и C2 для порожденного-они располагаются поверх B: image::fig3.png[] В этом случае, допустим, что страница в B была изменена начальным родительским процессом. В процессе возникнет ситуация копирования при записи и страница скопируется в C1, при этом исходная страница останется в B нетронутой. Теперь допустим, что та же самая страница в B изменяется порожденным процессом. В процессе возникнет ситуация копирования при записи и страница скопируется в C2. Исходная страница в B теперь полностью скрыта, так как и C1, и C2 имеют копии, а B теоретически может быть уничтожена, если она не представляет собой ""реального"" файла). Однако такую оптимизацию не так уж просто осуществить, потому что она делается на уровне мелких единиц. Во FreeBSD такая оптимизация не выполняется. Теперь положим (а это часто случается), что порожденный процесс выполняет вызов `exec()`. Его текущее адресное пространство обычно заменяется новым адресным пространством, представляющим новый файл. В этом случае уровень C2 уничтожается: image::fig4.png[] В этом случае количество потомков B становится равным одному и все обращения к B теперь выполняются через C1. Это означает, что B и C1 могут быть объединены. Все страницы в B, которые также существуют и в C1, во время объединения из B удаляются. Таким образом, хотя оптимизация на предыдущем шаге может не делаться, мы можем восстановить мертвые страницы при окончании работы процессов или при вызове `exec()`. Такая модель создает некоторое количество потенциальных проблем. Первая, с которой вы можете столкнуться, заключается в сравнительно большой последовательности уровней объектов VM, на сканирование которых тратится время и память. Большое количество уровней может возникнуть, когда процессы разветвляются, а затем разветвляются еще раз (как порожденные, так и порождающие). Вторая проблема заключается в том, что вы можете столкнуться с мертвыми, недоступными страницами глубоко в иерархии объектов VM. В нашем последнем примере если как родитель, так и потомок изменяют одну и ту же страницу, они оба получают собственные копии страницы, а исходная страница в B становится никому не доступной. такая страница в B может быть высвобождена. FreeBSD решает проблему с глубиной вложенности с помощью приема оптимизации, который называется ""All Shadowed Case"". Этот случай возникает, если в C1 либо C2 возникает столько случаев копирования страниц при записи, что они полностью закрывают все страницы в B. Допустим, что такое произошло в C1. C1 может теперь полностью заменить B, так что вместо цепочек C1->B->A и C2->B->A мы теперь имеем цепочки C1->A и C2->B->A. Но посмотрите, что получается-теперь B имеет только одну ссылку (C2), так что мы можем объединить B и C2. В конечном итоге B будет полностью удален и мы имеем цепочки C1->A и C2->A. Часто B будет содержать большое количество страниц, и ни C1, ни C2 не смогут полностью их заменить. Если мы снова породим процесс и создадим набор уровней D, при этом, однако, более вероятно, что один из уровней D постепенно сможет полностью заместить гораздо меньший набор данных, представленный C1 и C2. Та же самая оптимизация будет работать в любой точке графа и главным результатом этого является то, что даже на сильно загруженной машине с множеством порождаемых процессов стеки объектов VM не часто бывают глубже четырех уровней. Это так как для порождающего, так и для порожденного процессов, и остается в силе как в случае, когда ветвление делает родитель, так и в случае, когда ветвление выполняет потомок. Проблема с мертвой страницей все еще имеет место, когда C1 или C2 не полностью перекрывают B. Из-за других применяемых нами методов оптимизации этот случай не представляет большой проблемы и мы просто позволяем таким страницам существовать. Если система испытывает нехватку оперативной памяти, она выполняет их выгрузку в область подкачки, что занимает некоторое пространство в области подкачки, но это все. Преимущество модели VM-объектов заключается в очень быстром выполнении функции `fork()`, так как при этом не выполняется реального копирования данных. Минусом этого подхода является то, что вы можете построить сравнительно сложную иерархию объектов VM, которая несколько замедляет обработку ситуаций отсутствия страниц памяти, и к тому же тратится память на управление структурами объектов VM. Приемы оптимизации, применяемые во FreeBSD, позволяют снизить значимость этих проблем до степени, когда их можно без особых потерь игнорировать. [[swap-layers]] == Уровни области подкачки Страницы с собственными данными первоначально являются страницами, копируемыми при записи или заполняемыми нулями. Когда выполняется изменение, и, соответственно, копирование, начальное хранилище объекта (обычно файл) не может больше использоваться для хранения копии страницы, когда VM-системе нужно использовать ее повторно для других целей. В этот момент на помощь приходит область подкачки. Область подкачки выделяется для организации хранилища памяти, которая иначе не может быть доступна. FreeBSD создает структуру управления подкачкой для объекта VM, только когда это действительно нужно. Однако структура управления подкачкой исторически имела некоторые проблемы: * Во FreeBSD 3.X в структуре управления областью подкачки предварительно выделяется массив, который представляет целый объект, требующий хранения в области подкачки-даже если только несколько страниц этого объекта хранятся в области подкачки. Это создает проблему фрагментации памяти ядра в случае, когда в память отображаются большие объекты или когда ветвятся процессы, занимающие большой объем памяти при работе (RSS). * Также для отслеживания памяти подкачки в памяти ядра поддерживается ""список дыр"", и он также несколько фрагментирован. Так как ""список дыр"" является последовательным списком, то производительность при распределении и высвобождении памяти в области подкачки неоптимально и ее сложность зависит от количества страниц как O(n). * Также в процессе высвобождения памяти в области подкачки требуется выделение памяти в ядре, и это приводит к проблемам блокировки при недостатке памяти. * Проблема еще более обостряется из-за дыр, создаваемых по чередующемуся алгоритму. * Кроме того, список распределения блоков в области подкачки легко оказывается фрагментированным, что приводит к распределению непоследовательных областей. * Память ядра также должна распределяться по ходу работы для дополнительных структур по управлению областью подкачки при выгрузке страниц памяти в эту область. Очевидно, что мест для усовершенствований предостаточно. Во FreeBSD 4.X подсистема управления областью подкачки была полностью переписана мною: * Структуры управления областью подкачки распределяются при помощи хэш-таблицы, а не через линейный массив, что дает им фиксированный размер при распределении и работу с гораздо меньшими структурами. * Вместо того, чтобы использовать однонаправленный связный список для отслеживания выделения пространства в области подкачки, теперь используется побитовая карта блоков области подкачки, выполненная в основном в виде древовидной структуры с информацией о свободном пространстве, находящейся в узлах структур. Это приводит к тому, что выделение и высвобождение памяти в области подкачки становится операцией сложности O(1). * Все дерево также распределяется заранее для того, чтобы избежать распределения памяти ядра во время операций с областью подкачки при критически малом объеме свободной памяти. В конце концов, система обращается к области подкачки при нехватке памяти, так что мы должны избежать распределения памяти ядра в такие моменты для избежания потенциальных блокировок. * Для уменьшения фрагментации дерево может распределять большой последовательный кусок за раз, пропуская меньшие фрагментированные области. Я не сделал последний шаг к заведению ""указателя на распределение"", который будет передвигаться по участку области подкачки при выделении памяти для обеспечения в будущем распределения последовательных участков, или по крайней мере местоположения ссылки, но я убежден, что это может быть сделано. [[freeing-pages]] == Когда освобождать страницу Так как система VM использует всю доступную память для кэширования диска, то обычно действительно незанятых страниц очень мало. Система VM зависит от того, как она точно выбирает незанятые страницы для повторного использования для новых распределений. Оптимальный выбор страниц для высвобождения, возможно, является самой важной функцией любой VM-системы, из тех, что она может выполнять, потому что при неправильном выборе система VM вынуждена будет запрашивать страницы с диска, значительно снижая производительность всей системы. Какую дополнительную нагрузку мы может выделить в критическом пути для избежания высвобождения не той страницы? Каждый неправильный выбор будет стоить нам сотни тысяч тактов работы центрального процессора и заметное замедление работы затронутых процессов, так что мы должны смириться со значительными издержками для того, чтобы была заведомо выбрана правильная страница. Вот почему FreeBSD превосходит другие системы в производительности при нехватке ресурсов памяти. Алгоритм определения свободной страницы написан на основе истории использования страниц памяти. Для получения этой истории система использует возможности бита использования памяти, которые имеются в большинстве аппаратных таблицах страниц памяти. В любом случае, бит использования страницы очищается, и в некоторый более поздний момент VM-система обращается к странице снова и обнаруживает, что этот бит установлен. Это указывает на то, что страница активно используется. Периодически проверяя этот бит, накапливается история использования (в виде счетчика) физической страницы. Когда позже VM-системе требуется высвободить некоторые страницы, проверка истории выступает указателем при определении наиболее вероятной кандидатуры для повторного использования. Для тех платформ, что не имеют этой возможности, система эмулирует этот бит. Она снимает отображение или защищает страницу, что приводит к ошибке доступа к странице, если к странице выполняется повторное обращение. При возникновении этой ошибки система просто помечает страницу как используемую и снимает защиту со страницы, так что она может использоваться. Хотя использование такого приема только для определения использования страницы весьма накладно, это выгоднее, чем повторно использовать страницу для других целей и обнаружить, что она снова нужна процессу и подгружать ее с диска. FreeBSD использует несколько очередей страниц для обновления выбора страниц для повторного использования, а также для определения того, когда же грязные страницы должны быть сброшены в хранилище. Так как таблицы страниц во FreeBSD являются динамическими объектами, практически ничего не стоит вырезать страницу из адресного пространства любого использующего ее процесса. После того, как подходящая страница, на основе счетчика использования, выбрана, именно это и выполняется. Система должна отличать между чистыми страницами, которые теоретически могут быть высвобождены в любое время, и грязными страницами, которые сначала должны быть переписаны в хранилище перед тем, как их можно будет использовать повторно. После нахождения подходящей страницы она перемещается в неактивную очередь, если она является грязной, или в очередь кэша, если она чистая. Отдельный алгоритм, основывающийся на отношении количества грязных страниц к чистым, определяет, когда грязные страницы в неактивной очереди должны быть сброшены на диск. Когда это выполнится, сброшенные страницы перемещаются из неактивной очереди в очередь кэша. В этот момент страницы в очереди кэша могут быть повторно активизированы VM со сравнительно малыми накладными расходами. Однако страницы в очереди кэша предполагается ""высвобождать немедленно"" и повторно использовать в LRU-порядке (меньше всего используемый), когда системе потребуется выделение дополнительной памяти. Стоит отметить, что во FreeBSD VM-система пытается разделить чистые и грязные страницы во избежание срочной необходимости в ненужных сбросах грязных страниц (что отражается на пропускной способности ввода/вывода) и не перемещает беспричинно страницы между разными очередями, когда подсистема управления памятью не испытывает нехватку ресурсов. Вот почему вы можете видеть, что при выполнении команды `systat -vm` в некоторых системах значение счетчика очереди кэша мало, а счетчик активной очереди большой. При повышении нагрузки на VM-систему она прилагает большие усилия на поддержку различных очередей страниц в соотношениях, которые являются наиболее эффективными. Годами ходили современные легенды, что Linux выполняет работу по предотвращению выгрузки на диск лучше, чем FreeBSD, но это не так. На самом деле FreeBSD старается сбросить на диск неиспользуемые страницы для освобождения места под дисковый кэш, когда как Linux хранит неиспользуемые страницы в памяти и оставляет под кэш и страницы процессов меньше памяти. Я не знаю, остается ли это правдой на сегодняшний день. [[prefault-optimizations]] == Оптимизация ошибок доступа к страницам и их обнуления Полагая, что ошибка доступа к странице памяти в VM не является операцией с большими накладными расходами, если страница уже находится в основной памяти и может быть просто отображена в адресное пространство процесса, может оказаться, что это станет весьма накладно, если их будет оказываться регулярно много. Хорошим примером этой ситуации является запуск таких программ, как man:ls[1] или man:ps[1], снова и снова. Если бинарный файл программы отображен в память, но не отображен в таблицу страниц, то все страницы, к которым обращалась программа, окажутся недоступными при каждом запуске программы. Это не так уж необходимо, если эти страницы уже присутствуют в кэше VM, так что FreeBSD будет пытаться восстанавливать таблицы страниц процесса из тех страниц, что уже располагаются в VM-кэше. Однако во FreeBSD пока не выполняется предварительное копирование при записи определенных страниц при выполнении вызова exec. Например, если вы запускаете программу man:ls[1] одновременно с работающей `vmstat 1`, то заметите, что она всегда выдает некоторое количество ошибок доступа к страницам, даже когда вы запускаете ее снова и снова. Это ошибки заполнения нулями, а не ошибки кода программы (которые уже были обработаны). Предварительное копирование страниц при выполнении вызовов exec или fork находятся в области, требующей более тщательного изучения. Большой процент ошибок доступа к страницам, относится к ошибкам при заполнении нулями. Вы можете обычно видеть это, просматривая вывод команды `vmstat -s`. Это происходит, когда процесс обращается к страницам в своей области BSS. Область BSS предполагается изначально заполненной нулями, но VM-система не заботится о выделении памяти до тех пор, пока процесс реально к ней не обратится. При возникновении ошибки VM-система должна не только выделить новую страницу, но и заполнить ее нулями. Для оптимизации операции по заполнению нулями в системе VM имеется возможность предварительно обнулять страницы и помечать их, и запрашивать уже обнуленные страницы при возникновении ошибок заполнения нулями. Предварительное заполнение нулями происходит, когда CPU простаивает, однако количество страниц, которые система заранее заполняет нулями, ограничено, для того, чтобы не переполнить кэши памяти. Это прекрасный пример добавления сложности в VM-систему ради оптимизации критического пути. [[pre-table-optimizations]] == Оптимизация таблицы страниц Оптимизация таблицы страниц составляет самую содержательную часть архитектуры VM во FreeBSD и она проявляется при появлении нагрузки при значительном использовании `mmap()`. Я думаю, что это на самом деле особенность работы большинства BSD-систем, хотя я не уверен, когда это проявилось впервые. Есть два основных подхода к оптимизации. Первый заключается в том, что аппаратные таблицы страниц не содержат постоянного состояния, а вместо этого могут быть сброшены в любой момент с малыми накладными расходами. Второй подход состоит в том, что каждая активная таблица страниц в системе имеет управляющую структуру `pv_entry`, которая связана в структуру `vm_page`. FreeBSD может просто просматривать эти отображения, которые существуют, когда как в Linux должны проверяться все таблицы страниц, которые _могут_ содержать нужное отображение, что в некоторых ситуация дает увеличение сложности O(n^2). Из-за того, что FreeBSD стремится выбрать наиболее подходящую к повторному использованию или сбросу в область подкачки страницу, когда ощущается нехватка памяти, система дает лучшую производительность при нагрузке. Однако во FreeBSD требуется тонкая настройка ядра для соответствия ситуациям с большим совместно используемым адресным пространством, которые могут случиться в системе, обслуживающей сервер телеконференций, потому что структуры `pv_entry` могут оказаться исчерпанными. И в Linux, и во FreeBSD требуются доработки в этой области. FreeBSD пытается максимизировать преимущества от потенциально редко применяемой модели активного отображения (к примеру, не всем процессам нужно отображать все страницы динамической библиотеки), когда как Linux пытается упростить свои алгоритмы. FreeBSD имеет здесь общее преимущество в производительности за счет использования дополнительной памяти, но FreeBSD выглядит хуже в случае, когда большой файл совместно используется сотнями процессов. Linux, с другой стороны, выглядит хуже в случае, когда много процессов частично используют одну и ту же динамическую библиотеку, а также работает неоптимально при попытке определить, может ли страница повторно использоваться, или нет. [[page-coloring-optimizations]] == Подгонка страниц Мы закончим рассмотрением метода оптимизации подгонкой страниц. Подгонка является методом оптимизации, разработанным для того, чтобы доступ в последовательные страницы виртуальной памяти максимально использовал кэш процессора. В далеком прошлом (то есть больше 10 лет назад) процессорные кэши предпочитали отображать виртуальную память, а не физическую. Это приводило к огромному количеству проблем, включая необходимость очистки кэша в некоторых случаях при каждом переключении контекста и проблемы с замещением данных в кэше. В современных процессорах кэши отображают физическую память именно для решения этих проблем. Это означает, что две соседние страницы в адресном пространстве процессов могут не соответствовать двух соседним страницам в кэше. Фактически, если вы об этом не позаботились, то соседние страницы в виртуальной памяти могут использовать ту же самую страницу в кэше процессора-это приводит к сбросу кэшируемых данных и снижению производительности CPU. Это так даже с множественными ассоциативными кэшами (хотя здесь эффект несколько сглажен). Код выделения памяти во FreeBSD выполняет оптимизацию с применением подгонки страниц, означающую то, что код выделения памяти будет пытаться найти свободные страницы, которые являются последовательными с точки зрения кэша. Например, если страница 16 физической памяти назначается странице 0 виртуальной памяти процесса, а в кэш помещается 4 страницы, то код подгонки страниц не будет назначать страницу 20 физической памяти странице 1 виртуальной памяти процесса. Вместо этого будет назначена страница 21 физической памяти. Код подгонки страниц попытается избежать назначение страницы 20, потому что такое отображение перекрывается в той же самой памяти кэша как страница 16, и приведет к неоптимальному кэшированию. Как вы можете предположить, такой код значительно добавляет сложности в подсистему выделения памяти VM, но результат стоит того. Подгонка страниц делает память VM предсказуемой, как и обычная физическая память, относительно производительности кэша. [[conclusion]] == Заключение Виртуальная память в современных операционных системах должна решать несколько различных задач эффективно и при разных условиях. Модульный и алгоритмический подход, которому исторически следует BSD, позволяет нам изучить и понять существующую реализацию, а также сравнительно легко изменить большие блоки кода. За несколько последних лет в VM-системе FreeBSD было сделано некоторое количество усовершенствований, и работа над ними продолжается. [[allen-briggs-qa]] == Дополнительный сеанс вопросов и ответов от Аллена Бриггса (Allen Briggs) === Что это за алгоритм чередования, который вы упоминали в списке недостатков подсистемы управления разделом подкачки во FreeBSD 3.X? FreeBSD использует в области подкачки механизм чередования, с индексом по умолчанию, равным четырем. Это означает, что FreeBSD резервирует пространство для четырех областей подкачки, даже если у вас имеется всего лишь одна, две или три области. Так как в области подкачки имеется чередование, то линейное адресное пространство, представляющее ""четыре области подкачки"", будет фрагментироваться, если у вас нет на самом деле четырех областей подкачки. Например, если у вас две области A и B, то представление адресного пространства для этой области подкачки во FreeBSD будет организовано с чередованием блоков из 16 страниц: .... A B C D A B C D A B C D A B C D .... FreeBSD 3.X использует ""последовательный список свободных областей"" для управления свободными областями в разделе подкачки. Идея состоит в том, что большие последовательные блоки свободного пространства могут быть представлены при помощи узла односвязного списка ([.filename]#kern/subr_rlist.c#). Но из-за фрагментации последовательный список сам становится фрагментированным. В примере выше полностью неиспользуемое пространство в A и B будет показано как ""свободное"", а C и D как ""полностью занятое"". Каждой последовательности A-B требуется для учета узел списка, потому что C и D являются дырами, так что узел списка не может быть связан со следующей последовательностью A-B. Почему мы организуем чередование в области подкачки вместо того, чтобы просто объединить области подкачки в одно целое и придумать что-то более умное? Потому что гораздо легче выделять последовательные полосы адресного пространства и получать в результате автоматическое чередование между несколькими дисками, чем пытаться выдумывать сложности в другом месте. Фрагментация вызывает другие проблемы. Являясь последовательным списком в 3.X и имея такое огромную фрагментацию, выделение и освобождение в области подкачки становится алгоритмом сложности O(N), а не O(1). Вместе с другими факторами (частое обращение к области подкачки) вы получаете сложность уровней O(N^2) и O(N^3), что плохо. В системе 3.X также может потребоваться выделение KVM во время работы с областью подкачки для создания нового узла списка, что в условии нехватки памяти может привести к блокировке, если система попытается сбросить страницы в область подкачки. В 4.X мы не используем последовательный список. Вместо этого мы используем базисное дерево и битовые карты блоков области подкачки, а не ограниченный список узлов. Мы принимаем предварительное выделение всех битовых карт, требуемых для всей области подкачки, но при этом тратится меньше памяти, потому что мы используем битовые карты (один бит на блок), а не связанный список узлов. Использование базисного дерева вместо последовательного списка дает нам производительность O(1) вне зависимости от фрагментации дерева. === Как разделение чистых и грязных (неактивных) страниц связано с ситуацией, когда вы видите маленький счетчик очереди кэша и большой счетчик активной очереди в выдаче команды systat -vm? Разве системная статистика не считает активные и грязные страницы вместе за счетчик активной очереди? Да, это запутывает. Связь заключается в ""желаемом"" и ""действительном"". Мы желаем разделить страницы, но реальность такова, что пока у нас нет проблем с памятью, нам это на самом деле не нужно. Это означает, что FreeBSD не будет очень сильно стараться над отделением грязных страниц (неактивная очередь) от чистых страниц (очередь кэша), когда система не находится под нагрузкой, и не будет деактивировать страницы (активная очередь -> неактивная очередь), когда система не нагружена, даже если они не используются. === В примере с / vmstat 1 могут ли некоторые ошибки доступа к странице быть ошибками страниц данных (COW из выполнимого файла в приватные страницы)? То есть я полагаю, что ошибки доступа к страницам являются частично ошибками при заполнении нулями, а частично данных программы. Или вы гарантируете, что FreeBSD выполняет предварительно COW для данных программы? Ошибка COW может быть ошибкой при заполнении нулями или данных программы. Механизм в любом случае один и тот же, потому что хранилище данных программы уже в кэше. Я на самом деле не рад ни тому, ни другому. FreeBSD не выполняет предварительное COW данных программы и заполнение нулями, но она _выполняет_ предварительно отображение страниц, которые имеются в ее кэше. === В вашем разделе об оптимизации таблицы страниц, не могли бы вы более подробно рассказать о pv_entry и vm_page (или vm_page должна быть vm_pmap-как в 4.4, cf. pp. 180-181 of McKusick, Bostic, Karel, Quarterman)? А именно какое действие/реакцию должно потребоваться для сканирования отображений? `vm_page` представляет собой пару (object,index#). `pv_entry` является записью из аппаратной таблицы страниц (pte). Если у вас имеется пять процессов, совместно использующих одну и ту же физическую страницу, и в трех таблицах страниц этих процессов на самом деле отображается страница, то страница будет представляться одной структурой `vm_page` и тремя структурами `pv_entry`. Структуры `pv_entry` представляют страницы, отображаемые MMU (одна структура `pv_entry` соответствует одной pte). Это означает, что, когда нам нужно убрать все аппаратные ссылки на `vm_page` (для того, чтобы повторно использовать страницу для чего-то еще, выгрузить ее, очистить, пометить как грязную и так далее), мы можем просто просмотреть связный список структур `pv_entry`, связанных с этой `vm_page`, для того, чтобы удалить или изменить pte из их таблиц страниц. В Linux нет такого связного списка. Для того, чтобы удалить все отображения аппаратной таблицы страниц для `vm_page`, linux должен пройти по индексу каждого объекта VM, который _может_ отображать страницу. К примеру, если у вас имеется 50 процессов, которые все отображают ту же самую динамическую библиотеку и хотите избавиться от страницы X в этой библиотеке, то вам нужно пройтись по индексу всей таблицы страниц для каждого из этих 50 процессов, даже если только 10 из них на самом деле отображают страницу. Так что Linux использует простоту подхода за счет производительности. Многие алгоритмы VM, которые имеют сложность O(1) или (N малое) во FreeBSD, в Linux приобретают сложность O(N), O(N^2) или хуже. Так как pte, представляющий конкретную страницу в объекте, скорее всего, будет с тем же смещением во всех таблицах страниц, в которых они отображаются, то уменьшение количества обращений в таблицы страниц по тому же самому смещению часто позволяет избежать разрастания кэша L1 для этого смещения, что приводит к улучшению производительности. Во FreeBSD введены дополнительные сложности (схема с `pv_entry`) для увеличения производительности (уменьшая количество обращений _только_ к тем pte, которые нужно модифицировать). Но во FreeBSD имеется проблема масштабирования, которой нет в Linux, потому что имеется ограниченное число структур `pv_entry`, и это приводит к возникновению проблем при большом объеме совместно используемых данных. В этом случае у вас может возникнуть нехватка структур `pv_entry`, даже если свободной памяти хватает. Это может быть достаточно легко исправлено увеличением количества структур `pv_entry` при настройке, но на самом деле нам нужно найти лучший способ делать это. Что касается использования памяти под таблицу страниц против схемы с `pv_entry`: Linux использует ""постоянные"" таблицы страниц, которые не сбрасываются, но ему не нужны `pv_entry` для каждого потенциально отображаемого pte. FreeBSD использует ""сбрасываемые"" таблицы страниц, но для каждого реально отображаемого pte добавляется структура `pv_entry`. Я думаю, что использование памяти будет примерно одинакова, тем более что у FreeBSD есть алгоритмическое преимущество, заключающееся в способности сбрасывать таблицы страниц с очень малыми накладными расходами. === Наконец, в разделе о подгонке страниц хорошо бы было иметь краткое описание того, что это значит. Я не совсем это понял. Знаете ли вы, как работает аппаратный кэш памяти L1? Объясняю: Представьте машину с 16МБ основной памяти и только со 128К памяти кэша L1. В общем, этот кэш работает так, что каждый блок по 128К основной памяти использует _те же самые_ 128К кэша. Если вы обращаетесь к основной памяти по смещению 0, а затем к основной памяти по смещению 128К, вы перезаписываете данные кэша, прочтенные по смещению 0! Я очень сильно все упрощаю. То, что я только что описал, называется ""напрямую отображаемым"" аппаратным кэшем памяти. Большинство современных кэшей являются так называемыми 2-сторонними множественными ассоциативными или 4-сторонними множественными ассоциативными кэшами. Множественная ассоциативность позволяет вам обращаться к вплоть до N различным областям памяти, которые используют одну и ту же память кэша без уничтожения ранее помещенных в кэш данных. Но только N. Так что если у меня имеется 4-сторонний ассоциативный кэш, я могу обратиться к памяти по смещению 0, смещению 128К, 256К и смещению 384K, затем снова обратиться к памяти по смещению 0 и получу ее из кэша L1. Однако, если после этого я обращусь к памяти по смещению 512К, один из ранее помещенных в кэш объектов данных будет из кэша удален. Это чрезвычайно важно... для большинства обращений к памяти процессора _чрезвычайно_ важно, чтобы данные находились в кэше L1, так как кэш L1 работает на тактовой частоте работы процессора. В случае, если данных в кэше L1 не обнаруживается, и они ищутся в кэше L2 или в основной памяти, процессор будет простаивать, или, скорее, сидеть, сложив ручки, в ожидании окончания чтения из основной памяти, хотя за это время можно было выполнить _сотни_ операций. Основная память (динамическое ОЗУ, которое установлено в компьютере) работает по сравнению со скоростью работы ядра современных процессоров __медленно__. Хорошо, а теперь рассмотрим подгонку страниц: Все современные кэши памяти являются так называемыми _физическими_ кэшами. Они кэшируют адреса физической памяти, а не виртуальной. Это позволяет кэшу не принимать во внимание переключение контекстов процессов, что очень важно. Но в мире UNIX(R) вы работаете с виртуальными адресными пространствами, а не с физическими. Любая программа, вами написанная, имеет дело с виртуальным адресным пространством, ей предоставленным. Реальные _физические_ страницы, соответствующие виртуальному адресному пространству, не обязательно расположены физически последовательно! На самом деле у вас могут оказаться две страницы, которые в адресном пространстве процессов являются граничащими, но располагающимися по смещению 0 и по смещению 128К в _физической_ памяти. Обычно программа полагает, что две граничащие страницы будут кэшироваться оптимально. То есть вы можете обращаться к объектам данных в обеих страницах без замещений в кэше данных друг друга. Но это имеет место, если только физические страницы, соответствующие виртуальному адресному пространству, располагаются рядом (в такой мере, что попадают в кэш). Это именно то, что выполняет подгонка. Вместо того, чтобы назначать _случайные_ физические страницы виртуальным адресам, что может привести к неоптимальной работе кэша, при подгонке страниц виртуальным адресам назначаются _примерно подходящие по порядку_ физические страницы. Таким образом, программы могут писаться в предположении, что характеристики низлежащего аппаратного кэша для виртуального адресного пространства будут такими же, как если бы программа работала непосредственно в физическом адресном пространстве. Заметьте, что я сказал ""примерно"" подходящие, а не просто ""последовательные"". С точки зрения напрямую отображаемого кэша в 128К, физический адрес 0 одинаков с физическим адресом 128К. Так что две граничащие страницы в вашем виртуальном адресном пространстве могут располагаться по смещению 128К и 132К физической памяти, но могут легко находиться по смещению 128К и по смещению 4К физической памяти, и иметь те же самые характеристики работы кэша. Так что при подгонке _не нужно_ назначать в действительности последовательные страницы физической памяти последовательным страницам виртуальной памяти, достаточно просто добиться расположения страниц по соседству друг с другом с точки зрения работы кэша. ",12340,False,2068.6631562497355,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc //// = Using OpenID Connect (OIDC) to Protect Web Applications using Authorization Code Flow. include::./attributes.adoc[] :toc: This guide demonstrates how to use Quarkus OpenID Connect (OIDC) Extension to protect your Quarkus HTTP endpoints using OpenId Connect Authorization Code Flow supported by OpenId Connect compliant Authorization Servers such as https://www.keycloak.org/about.html[Keycloak]. The extension allows to easily authenticate the users of your web application by redirecting them to the OpenID Connect Provider (e.g.: Keycloak) to login and, once the authentication is complete, return them back with the code confirming the successful authentication. The extension will request ID and access tokens from the OpenID Connect Provider using an authorization code grant and verify these tokens in order to authorize an access to the application. Please read the link:security-openid-connect[Using OpenID Connect to Protect Service Applications] guide if you need to protect your applications using Bearer Token Authorization. Please read the link:security-openid-connect-multitenancy[Using OpenID Connect Multi-Tenancy] guide how to support multiple tenants. == Prerequisites To complete this guide, you need: * less than 15 minutes * an IDE * JDK 11+ installed with `JAVA_HOME` configured appropriately * Apache Maven {maven-version} * https://stedolan.github.io/jq/[jq tool] * Docker == Architecture In this example, we build a very simple web application with a single page: * `/index.html` This page is protected and can only be accessed by authenticated users. == Solution We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example. Clone the Git repository: `git clone {quickstarts-clone-url}`, or download an {quickstarts-archive-url}[archive]. The solution is located in the `security-openid-connect-web-authentication-quickstart` {quickstarts-tree-url}/security-openid-connect-web-authentication-quickstart[directory]. == Creating the Maven Project First, we need a new project. Create a new project with the following command: [source,bash,subs=attributes+] ---- mvn io.quarkus.platform:quarkus-maven-plugin:{quarkus-version}:create \\ -DprojectGroupId=org.acme \\ -DprojectArtifactId=security-openid-connect-web-authentication-quickstart \\ -Dextensions=""resteasy,oidc"" \\ -DnoExamples cd security-openid-connect-web-authentication-quickstart ---- If you already have your Quarkus project configured, you can add the `oidc` extension to your project by running the following command in your project base directory: [source,bash] ---- ./mvnw quarkus:add-extension -Dextensions=""oidc"" ---- This will add the following to your `pom.xml`: [source,xml] ---- io.quarkus quarkus-oidc ---- == Writing the application Let's write a simple JAX-RS resource which has all the tokens returned in the authorization code grant response injected: [source,java] ---- package org.acme.security.openid.connect.web.authentication; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.eclipse.microprofile.jwt.JsonWebToken; import io.quarkus.oidc.IdToken; import io.quarkus.oidc.RefreshToken; @Path(""/tokens"") public class TokenResource { /** * Injection point for the ID Token issued by the OpenID Connect Provider */ @Inject @IdToken JsonWebToken idToken; /** * Injection point for the Access Token issued by the OpenID Connect Provider */ @Inject JsonWebToken accessToken; /** * Injection point for the Refresh Token issued by the OpenID Connect Provider */ @Inject RefreshToken refreshToken; /** * Returns the tokens available to the application. This endpoint exists only for demonstration purposes, you should not * expose these tokens in a real application. * * @return a map containing the tokens available to the application */ @GET public String getTokens() { StringBuilder response = new StringBuilder().append("""") .append("""") .append(""
    ""); Object userName = this.idToken.getClaim(""preferred_username""); if (userName != null) { response.append(""
  • username: "").append(userName.toString()).append(""
  • ""); } Object scopes = this.accessToken.getClaim(""scope""); if (scopes != null) { response.append(""
  • scopes: "").append(scopes.toString()).append(""
  • ""); } response.append(""
  • refresh_token: "").append(refreshToken.getToken() != null).append(""
  • ""); return response.append(""
"").append("""").append("""").toString(); } } ---- This endpoint has ID, access and refresh tokens injected. It returns a `preferred_username` claim from the ID token, a `scope` claim from the access token and also a refresh token availability status. Note that you do not have to inject the tokens - it is only required if the endpoint needs to use the ID token to interact with the currently authenticated user or use the access token to access a downstream service on behalf of this user. Please see <> section below for more information. == Configuring the application The OpenID Connect extension allows you to define the configuration using the `application.properties` file which should be located at the `src/main/resources` directory. === Configuring using the application.properties file [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus quarkus.oidc.client-id=frontend quarkus.oidc.application-type=web-app quarkus.http.auth.permission.authenticated.paths=/* quarkus.http.auth.permission.authenticated.policy=authenticated ---- This is the simplest configuration you can have when enabling authentication to your application. The `quarkus.oidc.client-id` property references the `client_id` issued by the OpenID Connect Provider and, in this case, the application is a public client (no client secret is defined). The `quarkus.oidc.application-type` property is set to `web-app` in order to tell Quarkus that you want to enable the OpenID Connect Authorization Code Flow, so that your users are redirected to the OpenID Connect Provider to authenticate. For last, the `quarkus.http.auth.permission.authenticated` permission is set to tell Quarkus about the paths you want to protect. In this case, all paths are being protected by a policy that ensures that only `authenticated` users are allowed to access. For more details check link:security-authorization[Security Authorization Guide]. === Configuring CORS If you plan to consume this application from another application running on a different domain, you will need to configure CORS (Cross-Origin Resource Sharing). Please read the link:http-reference#cors-filter[HTTP CORS documentation] for more details. == Starting and Configuring the Keycloak Server To start a Keycloak Server you can use Docker and just run the following command: [source,bash,subs=attributes+] ---- docker run --name keycloak -e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin -p 8180:8080 {keycloak-docker-image} ---- You should be able to access your Keycloak Server at http://localhost:8180/auth[localhost:8180/auth]. Log in as the `admin` user to access the Keycloak Administration Console. Username should be `admin` and password `admin`. Import the {quickstarts-tree-url}/security-openid-connect-web-authentication-quickstart/config/quarkus-realm.json[realm configuration file] to create a new realm. For more details, see the Keycloak documentation about how to https://www.keycloak.org/docs/latest/server_admin/index.html#_create-realm[create a new realm]. == Running and Using the Application === Running in Developer Mode To run the microservice in dev mode, use `./mvnw clean compile quarkus:dev`. === Running in JVM Mode When you're done playing with ""dev-mode"" you can run it as a standard Java application. First compile it: [source,bash] ---- ./mvnw package ---- Then run it: [source,bash] ---- java -jar target/quarkus-app/quarkus-run.jar ---- === Running in Native Mode This same demo can be compiled into native code: no modifications required. This implies that you no longer need to install a JVM on your production environment, as the runtime technology is included in the produced binary, and optimized to run with minimal resource overhead. Compilation will take a bit longer, so this step is disabled by default; let's build again by enabling the `native` profile: [source,bash] ---- ./mvnw package -Pnative ---- After getting a cup of coffee, you'll be able to run this binary directly: [source,bash] ---- ./target/security-openid-connect-web-authentication-quickstart-runner ---- == Testing the Application To test the application, you should open your browser and access the following URL: * http://localhost:8080[http://localhost:8080] If everything is working as expected, you should be redirected to the Keycloak server to authenticate. In order to authenticate to the application you should type the following credentials when at the Keycloak login page: * Username: *alice* * Password: *alice* After clicking the `Login` button you should be redirected back to the application. == Redirection When the user is redirected to the OpenID Connect Provider to authenticate, the redirect URL includes a `redirect_uri` query parameter which indicates to the Provider where the user has to be redirected to once the authentication has been completed. Quarkus will set this parameter to the current request URL by default. For example, if the user is trying to access a Quarkus service endpoint at `http://localhost:8080/service/1` then the `redirect_uri` parameter will be set to `http://localhost:8080/service/1`. Similarly, if the request URL is `http://localhost:8080/service/2` then the `redirect_uri` parameter will be set to `http://localhost:8080/service/2`, etc. OpenID Connect Providers may be configured to require the `redirect_uri` parameter to have the same value (eg. `http://localhost:8080/service/callback`) for all the redirect URLs. In such cases a `quarkus.oidc.authentication.redirect-path` property has to be set, for example, `quarkus.oidc.authentication.redirect-path=/service/callback`, and Quarkus will set the `redirect_uri` parameter to an absolute URL such as `http://localhost:8080/service/callback` which will be the same regardless of the current request URL. If `quarkus.oidc.authentication.redirect-path` is set but the original request URL has to be restored after the user has been redirected back to a callback URL such as `http://localhost:8080/service/callback` then a `quarkus.oidc.authentication.restore-path-after-redirect` property has to be set to `true` which will restore the request URL such as `http://localhost:8080/service/1`, etc. [[oidc-cookies]] == Dealing with Cookies The OIDC adapter uses cookies to keep the session, code flow and post logout state. `quarkus.oidc.authentication.cookie-path` property is used to ensure the cookies are visible especially when you access the protected resources with overlapping or different roots, for example: * `/index.html` and `/web-app/service` * `/web-app/service1` and `/web-app/service2` * `/web-app1/service` and `/web-app2/service` `quarkus.oidc.authentication.cookie-path` is set to `/` by default but can be narrowed to the more specific root path such as `/web-app`. You can also set a `quarkus.oidc.authentication.cookie-path-header` property if the cookie path needs to be set dynamically. For example, setting `quarkus.oidc.authentication.cookie-path-header=X-Forwarded-Prefix` means that the value of HTTP `X-Forwarded-Prefix` header will be used to set a cookie path. If `quarkus.oidc.authentication.cookie-path-header` is set but no configured HTTP header is available in the current request then the `quarkus.oidc.authentication.cookie-path` will be checked. If your application is deployed across multiple domains, make sure to set a `quarkus.oidc.authentication.cookie-domain` property for the session cookie be visible to all protected Quarkus services, for example, if you have 2 services deployed at: * https://whatever.wherever.company.net/ * https://another.address.company.net/ then the `quarkus.oidc.authentication.cookie-domain` property must be set to `company.net`. == Logout By default the logout is based on the expiration time of the ID Token issued by the OpenID Connect Provider. When the ID Token expires, the current user session at the Quarkus endpoint is invalidated and the user is redirected to the OpenID Connect Provider again to authenticate. If the session at the OpenID Connect Provider is still active, users are automatically re-authenticated without having to provide their credentials again. The current user session may be automatically extended by enabling a `quarkus.oidc.token.refresh-expired` property. If it is set to `true` then when the current ID Token expires a Refresh Token Grant will be used to refresh ID Token as well as Access and Refresh Tokens. === User-Initiated Logout Users can request a logout by sending a request to the Quarkus endpoint logout path set with a `quarkus.oidc.logout.path` property. For example, if the endpoint address is `https://application.com/webapp` and the `quarkus.oidc.logout.path` is set to ""/logout"" then the logout request has to be sent to `https://application.com/webapp/logout`. This logout request will start an https://openid.net/specs/openid-connect-session-1_0.html#RPLogout[RP-Initiated Logout] and the user will be redirected to the OpenID Connect Provider to logout where a user may be asked to confirm the logout is indeed intended. The user will be returned to the endpoint post logout page once the logout has been completed if the `quarkus.oidc.logout.post-logout-path` property is set. For example, if the endpoint address is `https://application.com/webapp` and the `quarkus.oidc.logout.post-logout-path` is set to ""/signin"" then the user will be returned to `https://application.com/webapp/signin` (note this URI must be registered as a valid `post_logout_redirect_uri` in the OpenID Connect Provider). If the `quarkus.oidc.logout.post-logout-path` is set then a `q_post_logout` cookie will be created and a matching `state` query parameter will be added to the logout redirect URI and the OpenID Connect Provider will return this `state` once the logout has been completed. It is recommended for the Quarkus `web-app` applications to check that a `state` query parameter matches the value of the `q_post_logout` cookie which can be done for example in a JAX-RS filter. Note that a cookie name will vary when using link:security-openid-connect-multitenancy[OpenID Connect Multi-Tenancy]. For example, it will be named `q_post_logout_tenant_1` for a tenant with a `tenant_1` id, etc. Here is an example of how to configure an RP initiated logout flow: [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus quarkus.oidc.client-id=frontend quarkus.oidc.application-type=web-app quarkus.oidc.tenant-logout.logout.path=/logout quarkus.oidc.tenant-logout.logout.post-logout-path=/postlogout # Only the authenticated users can initiate a logout: quarkus.http.auth.permission.authenticated.paths=/logout quarkus.http.auth.permission.authenticated.policy=authenticated # Logged out users should be returned to the /welcome.html site which will offer an option to re-login: quarkus.http.auth.permission.authenticated.paths=/welcome.html quarkus.http.auth.permission.authenticated.policy=permit ---- You may also need to set `quarkus.oidc.authentication.cookie-path` to a path value common to all of the application resources which is `/` in this example. See <> for more information. [[access_id_and_access_tokens]] == Accessing ID and Access Tokens OIDC Code Authentication Mechanism acquires three tokens during the authorization code flow: https://openid.net/specs/openid-connect-core-1_0.html#IDToken[IDToken], Access Token and Refresh Token. ID Token is always a JWT token and is used to represent a user authentication with the JWT claims. One can access ID Token claims by injecting `JsonWebToken` with an `IdToken` qualifier: [source, java] ---- import javax.inject.Inject; import org.eclipse.microprofile.jwt.JsonWebToken; import io.quarkus.oidc.IdToken; import io.quarkus.security.Authenticated; @Path(""/web-app"") @Authenticated public class ProtectedResource { @Inject @IdToken JsonWebToken idToken; @GET public String getUserName() { return idToken.getName(); } } ---- Access Token is usually used by the OIDC `web-app` application to access other endpoints on behalf of the currently logged in user. The raw access token can be accessed as follows: [source, java] ---- import javax.inject.Inject; import org.eclipse.microprofile.jwt.JsonWebToken; import io.quarkus.oidc.AccessTokenCredential; import io.quarkus.security.Authenticated; @Path(""/web-app"") @Authenticated public class ProtectedResource { @Inject JsonWebToken accessToken; // or // @Inject // AccessTokenCredential accessTokenCredential; @GET public String getReservationOnBehalfOfUser() { String rawAccessToken = accessToken.getRawToken(); //or //String rawAccessToken = accessTokenCredential.getToken(); // Use the raw access token to access a remote endpoint return getReservationfromRemoteEndpoint(rawAccesstoken); } } ---- Note that `AccessTokenCredential` will have to be used if the Access Token issued to the Quarkus `web-app` application is opaque (binary) and can not be parsed to `JsonWebToken`. Injection of the `JsonWebToken` and `AccessTokenCredential` is supported in both `@RequestScoped` and `@ApplicationScoped` contexts. RefreshToken is only used to refresh the current ID and access tokens as part of its link:#session_management[session management] process. [[user-info]] == User Info If IdToken does not provide enough information about the currently authenticated user then you can set a `quarkus.oidc.user-info-required=true` property for a https://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo] JSON object from the OIDC userinfo endpoint to be requested. A request will be sent to the OpenId Provider UserInfo endpoint using the access token returned with the authorization code grant response and an `io.quarkus.oidc.UserInfo` (a simple `javax.json.JsonObject` wrapper) object will be created. `io.quarkus.oidc.UserInfo` can be either injected or accessed as a SecurityIdentity `userinfo` attribute. [[config-metadata]] == Configuration Metadata The current tenant's discovered link:https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata[OpenId Connect Configuration Metadata] is represented by `io.quarkus.oidc.OidcConfigurationMetadata` and can be either injected or accessed as a `SecurityIdentity` `configuration-metadata` attribute. The default tenant's `OidcConfigurationMetadata` is injected if the endpoint is public. [[token-claims-roles]] == Token Claims And SecurityIdentity Roles The way the roles are mapped to the SecurityIdentity roles from the verified tokens is identical to how it is done for the link:security-openid-connect#token-claims-and-securityidentity-roles[bearer tokens] with the only difference being is that https://openid.net/specs/openid-connect-core-1_0.html#IDToken[ID Token] is used as a source of the roles by default. Note if you use Keycloak then you should set a Microprofile JWT client scope for ID token to contain a `groups` claim, please see the https://www.keycloak.org/docs/latest/server_admin/#protocol[Keycloak Server Administration Guide] for more information. If only the access token contains the roles and this access token is not meant to be propagated to the downstream endpoints then set `quarkus.oidc.roles.source=accesstoken`. If UserInfo is the source of the roles then set `quarkus.oidc.authentication.user-info-required=true` and `quarkus.oidc.roles.source=userinfo`, and if needed, `quarkus.oidc.roles.role-claim-path`. Additionally a custom `SecurityIdentityAugmentor` can also be used to add the roles as documented link:security#security-identity-customization[here]. [[token-verification-introspection]] == Token Verification And Introspection Please see link:security-openid-connect#token-verification-introspection for details about how the tokens are verified and introspected. Note that in case of `web-app` applications only `IdToken` is verified by default since the access token is not used by default to access the current Quarkus `web-app` endpoint and instead meant to be propagated to the services expecting this access token, for example, to the OpenId Connect Provider's UserInfo endpoint, etc. However if you expect the access token to contain the roles required to access the current Quarkus endpoint (`quarkus.oidc.roles.source=accesstoken`) then it will also be verified. [[token-introspection-userinfo-cache]] == Token Introspection and UserInfo Cache Code flow access tokens are not introspected unless they are expected to be the source of roles but will be used to get `UserInfo`. So there will be one or two remote calls with the code flow access token, if the token introspection and/or `UserInfo` are required. Please see link:security-openid-connect#token-introspection-userinfo-cache for more information about using a default token cache or registering a custom cache implementation. [[session-management]] == Session Management If you have a link:security-openid-connect#single-page-applications[Single Page Application for Service Applications] where your OpenId Connect Provider script such as `keycloak.js` is managing an authoriization code flow then that script will also control the SPA authentication session lifespan. If you work with a Quarkus OIDC `web-app` application then it is Quarkus OIDC Code Authentication mechanism which is managing the user session lifespan. The session age is calculated by adding the lifespan value of the current IDToken and the values of the `quarkus.oidc.authentication.session-age-extension` and `quarkus.oidc.token.lifespan-grace` properties. Of the last two properties only `quarkus.oidc.authentication.session-age-extension` should be used to significantly extend the session lifespan if required since `quarkus.oidc.token.lifespan-grace` is only meant for taking some small clock skews into consideration. When the currently authenticated user returns to the protected Quarkus endpoint and the ID token associated with the session cookie has expired then, by default, the user will be auto-redirected to the OIDC Authorization endpoint to re-authenticate. Most likely the OIDC provider will challenge the user again though not necessarily if the session between the user and this OIDC provider is still active which may happen if it is configured to last longer than the ID token. If the `quarkus.oidc.token.refresh-expired` then the expired ID token (as well as the access token) will be refreshed using the refresh token returned with the authorization code grant response. This refresh token may also be recycled (refreshed) itself as part of this process. As a result the new session cookie will be created and the session will be extended. Note, `quarkus.oidc.authentication.session-age-extension` can be important when dealing with expired ID tokens, when the user is not very active. In such cases, if the ID token expires, then the session cookie may not be returned back to the Quarkus endpoint during the next user request and Quarkus will assume it is the first authentication request. Therefore using `quarkus.oidc.authentication.session-age-extension` is important if you need to have even the expired ID tokens refreshed. You can also complement refreshing the expired ID tokens by proactively refreshing the valid ID tokens which are about to be expired within the `quarkus.oidc.token.refresh-token-time-skew` value. If, during the current user request, it is calculated that the current ID token will expire within this `quarkus.oidc.token.refresh-token-time-skew` then it will be refreshed and the new session cookie will be created. This property should be set to a value which is less than the ID token lifespan; the closer it is to this lifespan value the more often the ID token will be refreshed. You can have this process further optimized by having a simple JavaScript function periodically emulating the user activity by pinging your Quarkus endpoint thus minimizing the window during which the user may have to be re-authenticated. Note this user session can not be extended forever - the returning user with the expired ID token will have to re-authenticate at the OIDC provider endpoint once the refresh token has expired. === TokenStateManager OIDC `CodeAuthenticationMechanism` is using the default `io.quarkus.oidc.TokenStateManager` interface implementation to keep the ID, access and refresh tokens returned in the authorization code or refresh grant responses in a session cookie. It makes Quarkus OIDC endpoints completely stateless. Note that some endpoints do not require the access token. An access token is only required if the endpoint needs to retrieve `UserInfo` or access the downstream service with this access token or use the roles associated with the access token (the roles in the ID token are checked by default). In such cases you can set either `quarkus.oidc.token-state-manager.strategy=id-refresh-token` (keep ID and refresh tokens only) or `quarkus.oidc.token-state-manager.strategy=id-token` (keep ID token only). If the ID, access and refresh tokens are JWT tokens then combining all of them (if the strategy is the default `keep-all-tokens`) or only ID and refresh tokens (if the strategy is `id-refresh-token`) may produce a session cookie value larger than 4KB and the browsers may not be able to keep this cookie. In such cases, you can use `quarkus.oidc.token-state-manager.split-tokens=true` to have a unique session token per each of these tokens. Register your own `io.quarkus.oidc.TokenStateManager' implementation as an `@ApplicationScoped` CDI bean if you need to customize the way the tokens are associated with the session cookie. For example, you may want to keep the tokens in a database and have only a database pointer stored in a session cookie. Note though that it may present some challenges in making the tokens available across multiple microservices nodes. Here is a simple example: [source, java] ---- package io.quarkus.oidc.test; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import io.quarkus.arc.AlternativePriority; import io.quarkus.oidc.AuthorizationCodeTokens; import io.quarkus.oidc.OidcTenantConfig; import io.quarkus.oidc.TokenStateManager; import io.quarkus.oidc.runtime.DefaultTokenStateManager; import io.smallrye.mutiny.Uni; import io.vertx.ext.web.RoutingContext; @ApplicationScoped @AlternativePriority(1) public class CustomTokenStateManager implements TokenStateManager { @Inject DefaultTokenStateManager tokenStateManager; @Override public Uni createTokenState(RoutingContext routingContext, OidcTenantConfig oidcConfig, AuthorizationCodeTokens sessionContent, TokenStateManager.CreateTokenStateRequestContext requestContext) { return tokenStateManager.createTokenState(routingContext, oidcConfig, sessionContent, requestContext) .map(t -> (t + ""|custom"")); } @Override public Uni getTokens(RoutingContext routingContext, OidcTenantConfig oidcConfig, String tokenState, TokenStateManager.GetTokensRequestContext requestContext) { if (!tokenState.endsWith(""|custom"")) { throw new IllegalStateException(); } String defaultState = tokenState.substring(0, tokenState.length() - 7); return tokenStateManager.getTokens(routingContext, oidcConfig, defaultState, requestContext); } @Override public Uni deleteTokens(RoutingContext routingContext, OidcTenantConfig oidcConfig, String tokenState, TokenStateManager.DeleteTokensRequestContext requestContext) { if (!tokenState.endsWith(""|custom"")) { throw new IllegalStateException(); } String defaultState = tokenState.substring(0, tokenState.length() - 7); return tokenStateManager.deleteTokens(routingContext, oidcConfig, defaultState, requestContext); } } ---- == Listening to important authentication events One can register `@ApplicationScoped` bean which will observe important OIDC authentication events. The listener will be updated when a user has logged in for the first time or re-authenticated, as well as when the session has been refreshed. More events may be reported in the future. For example: [source, java] ---- import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import io.quarkus.oidc.IdTokenCredential; import io.quarkus.oidc.SecurityEvent; import io.quarkus.security.identity.AuthenticationRequestContext; import io.vertx.ext.web.RoutingContext; @ApplicationScoped public class SecurityEventListener { public void event(@Observes SecurityEvent event) { String tenantId = event.getSecurityIdentity().getAttribute(""tenant-id""); RoutingContext vertxContext = event.getSecurityIdentity().getCredential(IdTokenCredential.class).getRoutingContext(); vertxContext.put(""listener-message"", String.format(""event:%s,tenantId:%s"", event.getEventType().name(), tenantId)); } } ---- == Single Page Applications Please check if implementing SPAs the way it is suggested in the link:security-openid-connect#single-page-applications[Single Page Applications for Service Applications] section can meet your requirements. If you prefer to use SPA and JavaScript API such as `Fetch` or `XMLHttpRequest`(XHR) with Quarkus web applications, please be aware that OpenID Connect Providers may not support CORS for Authorization endpoints where the users are authenticated after a redirect from Quarkus. This will lead to authentication failures if the Quarkus application and the OpenID Connect Provider are hosted on the different HTTP domains/ports. In such cases, set the `quarkus.oidc.authentication.java-script-auto-redirect` property to `false` which will instruct Quarkus to return a `499` status code and `WWW-Authenticate` header with the `OIDC` value. The browser script also needs to be updated to set `X-Requested-With` header with the `JavaScript` value and reload the last requested page in case of `499`, for example: [source,javascript] ---- Future callQuarkusService() async { Map headers = Map.fromEntries([MapEntry(""X-Requested-With"", ""JavaScript"")]); await http .get(""https://localhost:443/serviceCall"") .then((response) { if (response.statusCode == 499) { window.location.assign(""https://localhost.com:443/serviceCall""); } }); } ---- == Integration with GitHub and other OAuth2 providers Some well known providers such as `GitHub` or `LinkedIn` are not `OpenId Connect` but `OAuth2` providers which support the `authorization code flow`, for example, link:https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps[GitHub OAuth2] and link:https://docs.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow[LinkedIn OAuth2]. The main difference between `OAuth2` and `OpenId Connect` providers is that `OpenId Connect` providers, by building on top of `OAuth2`, return an `ID Token` representing a user authentication, in addition to the standard authorization code flow access and refresh tokens returned by `OAuth2` providers. With `OAuth2` providers, the fact of the user authentication is implicit and is indirectly represented by the access token which represents an authenticated user authorizing the current Quarkus `web-app` application to access some data on behalf of this user. For example, when working with `GitHub`, the Quarkus endpoint can acquire an access token which will allow it to request a `GitHub` user profile of the current user. In fact this is exactly how a standard `OpenId Connect` `UserInfo` acqusition also works - by authenticating into your `OpenId Connect` provider you also give a permission to Quarkus application to acquire your `UserInfo` on your behalf - and it also shows what is meant by `OpenId Connect` being built on top of `OAuth2`. In order to support the integration with such `OAuth2` servers, `quarkus-oidc` needs to be configured to allow the authorization code flow responses without `IdToken`: `quarkus.oidc.authentication.id-token-required=false`. The next step is to ensure that the returned access token can be useful to the current Quarkus endpoint. If the `OAuth2` provider supports the introspection endpoint then you may be able to use this access token as a source of roles with `quarkus.oidc.roles.source=accesstoken`. If no introspection endpoint is available then at the very least it should be possible to request a user information from this provider with `quarkus.oidc.authentication.user-info-required` - this is the case with `GitHib`. Also, OAuth2 servers may not support a well-known configuration endpoint in which case the discovery has to be disabled and the authorization, token, and introspection and/or userinfo endpoint paths have to be configured manually. Here is how you can integrate `quarkus-oidc` with `GitHub` after you have link:https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-app[created a GitHub OAuth application]. Configure your Quarkus endpoint like this: ```properties quarkus.oidc.auth-server-url=https://github.com/login/oauth quarkus.oidc.discovery-enabled=false quarkus.oidc.authorization-path=authorize quarkus.oidc.token-path=access_token quarkus.oidc.user-info-path=https://api.github.com/user # See https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps quarkus.oidc.authentication.scopes=user:email # Make sure a user info is required quarkus.oidc.authentication.user-info-required=true # Allow the code flow responses without ID tokens quarkus.oidc.authentication.id-token-required=false quarkus.oidc.application-type=web-app quarkus.oidc.client-id=github_app_clientid quarkus.oidc.credentials.secret=github_app_clientsecret ``` This is all what is needed for an endpoint like this one to return the currently authenticated user's profile with `GET http:localhost:8080/github/userinfo`: ```java import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import io.quarkus.oidc.UserInfo; import io.quarkus.security.Authenticated; @Path(""/github"") @Authenticated public class TokenResource { @Inject UserInfo userInfo; @GET @Path(""/userinfo"") @Produces(""application/json"") public String getUserInfo() { return userInfo.getUserInfoString(); } } ``` In your own endpoint you can access individual `UserInfo` properties as required. The last important point is to make sure the callback path you enter in the GitHub OAuth application configuration matches the endpoint path where you'd like the user be redirected to after a successful GitHub authentication and application authorization, in this case it has to be set to `http:localhost:8080/github/userinfo`. == Cloud Services === Google Cloud You can have Quarkus OIDC `web-app` applications access **Google Cloud services** such as **BigQuery** on behalf of the currently authenticated users who have enabled OpenID Connect (Authorization Code Flow) permissions to such services in their Google Developer Consoles. It is super easy to do with https://github.com/quarkiverse[Quarkiverse] https://github.com/quarkiverse/quarkiverse-google-cloud-services[Google Cloud Services], only add the https://github.com/quarkiverse/quarkiverse-google-cloud-services/releases/latest[latest tag] service dependency, for example: [source,xml] ---- io.quarkiverse.googlecloudservices quarkus-google-cloud-bigquery ${quarkiverse.googlecloudservices.version} ---- and configure Google OIDC properties: [source, properties] ---- quarkus.oidc.auth-server-url=https://accounts.google.com quarkus.oidc.application-type=web-app quarkus.oidc.client-id={GOOGLE_CLIENT_ID} quarkus.oidc.credentials.secret={GOOGLE_CLIENT_SECRET} quarkus.oidc.token.issuer=https://accounts.google.com ---- == Provider Endpoint configuration OIDC `web-app` application needs to know OpenId Connect provider's authorization, token, `JsonWebKey` (JWK) set and possibly `UserInfo`, introspection and end session (RP-initiated logout) endpoint addresses. By default they are discovered by adding a `/.well-known/openid-configuration` path to the configured `quarkus.oidc.auth-server-url`. Alternatively, if the discovery endpoint is not available or you would like to save on the discovery endpoint roundtrip, you can disable the discovery and configure them with relative path values, for example: [source, properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus quarkus.oidc.discovery-enabled=false # Authorization endpoint: http://localhost:8180/auth/realms/quarkus/protocol/openid-connect/auth quarkus.oidc.authorization-path=/protocol/openid-connect/auth # Token endpoint: http://localhost:8180/auth/realms/quarkus/protocol/openid-connect/token quarkus.oidc.token-path=/protocol/openid-connect/token # JWK set endpoint: http://localhost:8180/auth/realms/quarkus/protocol/openid-connect/certs quarkus.oidc.jwks-path=/protocol/openid-connect/certs # UserInfo endpoint: http://localhost:8180/auth/realms/quarkus/protocol/openid-connect/userinfo quarkus.oidc.user-info-path=/protocol/openid-connect/userinfo # Token Introspection endpoint: http://localhost:8180/auth/realms/quarkus/protocol/openid-connect/token/introspect quarkus.oidc.introspection-path=/protocol/openid-connect/token/introspect # End session endpoint: http://localhost:8180/auth/realms/quarkus/protocol/openid-connect/logout quarkus.oidc.end-session-path=/protocol/openid-connect/logout ---- [[jwt-claim-verification]] == JSON Web Token Claim Verification Please see link:security-openid-connect#jwt-claim-verification[JSON Web Token Claim verification] section about the claim verification, including the `iss` (issuer) claim. It applies to ID tokens but also to access tokens in a JWT format if the `web-app` application has requested the access token verification. == Token Propagation Please see link:security-openid-connect-client#token-propagation[Token Propagation] section about the Authorization Code Flow access token propagation to the downstream services. [[oidc-provider-client-authentication]] == Oidc Provider Client Authentication `quarkus.oidc.runtime.OidcProviderClient` is used when a remote request to an OpenId Connect Provider has to be done. It has to authenticate to the OpenId Connect Provider when the authorization code has to be exchanged for the ID, access and refresh tokens, when the ID and access tokens have to be refreshed or introspected. All the https://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication[OIDC Client Authentication] options are supported, for example: `client_secret_basic`: [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus/ quarkus.oidc.client-id=quarkus-app quarkus.oidc.credentials.secret=mysecret ---- or [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus/ quarkus.oidc.client-id=quarkus-app quarkus.oidc.credentials.client-secret.value=mysecret ---- or with the secret retrieved from a link:credentials-provider[CredentialsProvider]: [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus/ quarkus.oidc.client-id=quarkus-app # This is a key which will be used to retrieve a secret from the map of credentials returned from CredentialsProvider quarkus.oidc.credentials.client-secret.provider.key=mysecret-key # Set it only if more than one CredentialsProvider can be registered quarkus.oidc.credentials.client-secret.provider.name=oidc-credentials-provider ---- `client_secret_post`: [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus/ quarkus.oidc.client-id=quarkus-app quarkus.oidc.credentials.client-secret.value=mysecret quarkus.oidc.credentials.client-secret.method=post ---- `client_secret_jwt`: [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus/ quarkus.oidc.client-id=quarkus-app quarkus.oidc.credentials.jwt.secret=AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow # This is a token key identifier 'kid' header - set it if your OpenId Connect provider requires it, quarkus.oidc.credentials.jwt.token-key-id=mykey ---- or with the secret retrieved from a link:credentials-provider[CredentialsProvider]: [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus/ quarkus.oidc.client-id=quarkus-app # This is a key which will be used to retrieve a secret from the map of credentials returned from CredentialsProvider quarkus.oidc.credentials.jwt.secret-provider.key=mysecret-key # Set it only if more than one CredentialsProvider can be registered quarkus.oidc.credentials.jwt.secret-provider.name=oidc-credentials-provider ---- `private_key_jwt` with the PEM key file: [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus/ quarkus.oidc.client-id=quarkus-app quarkus.oidc.credentials.jwt.key-file=privateKey.pem # This is a token key identifier 'kid' header - set it if your OpenId Connect provider requires it quarkus.oidc.credentials.jwt.token-key-id=mykey ---- `private_key_jwt` with the key store file: [source,properties] ---- quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus/ quarkus.oidc.client-id=quarkus-app quarkus.oidc.credentials.jwt.key-store-file=keystore.jks quarkus.oidc.credentials.jwt.key-store-password=mypassword quarkus.oidc.credentials.jwt.key-password=mykeypassword # Private key alias inside the keystore quarkus.oidc.credentials.jwt.key-id=mykey # This is a token key identifier 'kid' header - set it if your OpenId Connect provider requires it, # Note it can be different to the `quarkus.oidc.credentials.jwt.key-id` value quarkus.oidc.credentials.jwt.token-key-id=mykey ---- Using `client_secret_jwt` or `private_key_jwt` authentication methods ensures that no client secret goes over the wire. [[integration-testing]] == Testing Start by adding the following dependencies to your test project: [source,xml] ---- net.sourceforge.htmlunit htmlunit org.eclipse.jetty * test io.quarkus quarkus-junit5 test ---- [[integration-testing-wiremock]] === Wiremock Add the following dependency: [source,xml] ---- io.quarkus quarkus-test-oidc-server test ---- Prepare the REST test endpoints, set `application.properties`, for example: [source, properties] ---- # keycloak.url is set by OidcWiremockTestResource quarkus.oidc.auth-server-url=${keycloak.url}/realms/quarkus/ quarkus.oidc.client-id=quarkus-web-app quarkus.oidc.credentials.secret=secret quarkus.oidc.application-type=web-app ---- and finally write the test code, for example: [source, java] ---- import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import com.gargoylesoftware.htmlunit.SilentCssErrorHandler; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.oidc.server.OidcWiremockTestResource; @QuarkusTest @QuarkusTestResource(OidcWiremockTestResource.class) public class CodeFlowAuthorizationTest { @Test public void testCodeFlow() throws Exception { try (final WebClient webClient = createWebClient()) { // the test REST endpoint listens on '/code-flow' HtmlPage page = webClient.getPage(""http://localhost:8081/code-flow""); HtmlForm form = page.getFormByName(""form""); // user 'alice' has the 'user' role form.getInputByName(""username"").type(""alice""); form.getInputByName(""password"").type(""alice""); page = form.getInputByValue(""login"").click(); assertEquals(""alice"", page.getBody().asText()); } } private WebClient createWebClient() { WebClient webClient = new WebClient(); webClient.setCssErrorHandler(new SilentCssErrorHandler()); return webClient; } } ---- `OidcWiremockTestResource` recognizes `alice` and `admin` users. The user `alice` has the `user` role only by default - it can be customized with a `quarkus.test.oidc.token.user-roles` system property. The user `admin` has the `user` and `admin` roles by default - it can be customized with a `quarkus.test.oidc.token.admin-roles` system property. Additionally, `OidcWiremockTestResource` set token issuer and audience to `https://service.example.com` which can be customized with `quarkus.test.oidc.token.issuer` and `quarkus.test.oidc.token.audience` system properties. `OidcWiremockTestResource` can be used to emulate all OpenId Connect providers. [[integration-testing-keycloak-devservices]] === Dev Services for Keycloak Using link:security-openid-connect-dev-services[Dev Services for Keycloak] is recommended for the integration testing against Keycloak. `Dev Services for Keycloak` will launch and initialize a test container: it will create a `quarkus` realm, a `quarkus-app` client (`secret` secret) and add `alice` (`admin` and `user` roles) and `bob` (`user` role) users, where all of these properties can be customized. First prepare `application.properties`. You can start with a completely empty `application.properties` as `Dev Services for Keycloak` will register `quarkus.oidc.auth-server-url` pointing to the running test container as well as `quarkus.oidc.client-id=quarkus-app` and `quarkus.oidc.credentials.secret=secret`. But if you already have all the required `quarkus-oidc` properties configured then you only need to associate `quarkus.oidc.auth-server-url` with the `prod` profile for `Dev Services for Keycloak`to start a container, for example: [source,properties] ---- %prod.quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus ---- If a custom realm file has to be imported into Keycloak before running the tests then you can configure `Dev Services for Keycloak` as follows: [source,properties] ---- %prod.quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/quarkus quarkus.keycloak.devservices.realm-path=quarkus-realm.json ---- Finally write a test code the same way as it is described in the <> section above. The only difference is that `@QuarkusTestResource` is no longer needed: [source, java] ---- @QuarkusTest public class CodeFlowAuthorizationTest { } ---- [[integration-testing-keycloak]] === KeycloakTestResourceLifecycleManager If you need to do the integration testing against Keycloak then you are encouraged to do it with <>. Use `KeycloakTestResourceLifecycleManager` for your tests only if there is a good reason not to use `Dev Services for Keycloak`. Start with adding the following dependency: [source,xml] ---- io.quarkus quarkus-test-keycloak-server test ---- which provides `io.quarkus.test.keycloak.server.KeycloakTestResourceLifecycleManager` - an implementation of `io.quarkus.test.common.QuarkusTestResourceLifecycleManager` which starts a Keycloak container. And configure `maven.surefire.plugin` as follows: [source,xml] ---- maven-surefire-plugin ${keycloak.docker.image} ---- (and similarly `maven.failsafe.plugin` when testing in native image). And now set the configuration and write the test code the same way as it is described in the <> section above. The only difference is the name of `QuarkusTestResource`: [source, java] ---- import io.quarkus.test.keycloak.server.KeycloakTestResourceLifecycleManager; @QuarkusTest @QuarkusTestResource(KeycloakTestResourceLifecycleManager.class) public class CodeFlowAuthorizationTest { } ---- `KeycloakTestResourceLifecycleManager` registers `alice` and `admin` users. The user `alice` has the `user` role only by default - it can be customized with a `keycloak.token.user-roles` system property. The user `admin` has the `user` and `admin` roles by default - it can be customized with a `keycloak.token.admin-roles` system property. By default, `KeycloakTestResourceLifecycleManager` uses HTTPS to initialize a Keycloak instance which can be disabled with `keycloak.use.https=false`. Default realm name is `quarkus` and client id - `quarkus-web-app` - set `keycloak.realm` and `keycloak.web-app.client` system properties to customize the values if needed. [[integration-testing-security-annotation]] === TestSecurity annotation Please see link:security-openid-connect#integration-testing-security-annotation[Use TestingSecurity with injected JsonWebToken] section for more information about using `@TestSecurity` and `@OidcSecurity` annotations for testing the `web-app` application endpoint code which depends on the injected ID and access `JsonWebToken` as well as `UserInfo` and `OidcConfigurationMetadata`. == How to check the errors in the logs == Please enable `io.quarkus.oidc.runtime.OidcProvider` `TRACE` level logging to see more details about the token verification errors: [source, properties] ---- quarkus.log.category.""io.quarkus.oidc.runtime.OidcProvider"".level=TRACE quarkus.log.category.""io.quarkus.oidc.runtime.OidcProvider"".min-level=TRACE ---- Please enable `io.quarkus.oidc.runtime.OidcRecorder` `TRACE` level logging to see more details about the OidcProvider client initialization errors: [source, properties] ---- quarkus.log.category.""io.quarkus.oidc.runtime.OidcRecorder"".level=TRACE quarkus.log.category.""io.quarkus.oidc.runtime.OidcRecorder"".min-level=TRACE ---- == Running behind a reverse proxy OIDC authentication mechanism can be affected if your Quarkus application is running behind a reverse proxy/gateway/firewall when HTTP `Host` header may be reset to the internal IP address, HTTPS connection may be terminated, etc. For example, an authorization code flow `redirect_uri` parameter may be set to the internal host instead of the expected external one. In such cases configuring Quarkus to recognize the original headers forwarded by the proxy will be required, see link:http-reference#reverse-proxy[Running behind a reverse proxy] Vert.x documentation section for more information. For example, if your Quarkus endpoint runs in a cluster behind Kubernetes Ingress then a redirect from the OpenId Connect Provider back to this endpoint may not work since the calculated `redirect_uri` parameter may point to the internal endpoint address. This problem can be resolved with the following configuration: [source,properties] ---- quarkus.http.proxy.proxy-address-forwarding=true quarkus.http.proxy.allow-forwarded=false quarkus.http.proxy.enable-forwarded-host=true quarkus.http.proxy.forwarded-host-header=X-ORIGINAL-HOST ---- where `X-ORIGINAL-HOST` is set by Kubernetes Ingress to represent the external endpoint address. `quarkus.oidc.authentication.force-redirect-https-scheme` property may also be used when the Quarkus application is running behind a SSL terminating reverse proxy. == External and Internal Access to OpenId Connect Provider Note that the OpenId Connect Provider externally accessible authorization, logout and other endpoints may have different HTTP(S) URLs compared to the URLs auto-discovered or configured relative to `quarkus.oidc.auth-server-url` internal URL. In such cases an issuer verification failure may be reported by the endpoint and redirects to the externally accessible Connect Provider endpoints may fail. In such cases, if you work with Keycloak then please start it with a `KEYCLOAK_FRONTEND_URL` system property set to the externally accessible base URL. If you work with other Openid Connect providers then please check your provider's documentation. == Customize authentication requests By default, only the `response_type` (set to `code`), `scope` (set to 'openid'), `client_id`, `redirect_uri` and `state` properties are passed as HTTP query parameters to the OpenId Connect provider's authorization endpoint when the user is redirected to it to authenticate. You can add more properties to it with `quarkus.oidc.authentication.extra-params`. For example, some OpenId Connect providers may choose to return the authorization code as part of the redirect URI's fragment which would break the authentication process - it can be fixed as follows: [source,properties] ---- quarkus.oidc.authentication.extra-params.response_mode=query ---- == Configuration Reference include::{generated-dir}/config/quarkus-oidc.adoc[opts=optional] == References * https://www.keycloak.org/documentation.html[Keycloak Documentation] * https://openid.net/connect/[OpenID Connect] * https://tools.ietf.org/html/rfc7519[JSON Web Token] * link:security-openid-connect-client[Quarkus - Using OpenID Connect and OAuth2 Client and Filters to manage access tokens] * link:security-openid-connect-dev-services[Dev Services for Keycloak] * link:security[Quarkus Security] ",12531,False,2359.088229012442,median "// Automatically generated by 'openshift-apidocs-gen'. Do not edit. :_content-type: ASSEMBLY [id=""cronjob-batch-v1""] = CronJob [batch/v1] ifdef::product-title[] include::_attributes/common-attributes.adoc[] endif::[] toc::[] Description:: + -- CronJob represents the configuration of a single cron job. -- Type:: `object` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `metadata` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta[`ObjectMeta`] | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `spec` | `object` | CronJobSpec describes how the job execution will look like and when it will actually run. | `status` | `object` | CronJobStatus represents the current state of a cron job. |=== === .spec Description:: + -- CronJobSpec describes how the job execution will look like and when it will actually run. -- Type:: `object` Required:: - `schedule` - `jobTemplate` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `concurrencyPolicy` | `string` | Specifies how to treat concurrent executions of a Job. Valid values are: - ""Allow"" (default): allows CronJobs to run concurrently; - ""Forbid"": forbids concurrent runs, skipping next run if previous run hasn't finished yet; - ""Replace"": cancels currently running job and replaces it with a new one | `failedJobsHistoryLimit` | `integer` | The number of failed finished jobs to retain. Value must be non-negative integer. Defaults to 1. | `jobTemplate` | `object` | JobTemplateSpec describes the data a Job should have when created from a template | `schedule` | `string` | The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron. | `startingDeadlineSeconds` | `integer` | Optional deadline in seconds for starting the job if it misses scheduled time for any reason. Missed jobs executions will be counted as failed ones. | `successfulJobsHistoryLimit` | `integer` | The number of successful finished jobs to retain. Value must be non-negative integer. Defaults to 3. | `suspend` | `boolean` | This flag tells the controller to suspend subsequent executions, it does not apply to already started executions. Defaults to false. |=== === .spec.jobTemplate Description:: + -- JobTemplateSpec describes the data a Job should have when created from a template -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `metadata` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta[`ObjectMeta`] | Standard object's metadata of the jobs created from this template. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `spec` | `object` | JobSpec describes how the job execution will look like. |=== === .spec.jobTemplate.spec Description:: + -- JobSpec describes how the job execution will look like. -- Type:: `object` Required:: - `template` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `activeDeadlineSeconds` | `integer` | Specifies the duration in seconds relative to the startTime that the job may be continuously active before the system tries to terminate it; value must be positive integer. If a Job is suspended (at creation or through an update), this timer will effectively be stopped and reset when the Job is resumed again. | `backoffLimit` | `integer` | Specifies the number of retries before marking this job failed. Defaults to 6 | `completionMode` | `string` | CompletionMode specifies how Pod completions are tracked. It can be `NonIndexed` (default) or `Indexed`. `NonIndexed` means that the Job is considered complete when there have been .spec.completions successfully completed Pods. Each Pod completion is homologous to each other. `Indexed` means that the Pods of a Job get an associated completion index from 0 to (.spec.completions - 1), available in the annotation batch.kubernetes.io/job-completion-index. The Job is considered complete when there is one successfully completed Pod for each index. When value is `Indexed`, .spec.completions must be specified and `.spec.parallelism` must be less than or equal to 10^5. In addition, The Pod name takes the form `$(job-name)-$(index)-$(random-string)`, the Pod hostname takes the form `$(job-name)-$(index)`. This field is beta-level. More completion modes can be added in the future. If the Job controller observes a mode that it doesn't recognize, the controller skips updates for the Job. | `completions` | `integer` | Specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/ | `manualSelector` | `boolean` | manualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsible for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#specifying-your-own-pod-selector | `parallelism` | `integer` | Specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/ | `selector` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector[`LabelSelector`] | A label query over pods that should match the pod count. Normally, the system sets this field for you. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors | `suspend` | `boolean` | Suspend specifies whether the Job controller should create Pods or not. If a Job is created with suspend set to true, no Pods are created by the Job controller. If a Job is suspended after creation (i.e. the flag goes from false to true), the Job controller will delete all active Pods associated with this Job. Users must design their workload to gracefully handle this. Suspending a Job will reset the StartTime field of the Job, effectively resetting the ActiveDeadlineSeconds timer too. Defaults to false. This field is beta-level, gated by SuspendJob feature flag (enabled by default). | `template` | xref:../objects/index.adoc#io.k8s.api.core.v1.PodTemplateSpec[`PodTemplateSpec`] | Describes the pod that will be created when executing a job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/ | `ttlSecondsAfterFinished` | `integer` | ttlSecondsAfterFinished limits the lifetime of a Job that has finished execution (either Complete or Failed). If this field is set, ttlSecondsAfterFinished after the Job finishes, it is eligible to be automatically deleted. When the Job is being deleted, its lifecycle guarantees (e.g. finalizers) will be honored. If this field is unset, the Job won't be automatically deleted. If this field is set to zero, the Job becomes eligible to be deleted immediately after it finishes. This field is alpha-level and is only honored by servers that enable the TTLAfterFinished feature. |=== === .status Description:: + -- CronJobStatus represents the current state of a cron job. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `active` | xref:../objects/index.adoc#io.k8s.api.core.v1.ObjectReference[`array (ObjectReference)`] | A list of pointers to currently running jobs. | `lastScheduleTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Information when was the last time the job was successfully scheduled. | `lastSuccessfulTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Information when was the last time the job successfully completed. |=== == API endpoints The following API endpoints are available: * `/apis/batch/v1/cronjobs` - `GET`: list or watch objects of kind CronJob * `/apis/batch/v1/watch/cronjobs` - `GET`: watch individual changes to a list of CronJob. deprecated: use the 'watch' parameter with a list operation instead. * `/apis/batch/v1/namespaces/{namespace}/cronjobs` - `DELETE`: delete collection of CronJob - `GET`: list or watch objects of kind CronJob - `POST`: create a CronJob * `/apis/batch/v1/watch/namespaces/{namespace}/cronjobs` - `GET`: watch individual changes to a list of CronJob. deprecated: use the 'watch' parameter with a list operation instead. * `/apis/batch/v1/namespaces/{namespace}/cronjobs/{name}` - `DELETE`: delete a CronJob - `GET`: read the specified CronJob - `PATCH`: partially update the specified CronJob - `PUT`: replace the specified CronJob * `/apis/batch/v1/watch/namespaces/{namespace}/cronjobs/{name}` - `GET`: watch changes to an object of kind CronJob. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. * `/apis/batch/v1/namespaces/{namespace}/cronjobs/{name}/status` - `GET`: read status of the specified CronJob - `PATCH`: partially update status of the specified CronJob - `PUT`: replace status of the specified CronJob === /apis/batch/v1/cronjobs .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | 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 together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". 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` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | 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` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: list or watch objects of kind CronJob .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.batch.v1.CronJobList[`CronJobList`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/watch/cronjobs .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | 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 together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". 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` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | 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` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch individual changes to a list of CronJob. deprecated: use the 'watch' parameter with a list operation instead. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/namespaces/{namespace}/cronjobs .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of CronJob .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `continue` | `string` | 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 together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". 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. | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `gracePeriodSeconds` | `integer` | 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. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | 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. | `orphanDependents` | `boolean` | 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` | `string` | 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. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions[`DeleteOptions`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list or watch objects of kind CronJob .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | 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 together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". 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` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | 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` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.batch.v1.CronJobList[`CronJobList`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a CronJob .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 201 - Created | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 202 - Accepted | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/watch/namespaces/{namespace}/cronjobs .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | 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 together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". 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` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | 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` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch individual changes to a list of CronJob. deprecated: use the 'watch' parameter with a list operation instead. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/namespaces/{namespace}/cronjobs/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the CronJob | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a CronJob .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | 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` | `boolean` | 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` | `string` | 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. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions[`DeleteOptions`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 202 - Accepted | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified CronJob .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified CronJob .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 201 - Created | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified CronJob .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 201 - Created | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/watch/namespaces/{namespace}/cronjobs/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the CronJob | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | 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 together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". 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` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | 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` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch changes to an object of kind CronJob. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/namespaces/{namespace}/cronjobs/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the CronJob | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified CronJob .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified CronJob .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 201 - Created | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified CronJob .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 201 - Created | xref:../workloads_apis/cronjob-batch-v1.adoc#cronjob-batch-v1[`CronJob`] schema | 401 - Unauthorized | Empty |=== ",12224,True,3016.605838654236,median "#include ""marching_cubes.hpp"" mesh create_chunk(vec3 origin, const int nb_cubes, const float cube_size, float f(vec3), float isolevel){ mesh chunk; int last=0; std::map coordsToIdx; Cube cube; int ntriangles=0; int edgeTable[256]={ 0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0 }; int triTable[256][16] = {{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}; for (int i=0; i &coordsToIdx, int &last, int edgeTable[256], int triTable[256][16]){ vec3 points[12]; /* Determine the index into the edge table which tells us which vertices are inside of the surface */ int cubeindex = 0; if (cube.val[0] < isolevel) cubeindex |= 1; if (cube.val[1] < isolevel) cubeindex |= 2; if (cube.val[2] < isolevel) cubeindex |= 4; if (cube.val[3] < isolevel) cubeindex |= 8; if (cube.val[4] < isolevel) cubeindex |= 16; if (cube.val[5] < isolevel) cubeindex |= 32; if (cube.val[6] < isolevel) cubeindex |= 64; if (cube.val[7] < isolevel) cubeindex |= 128; /* Cube is entirely in/out of the surface */ if (edgeTable[cubeindex] == 0) return(0); /* Find the vertices where the surface intersects the cube */ if (edgeTable[cubeindex] & 1) points[0] = interpolate(isolevel,cube.p[0],cube.p[1],cube.val[0],cube.val[1]); if (edgeTable[cubeindex] & 2) points[1] = interpolate(isolevel,cube.p[1],cube.p[2],cube.val[1],cube.val[2]); if (edgeTable[cubeindex] & 4) points[2] = interpolate(isolevel,cube.p[2],cube.p[3],cube.val[2],cube.val[3]); if (edgeTable[cubeindex] & 8) points[3] = interpolate(isolevel,cube.p[3],cube.p[0],cube.val[3],cube.val[0]); if (edgeTable[cubeindex] & 16) points[4] = interpolate(isolevel,cube.p[4],cube.p[5],cube.val[4],cube.val[5]); if (edgeTable[cubeindex] & 32) points[5] = interpolate(isolevel,cube.p[5],cube.p[6],cube.val[5],cube.val[6]); if (edgeTable[cubeindex] & 64) points[6] = interpolate(isolevel,cube.p[6],cube.p[7],cube.val[6],cube.val[7]); if (edgeTable[cubeindex] & 128) points[7] = interpolate(isolevel,cube.p[7],cube.p[4],cube.val[7],cube.val[4]); if (edgeTable[cubeindex] & 256) points[8] = interpolate(isolevel,cube.p[0],cube.p[4],cube.val[0],cube.val[4]); if (edgeTable[cubeindex] & 512) points[9] = interpolate(isolevel,cube.p[1],cube.p[5],cube.val[1],cube.val[5]); if (edgeTable[cubeindex] & 1024) points[10] = interpolate(isolevel,cube.p[2],cube.p[6],cube.val[2],cube.val[6]); if (edgeTable[cubeindex] & 2048) points[11] = interpolate(isolevel,cube.p[3],cube.p[7],cube.val[3],cube.val[7]); /* Create the triangle */ int ntriang = 0; for (int i=0; triTable[cubeindex][i] != -1; i+=3) { vec3 p1 = points[triTable[cubeindex][i ]]; vec3 p2 = points[triTable[cubeindex][i+1]]; vec3 p3 = points[triTable[cubeindex][i+2]]; unsigned int i1, i2, i3; std::map::iterator it; it = coordsToIdx.find(p1); if(it != coordsToIdx.end()) {i1 = it->second;} else {i1 = last++; chunk.position.push_back(p1); chunk.texture_uv.push_back(evaluateTexture(p1)); coordsToIdx[p1]=i1;} it = coordsToIdx.find(p2); if(it != coordsToIdx.end()) {i2 = it->second;} else {i2 = last++; chunk.position.push_back(p2); chunk.texture_uv.push_back(evaluateTexture(p2)); coordsToIdx[p2]=i2;} it = coordsToIdx.find(p3); if(it != coordsToIdx.end()) {i3 = it->second;} else {i3 = last++; chunk.position.push_back(p3); chunk.texture_uv.push_back(evaluateTexture(p3)); coordsToIdx[p3]=i3;} const index3 triangle = {i3, i2, i1}; chunk.connectivity.push_back(triangle); ntriang++; } return(ntriang); } vec3 interpolate(float isolevel, vec3 p1, vec3 p2, float valp1, float valp2) { float mu; vec3 p; if (fabs(isolevel-valp1) < 0.00001) return(p1); if (fabs(isolevel-valp2) < 0.00001) return(p2); if (fabs(valp1-valp2) < 0.00001) return(p1); mu = (isolevel - valp1) / (valp2 - valp1); p.x = p1.x + mu * (p2.x - p1.x); p.y = p1.y + mu * (p2.y - p1.y); p.z = p1.z + mu * (p2.z - p1.z); return p; } vec2 evaluateTexture(vec3 p){ vec2 uv; uv.x = 0.1*(p.x + p.y); uv.y = 0.1*(p.z + p.y); return uv; } ",16293,True,4836.772191292651,median "[[defining-processors]] === Define processors You can use processors to filter and enhance data before sending it to the configured output. To define a processor, you specify the processor name, an optional condition, and a set of parameters: [source,yaml] ------ processors: - : when: - : when: ... ------ Where: * `` specifies a <> that performs some kind of action, such as selecting the fields that are exported or adding metadata to the event. * `` specifies an optional <>. If the condition is present, then the action is executed only if the condition is fulfilled. If no condition is passed, then the action is always executed. * `` is the list of parameters to pass to the processor. More complex conditional processing can be accomplished by using the if-then-else processor configuration. This allows multiple processors to be executed based on a single condition. [source,yaml] ---- processors: - if: then: <1> - : - : ... else: <2> - : - : ... ---- <1> `then` must contain a single processor or a list of one or more processors to execute when the condition evaluates to true. <2> `else` is optional. It can contain a single processor or a list of processors to execute when the conditional evaluate to false. [[where-valid]] ==== Where are processors valid? // TODO: ANY NEW BEATS THAT RE-USE THIS TOPIC NEED TO DEFINE processor-scope. ifeval::[""{beatname_lc}""==""filebeat""] :processor-scope: input endif::[] ifeval::[""{beatname_lc}""==""auditbeat""] :processor-scope: module endif::[] ifeval::[""{beatname_lc}""==""metricbeat""] :processor-scope: module endif::[] ifeval::[""{beatname_lc}""==""packetbeat""] :processor-scope: protocol endif::[] ifeval::[""{beatname_lc}""==""heartbeat""] :processor-scope: monitor endif::[] ifeval::[""{beatname_lc}""==""winlogbeat""] :processor-scope: event log shipper endif::[] Processors are valid: * At the top-level in the configuration. The processor is applied to all data collected by {beatname_uc}. * Under a specific {processor-scope}. The processor is applied to the data collected for that {processor-scope}. ifeval::[""{beatname_lc}""==""filebeat""] For example: + [source,yaml] ------ - type: processors: - : when: ... ------ + Similarly, for {beatname_uc} modules, you can define processors under the `input` section of the module definition. endif::[] ifeval::[""{beatname_lc}""==""metricbeat""] [source,yaml] ---- - module: metricsets: [""""] processors: - : when: ---- endif::[] ifeval::[""{beatname_lc}""==""auditbeat""] For example: + [source,yaml] ---- auditbeat.modules: - module: processors: - : when: ---- endif::[] ifeval::[""{beatname_lc}""==""packetbeat""] For example: + [source,yaml] ---- packetbeat.protocols: - type: processors: - : when: ---- * Under `packetbeat.flows`. The processor is applied to the data in <>: + [source,yaml] ---- packetbeat.flows: processors: - : when: ---- endif::[] ifeval::[""{beatname_lc}""==""heartbeat""] For example: + [source,yaml] ---- heartbeat.monitors: - type: processors: - : when: ---- endif::[] ifeval::[""{beatname_lc}""==""winlogbeat""] For example: + [source,yaml] ---- winlogbeat.event_logs: - name: processors: - : when: ---- endif::[] [[processors]] ==== Processors The supported processors are: * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> ifdef::has_decode_csv_fields_processor[] * <> endif::[] * <> * <> * <> * <> * <> * <> * <> * <> ifdef::has_script_processor[] * <> endif::[] [[conditions]] ==== Conditions Each condition receives a field to compare. You can specify multiple fields under the same condition by using `AND` between the fields (for example, `field1 AND field2`). For each field, you can specify a simple field name or a nested map, for example `dns.question.name`. See <> for a list of all the fields that are exported by {beatname_uc}. The supported conditions are: * <> * <> * <> * <> * <> * <> * <> * <> * <> [float] [[condition-equals]] ===== `equals` With the `equals` condition, you can compare if a field has a certain value. The condition accepts only an integer or a string value. For example, the following condition checks if the response code of the HTTP transaction is 200: [source,yaml] ------- equals: http.response.code: 200 ------- [float] [[condition-contains]] ===== `contains` The `contains` condition checks if a value is part of a field. The field can be a string or an array of strings. The condition accepts only a string value. For example, the following condition checks if an error is part of the transaction status: [source,yaml] ------ contains: status: ""Specific error"" ------ [float] [[condition-regexp]] ===== `regexp` The `regexp` condition checks the field against a regular expression. The condition accepts only strings. For example, the following condition checks if the process name starts with `foo`: [source,yaml] ----- regexp: system.process.name: ""foo.*"" ----- [float] [[condition-range]] ===== `range` The `range` condition checks if the field is in a certain range of values. The condition supports `lt`, `lte`, `gt` and `gte`. The condition accepts only integer or float values. For example, the following condition checks for failed HTTP transactions by comparing the `http.response.code` field with 400. [source,yaml] ------ range: http.response.code: gte: 400 ------ This can also be written as: [source,yaml] ---- range: http.response.code.gte: 400 ---- The following condition checks if the CPU usage in percentage has a value between 0.5 and 0.8. [source,yaml] ------ range: system.cpu.user.pct.gte: 0.5 system.cpu.user.pct.lt: 0.8 ------ [float] [[condition-network]] ===== `network` The `network` condition checks if the field is in a certain IP network range. Both IPv4 and IPv6 addresses are supported. The network range may be specified using CIDR notation, like ""192.0.2.0/24"" or ""2001:db8::/32"", or by using one of these named ranges: - `loopback` - Matches loopback addresses in the range of `127.0.0.0/8` or `::1/128`. - `unicast` - Matches global unicast addresses defined in RFC 1122, RFC 4632, and RFC 4291 with the exception of the IPv4 broadcast address (`255.255.255.255`). This includes private address ranges. - `multicast` - Matches multicast addresses. - `interface_local_multicast` - Matches IPv6 interface-local multicast addresses. - `link_local_unicast` - Matches link-local unicast addresses. - `link_local_multicast` - Matches link-local multicast addresses. - `private` - Matches private address ranges defined in RFC 1918 (IPv4) and RFC 4193 (IPv6). - `public` - Matches addresses that are not loopback, unspecified, IPv4 broadcast, link local unicast, link local multicast, interface local multicast, or private. - `unspecified` - Matches unspecified addresses (either the IPv4 address ""0.0.0.0"" or the IPv6 address ""::""). The following condition returns true if the `source.ip` value is within the private address space. [source,yaml] ---- network: source.ip: private ---- This condition returns true if the `destination.ip` value is within the IPv4 range of `192.168.1.0` - `192.168.1.255`. [source,yaml] ---- network: destination.ip: '192.168.1.0/24' ---- And this condition returns true when `destination.ip` is within any of the given subnets. [source,yaml] ---- network: destination.ip: ['192.168.1.0/24', '10.0.0.0/8', loopback] ---- [float] [[condition-has_fields]] ===== `has_fields` The `has_fields` condition checks if all the given fields exist in the event. The condition accepts a list of string values denoting the field names. For example, the following condition checks if the `http.response.code` field is present in the event. [source,yaml] ------ has_fields: ['http.response.code'] ------ [float] [[condition-or]] ===== `or` The `or` operator receives a list of conditions. [source,yaml] ------- or: - - - ... ------- For example, to configure the condition `http.response.code = 304 OR http.response.code = 404`: [source,yaml] ------ or: - equals: http.response.code: 304 - equals: http.response.code: 404 ------ [float] [[condition-and]] ===== `and` The `and` operator receives a list of conditions. [source,yaml] ------- and: - - - ... ------- For example, to configure the condition `http.response.code = 200 AND status = OK`: [source,yaml] ------ and: - equals: http.response.code: 200 - equals: status: OK ------ To configure a condition like ` OR AND `: [source,yaml] ------ or: - - and: - - ------ [float] [[condition-not]] ===== `not` The `not` operator receives the condition to negate. [source,yaml] ------- not: ------- For example, to configure the condition `NOT status = OK`: [source,yaml] ------ not: equals: status: OK ------ [[add-cloud-metadata]] === Add cloud metadata The `add_cloud_metadata` processor enriches each event with instance metadata from the machine's hosting provider. At startup it will detect the hosting provider and cache the instance metadata. The following cloud providers are supported: - Amazon Web Services (AWS) - Digital Ocean - Google Compute Engine (GCE) - https://www.qcloud.com/?lang=en[Tencent Cloud] (QCloud) - Alibaba Cloud (ECS) - Azure Virtual Machine - Openstack Nova The simple configuration below enables the processor. [source,yaml] ------------------------------------------------------------------------------- processors: - add_cloud_metadata: ~ ------------------------------------------------------------------------------- The `add_cloud_metadata` processor has two optional configuration settings. The first one is `timeout` which specifies the maximum amount of time to wait for a successful response when detecting the hosting provider. The default timeout value is `3s`. If a timeout occurs then no instance metadata will be added to the events. This makes it possible to enable this processor for all your deployments (in the cloud or on-premise). The second optional configuration setting is `overwrite`. When `overwrite` is `true`, `add_cloud_metadata` overwrites existing `cloud.*` fields (`false` by default). The metadata that is added to events varies by hosting provider. Below are examples for each of the supported providers. _AWS_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""account.id"": ""123456789012"", ""availability_zone"": ""us-east-1c"", ""instance.id"": ""i-4e123456"", ""machine.type"": ""t2.medium"", ""image.id"": ""ami-abcd1234"", ""provider"": ""aws"", ""region"": ""us-east-1"" } } ------------------------------------------------------------------------------- _Digital Ocean_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""instance.id"": ""1234567"", ""provider"": ""digitalocean"", ""region"": ""nyc2"" } } ------------------------------------------------------------------------------- _GCP_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""availability_zone"": ""us-east1-b"", ""instance.id"": ""1234556778987654321"", ""machine.type"": ""f1-micro"", ""project.id"": ""my-dev"", ""provider"": ""gcp"" } } ------------------------------------------------------------------------------- _Tencent Cloud_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""availability_zone"": ""gz-azone2"", ""instance.id"": ""ins-qcloudv5"", ""provider"": ""qcloud"", ""region"": ""china-south-gz"" } } ------------------------------------------------------------------------------- _Alibaba Cloud_ This metadata is only available when VPC is selected as the network type of the ECS instance. [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""availability_zone"": ""cn-shenzhen"", ""instance.id"": ""i-wz9g2hqiikg0aliyun2b"", ""provider"": ""ecs"", ""region"": ""cn-shenzhen-a"" } } ------------------------------------------------------------------------------- _Azure Virtual Machine_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""provider"": ""az"", ""instance.id"": ""04ab04c3-63de-4709-a9f9-9ab8c0411d5e"", ""instance.name"": ""test-az-vm"", ""machine.type"": ""Standard_D3_v2"", ""region"": ""eastus2"" } } ------------------------------------------------------------------------------- _Openstack Nova_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""instance.name"": ""test-998d932195.mycloud.tld"", ""instance.id"": ""i-00011a84"", ""availability_zone"": ""xxxx-az-c"", ""provider"": ""openstack"", ""machine.type"": ""m2.large"" } } ------------------------------------------------------------------------------- [[add-fields]] === Add fields The `add_fields` processor adds additional fields to the event. Fields can be scalar values, arrays, dictionaries, or any nested combination of these. By default the fields that you specify will be grouped under the `fields` sub-dictionary in the event. To group the fields under a different sub-dictionary, use the `target` setting. To store the fields as top-level fields, set `target: ''`. `target`:: (Optional) Sub-dictionary to put all fields into. Defaults to `fields`. `fields`:: Fields to be added. For example, this configuration: [source,yaml] ------------------------------------------------------------------------------ processors: - add_fields: target: project fields: name: myproject id: '574734885120952459' ------------------------------------------------------------------------------ Adds these fields to any event: [source,json] ------------------------------------------------------------------------------- { ""project"": { ""name"": ""myproject"", ""id"": ""574734885120952459"" } } ------------------------------------------------------------------------------- [[add-labels]] === Add labels The `add_labels` processors adds a set of key-value pairs to an event. The processor will flatten nested configuration objects like arrays or dictionaries into a fully qualified name by merging nested names with a `.`. Array entries create numeric names starting with 0. Labels are always stored under the Elastic Common Schema compliant `labels` sub-dictionary. `labels`:: dictionaries of labels to be added. For example, this configuration: [source,yaml] ------------------------------------------------------------------------------ processors: - add_labels: labels: number: 1 with.dots: test nested: with.dots: nested array: - do - re - with.field: mi ------------------------------------------------------------------------------ Adds these fields to every event: [source,json] ------------------------------------------------------------------------------- { ""labels"": { ""number"": 1, ""with.dots"": ""test"", ""nested.with.dots"": ""nested"", ""array.0"": ""do"", ""array.1"": ""re"", ""array.2.with.field"": ""mi"" } } ------------------------------------------------------------------------------- [[add-locale]] === Add the local time zone The `add_locale` processor enriches each event with the machine's time zone offset from UTC or with the name of the time zone. It supports one configuration option named `format` that controls whether an offset or time zone abbreviation is added to the event. The default format is `offset`. The processor adds the a `beat.timezone` value to each event. The configuration below enables the processor with the default settings. [source,yaml] ------------------------------------------------------------------------------- processors: - add_locale: ~ ------------------------------------------------------------------------------- This configuration enables the processor and configures it to add the time zone abbreviation to events. [source,yaml] ------------------------------------------------------------------------------- processors: - add_locale: format: abbreviation ------------------------------------------------------------------------------- NOTE: Please note that `add_locale` differentiates between daylight savings time (DST) and regular time. For example `CEST` indicates DST and and `CET` is regular time. [[add-tags]] === Add tags The `add_tags` processor adds tags to a list of tags. If the target field already exists, the tags are appended to the existing list of tags. `tags`:: List of tags to add. `target`:: (Optional) Field the tags will be added to. Defaults to `tags`. For example, this configuration: [source,yaml] ------------------------------------------------------------------------------ processors: - add_tags: tags: [web, production] target: ""environment"" ------------------------------------------------------------------------------ Adds the environment field to every event: [source,json] ------------------------------------------------------------------------------- { ""environment"": [""web"", ""production""] } ------------------------------------------------------------------------------- ifdef::has_decode_csv_fields_processor[] [[decode-csv-fields]] === Decode CSV fields experimental[] The `decode_csv_fields` processor decodes fields containing records in comma-separated format (CSV). It will output the values as an array of strings. This processor is available for Filebeat and Journalbeat. [source,yaml] ----------------------------------------------------- processors: - decode_csv_fields: fields: message: decoded.csv separator: , ignore_missing: false overwrite_keys: true trim_leading_whitespace: false fail_on_error: true ----------------------------------------------------- The `decode_csv_fields` has the following settings: `fields`:: This is a mapping from the source field containing the CSV data to the destination field to which the decoded array will be written. `separator`:: (Optional) Character to be used as a column separator. The default is the comma character. For using a TAB character you must set it to ""\\t"". `ignore_missing`:: (Optional) Whether to ignore events which lack the source field. The default is `false`, which will fail processing of an event if a field is missing. `overwrite_keys`:: Whether the target field is overwritten if it already exists. The default is false, which will fail processing of an event when `target` already exists. `trim_leading_space`:: Whether extra space after the separator is trimmed from values. This works even if the separator is also a space. The default is `false`. `fail_on_error`:: (Optional) If set to true, in case of an error the changes to the event are reverted, and the original event is returned. If set to `false`, processing continues also if an error happens. Default is `true`. endif::[] [[decode-json-fields]] === Decode JSON fields The `decode_json_fields` processor decodes fields containing JSON strings and replaces the strings with valid JSON objects. [source,yaml] ----------------------------------------------------- processors: - decode_json_fields: fields: [""field1"", ""field2"", ...] process_array: false max_depth: 1 target: """" overwrite_keys: false ----------------------------------------------------- The `decode_json_fields` processor has the following configuration settings: `fields`:: The fields containing JSON strings to decode. `process_array`:: (Optional) A boolean that specifies whether to process arrays. The default is false. `max_depth`:: (Optional) The maximum parsing depth. The default is 1. `target`:: (Optional) The field under which the decoded JSON will be written. By default the decoded JSON object replaces the string field from which it was read. To merge the decoded JSON fields into the root of the event, specify `target` with an empty string (`target: """"`). Note that the `null` value (`target:`) is treated as if the field was not set at all. `overwrite_keys`:: (Optional) A boolean that specifies whether keys that already exist in the event are overwritten by keys from the decoded JSON object. The default value is false. [[community-id]] === Community ID Network Flow Hash The `community_id` processor computes a network flow hash according to the https://github.com/corelight/community-id-spec[Community ID Flow Hash specification]. The flow hash is useful for correlating all network events related to a single flow. For example you can filter on a community ID value and you might get back the Netflow records from multiple collectors and layer 7 protocol records from Packetbeat. By default the processor is configured to read the flow parameters from the appropriate Elastic Common Schema (ECS) fields. If you are processing ECS data then no parameters are required. [source,yaml] ---- processors: - community_id: ---- If the data does not conform to ECS then you can customize the field names that the processor reads from. You can also change the `target` field which is where the computed hash is written to. [source,yaml] ---- processors: - community_id: fields: source_ip: my_source_ip source_port: my_source_port destination_ip: my_dest_ip destination_port: my_dest_port transport: proto icmp_type: my_icmp_type icmp_code: my_icmp_code target: network.community_id ---- If the necessary fields are not present in the event then the processor will silently continue without adding the target field. The processor also accepts an optional `seed` parameter that must be a 16-bit unsigned integer. This value gets incorporated into all generated hashes. [[convert]] === Convert The `convert` processor converts a field in the event to a different type, such as converting a string to an integer. The supported types include: `integer`, `long`, `float`, `double`, `string`, `boolean`, and `ip`. The `ip` type is effectively an alias for `string`, but with an added validation that the value is an IPv4 or IPv6 address. [source,yaml] ---- processors: - convert: fields: - {from: ""src_ip"", to: ""source.ip"", type: ""ip""} - {from: ""src_port"", to: ""source.port"", type: ""integer""} ignore_missing: true fail_on_error: false ---- The `convert` processor has the following configuration settings: `fields`:: (Required) This is the list of fields to convert. At least one item must be contained in the list. Each item in the list must have a `from` key that specifies the source field. The `to` key is optional and specifies where to assign the converted value. If `to` is omitted then the `from` field is updated in-place. The `type` key specifies the data type to convert the value to. If `type` is omitted then the processor copies or renames the field without any type conversion. `ignore_missing`:: (Optional) If `true` the processor continues to the next field when the `from` key is not found in the event. If false then the processor returns an error and does not process the remaining fields. Default is `false`. `fail_on_error`:: (Optional) If false type conversion failures are ignored and the processor continues to the next field. Default is `true`. `tag`:: (Optional) An identifier for this processor. Useful for debugging. `mode`:: (Optional) When both `from` and `to` are defined for a field then `mode` controls whether to `copy` or `rename` the field when the type conversion is successful. Default is `copy`. [[drop-event]] === Drop events The `drop_event` processor drops the entire event if the associated condition is fulfilled. The condition is mandatory, because without one, all the events are dropped. [source,yaml] ------ processors: - drop_event: when: condition ------ See <> for a list of supported conditions. [[drop-fields]] === Drop fields from events The `drop_fields` processor specifies which fields to drop if a certain condition is fulfilled. The condition is optional. If it's missing, the specified fields are always dropped. The `@timestamp` and `type` fields cannot be dropped, even if they show up in the `drop_fields` list. [source,yaml] ----------------------------------------------------- processors: - drop_fields: when: condition fields: [""field1"", ""field2"", ...] ----------------------------------------------------- See <> for a list of supported conditions. NOTE: If you define an empty list of fields under `drop_fields`, then no fields are dropped. [[include-fields]] === Keep fields from events The `include_fields` processor specifies which fields to export if a certain condition is fulfilled. The condition is optional. If it's missing, the specified fields are always exported. The `@timestamp` and `type` fields are always exported, even if they are not defined in the `include_fields` list. [source,yaml] ------- processors: - include_fields: when: condition fields: [""field1"", ""field2"", ...] ------- See <> for a list of supported conditions. You can specify multiple `include_fields` processors under the `processors` section. NOTE: If you define an empty list of fields under `include_fields`, then only the required fields, `@timestamp` and `type`, are exported. [[rename-fields]] === Rename fields from events The `rename` processor specifies a list of fields to rename. Under the `fields` key each entry contains a `from: old-key` and a `to: new-key` pair. `from` is the origin and `to` the target name of the field. Renaming fields can be useful in cases where field names cause conflicts. For example if an event has two fields, `c` and `c.b`, that are both assigned scalar values (e.g. `{""c"": 1, ""c.b"": 2}`) this will result in an Elasticsearch error at ingest time. This is because the value of a cannot simultaneously be a scalar and an object. To prevent this rename_fields can be used to rename `c` to `c.value`. Rename fields cannot be used to overwrite fields. To overwrite fields either first rename the target field or use the `drop_fields` processor to drop the field and then rename the field. [source,yaml] ------- processors: - rename: fields: - from: ""a.g"" to: ""e.d"" ignore_missing: false fail_on_error: true ------- The `rename` processor has the following configuration settings: `ignore_missing`:: (Optional) If set to true, no error is logged in case a key which should be renamed is missing. Default is `false`. `fail_on_error`:: (Optional) If set to true, in case of an error the renaming of fields is stopped and the original event is returned. If set to false, renaming continues also if an error happened during renaming. Default is `true`. See <> for a list of supported conditions. You can specify multiple `ignore_missing` processors under the `processors` section. [[add-kubernetes-metadata]] === Add Kubernetes metadata The `add_kubernetes_metadata` processor annotates each event with relevant metadata based on which Kubernetes pod the event originated from. Each event is annotated with: * Pod Name * Pod UID * Namespace * Labels The `add_kubernetes_metadata` processor has two basic building blocks which are: * Indexers * Matchers Indexers take in a pod's metadata and builds indices based on the pod metadata. For example, the `ip_port` indexer can take a Kubernetes pod and index the pod metadata based on all `pod_ip:container_port` combinations. Matchers are used to construct lookup keys for querying indices. For example, when the `fields` matcher takes `[""metricset.host""]` as a lookup field, it would construct a lookup key with the value of the field `metricset.host`. Each Beat can define its own default indexers and matchers which are enabled by default. For example, FileBeat enables the `container` indexer, which indexes pod metadata based on all container IDs, and a `logs_path` matcher, which takes the `log.file.path` field, extracts the container ID, and uses it to retrieve metadata. The configuration below enables the processor when {beatname_lc} is run as a pod in Kubernetes. [source,yaml] ------------------------------------------------------------------------------- processors: - add_kubernetes_metadata: in_cluster: true ------------------------------------------------------------------------------- The configuration below enables the processor on a Beat running as a process on the Kubernetes node. [source,yaml] ------------------------------------------------------------------------------- processors: - add_kubernetes_metadata: in_cluster: false host: kube_config: ${HOME}/.kube/config ------------------------------------------------------------------------------- The configuration below has the default indexers and matchers disabled and enables ones that the user is interested in. [source,yaml] ------------------------------------------------------------------------------- processors: - add_kubernetes_metadata: in_cluster: false host: kube_config: ~/.kube/config default_indexers.enabled: false default_matchers.enabled: false indexers: - ip_port: matchers: - fields: lookup_fields: [""metricset.host""] ------------------------------------------------------------------------------- The `add_kubernetes_metadata` processor has the following configuration settings: `in_cluster`:: (Optional) Use in cluster settings for Kubernetes client, `true` by default. `host`:: (Optional) Identify the node where {beatname_lc} is running in case it cannot be accurately detected, as when running {beatname_lc} in host network mode. `namespace`:: (Optional) Select the namespace from which to collect the metadata. If it is not set, the processor collects metadata from all namespaces. It is unset by default. `kube_config`:: (Optional) Use given config file as configuration for Kubernetes client. `default_indexers.enabled`:: (Optional) Enable/Disable default pod indexers, in case you want to specify your own. `default_matchers.enabled`:: (Optional) Enable/Disable default pod matchers, in case you want to specify your own. [[add-docker-metadata]] === Add Docker metadata The `add_docker_metadata` processor annotates each event with relevant metadata from Docker containers: * Container ID * Name * Image * Labels [NOTE] ===== When running {beatname_uc} in a container, you need to provide access to Docker’s unix socket in order for the `add_docker_metadata` processor to work. You can do this by mounting the socket inside the container. For example: `docker run -v /var/run/docker.sock:/var/run/docker.sock ...` To avoid privilege issues, you may also need to add `--user=root` to the `docker run` flags. Because the user must be part of the docker group in order to access `/var/run/docker.sock`, root access is required if {beatname_uc} is running as non-root inside the container. ===== [source,yaml] ------------------------------------------------------------------------------- processors: - add_docker_metadata: host: ""unix:///var/run/docker.sock"" #match_fields: [""system.process.cgroup.id""] #match_pids: [""process.pid"", ""process.ppid""] #match_source: true #match_source_index: 4 #match_short_id: true #cleanup_timeout: 60 #labels.dedot: false # To connect to Docker over TLS you must specify a client and CA certificate. #ssl: # certificate_authority: ""/etc/pki/root/ca.pem"" # certificate: ""/etc/pki/client/cert.pem"" # key: ""/etc/pki/client/cert.key"" ------------------------------------------------------------------------------- It has the following settings: `host`:: (Optional) Docker socket (UNIX or TCP socket). It uses `unix:///var/run/docker.sock` by default. `ssl`:: (Optional) SSL configuration to use when connecting to the Docker socket. `match_fields`:: (Optional) A list of fields to match a container ID, at least one of them should hold a container ID to get the event enriched. `match_pids`:: (Optional) A list of fields that contain process IDs. If the process is running in Docker then the event will be enriched. The default value is `[""process.pid"", ""process.ppid""]`. `match_source`:: (Optional) Match container ID from a log path present in the `log.file.path` field. Enabled by default. `match_short_id`:: (Optional) Match container short ID from a log path present in the `log.file.path` field. Disabled by default. This allows to match directories names that have the first 12 characters of the container ID. For example, `/var/log/containers/b7e3460e2b21/*.log`. `match_source_index`:: (Optional) Index in the source path split by `/` to look for container ID. It defaults to 4 to match `/var/lib/docker/containers//*.log` `cleanup_timeout`:: (Optional) Time of inactivity to consider we can clean and forget metadata for a container, 60s by default. `labels.dedot`:: (Optional) Default to be false. If set to true, replace dots in labels with `_`. [[add-host-metadata]] === Add Host metadata beta[] [source,yaml] ------------------------------------------------------------------------------- processors: - add_host_metadata: netinfo.enabled: false cache.ttl: 5m geo: name: nyc-dc1-rack1 location: 40.7128, -74.0060 continent_name: North America country_iso_code: US region_name: New York region_iso_code: NY city_name: New York ------------------------------------------------------------------------------- It has the following settings: `netinfo.enabled`:: (Optional) Default false. Include IP addresses and MAC addresses as fields host.ip and host.mac `cache.ttl`:: (Optional) The processor uses an internal cache for the host metadata. This sets the cache expiration time. The default is 5m, negative values disable caching altogether. `geo.name`:: User definable token to be used for identifying a discrete location. Frequently a datacenter, rack, or similar. `geo.location`:: Longitude and latitude in comma separated format. `geo.continent_name`:: Name of the continent. `geo.country_name`:: Name of the country. `geo.region_name`:: Name of the region. `geo.city_name`:: Name of the city. `geo.country_iso_code`:: ISO country code. `geo.region_iso_code`:: ISO region code. The `add_host_metadata` processor annotates each event with relevant metadata from the host machine. The fields added to the event look like the following: [source,json] ------------------------------------------------------------------------------- { ""host"":{ ""architecture"":""x86_64"", ""name"":""example-host"", ""id"":"""", ""os"":{ ""family"":""darwin"", ""build"":""16G1212"", ""platform"":""darwin"", ""version"":""10.12.6"", ""kernel"":""16.7.0"", ""name"":""Mac OS X"" }, ""ip"": [""192.168.0.1"", ""10.0.0.1""], ""mac"": [""00:25:96:12:34:56"", ""72:00:06:ff:79:f1""], ""geo"": { ""continent_name"": ""North America"", ""country_iso_code"": ""US"", ""region_name"": ""New York"", ""region_iso_code"": ""NY"", ""city_name"": ""New York"", ""name"": ""nyc-dc1-rack1"", ""location"": ""40.7128, -74.0060"" } } } ------------------------------------------------------------------------------- [[add-observer-metadata]] === Add Observer metadata beta[] [source,yaml] ------------------------------------------------------------------------------- processors: - add_observer_metadata: netinfo.enabled: false cache.ttl: 5m geo: name: nyc-dc1-rack1 location: 40.7128, -74.0060 continent_name: North America country_iso_code: US region_name: New York region_iso_code: NY city_name: New York ------------------------------------------------------------------------------- It has the following settings: `netinfo.enabled`:: (Optional) Default false. Include IP addresses and MAC addresses as fields observer.ip and observer.mac `cache.ttl`:: (Optional) The processor uses an internal cache for the observer metadata. This sets the cache expiration time. The default is 5m, negative values disable caching altogether. `geo.name`:: User definable token to be used for identifying a discrete location. Frequently a datacenter, rack, or similar. `geo.location`:: Longitude and latitude in comma separated format. `geo.continent_name`:: Name of the continent. `geo.country_name`:: Name of the country. `geo.region_name`:: Name of the region. `geo.city_name`:: Name of the city. `geo.country_iso_code`:: ISO country code. `geo.region_iso_code`:: ISO region code. The `add_geo_metadata` processor annotates each event with relevant metadata from the observer machine. The fields added to the event look like the following: [source,json] ------------------------------------------------------------------------------- { ""observer"" : { ""hostname"" : ""avce"", ""type"" : ""heartbeat"", ""vendor"" : ""elastic"", ""ip"" : [ ""192.168.1.251"", ""fe80::64b2:c3ff:fe5b:b974"", ], ""mac"" : [ ""dc:c1:02:6f:1b:ed"", ], ""geo"": { ""continent_name"": ""North America"", ""country_iso_code"": ""US"", ""region_name"": ""New York"", ""region_iso_code"": ""NY"", ""city_name"": ""New York"", ""name"": ""nyc-dc1-rack1"", ""location"": ""40.7128, -74.0060"" } } } ------------------------------------------------------------------------------- [[dissect]] === Dissect strings The dissect processor tokenizes incoming strings using defined patterns. [source,yaml] ------- processors: - dissect: tokenizer: ""%{key1} %{key2}"" field: ""message"" target_prefix: ""dissect"" ------- The `dissect` processor has the following configuration settings: `field`:: (Optional) The event field to tokenize. Default is `message`. `target_prefix`:: (Optional) The name of the field where the values will be extracted. When an empty string is defined, the processor will create the keys at the root of the event. Default is `dissect`. When the target key already exists in the event, the processor won't replace it and log an error; you need to either drop or rename the key before using dissect. For tokenization to be successful, all keys must be found and extracted, if one of them cannot be found an error will be logged and no modification is done on the original event. NOTE: A key can contain any characters except reserved suffix or prefix modifiers: `/`,`&`, `+` and `?`. See <> for a list of supported conditions. [[processor-dns]] === DNS Reverse Lookup The DNS processor performs reverse DNS lookups of IP addresses. It caches the responses that it receives in accordance to the time-to-live (TTL) value contained in the response. It also caches failures that occur during lookups. Each instance of this processor maintains its own independent cache. The processor uses its own DNS resolver to send requests to nameservers and does not use the operating system's resolver. It does not read any values contained in `/etc/hosts`. This processor can significantly slow down your pipeline's throughput if you have a high latency network or slow upstream nameserver. The cache will help with performance, but if the addresses being resolved have a high cardinality then the cache benefits will be diminished due to the high miss ratio. By way of example, if each DNS lookup takes 2 milliseconds, the maximum throughput you can achieve is 500 events per second (1000 milliseconds / 2 milliseconds). If you have a high cache hit ratio then your throughput can be higher. This is a minimal configuration example that resolves the IP addresses contained in two fields. [source,yaml] ---- processors: - dns: type: reverse fields: source.ip: source.hostname destination.ip: destination.hostname ---- Next is a configuration example showing all options. [source,yaml] ---- processors: - dns: type: reverse action: append fields: server.ip: server.hostname client.ip: client.hostname success_cache: capacity.initial: 1000 capacity.max: 10000 failure_cache: capacity.initial: 1000 capacity.max: 10000 ttl: 1m nameservers: ['192.0.2.1', '203.0.113.1'] timeout: 500ms tag_on_failure: [_dns_reverse_lookup_failed] ---- The `dns` processor has the following configuration settings: `type`:: The type of DNS lookup to perform. The only supported type is `reverse` which queries for a PTR record. `action`:: This defines the behavior of the processor when the target field already exists in the event. The options are `append` (default) and `replace`. `fields`:: This is a mapping of source field names to target field names. The value of the source field will be used in the DNS query and result will be written to the target field. `success_cache.capacity.initial`:: The initial number of items that the success cache will be allocated to hold. When initialized the processor will allocate the memory for this number of items. Default value is `1000`. `success_cache.capacity.max`:: The maximum number of items that the success cache can hold. When the maximum capacity is reached a random item is evicted. Default value is `10000`. `failure_cache.capacity.initial`:: The initial number of items that the failure cache will be allocated to hold. When initialized the processor will allocate the memory for this number of items. Default value is `1000`. `failure_cache.capacity.max`:: The maximum number of items that the failure cache can hold. When the maximum capacity is reached a random item is evicted. Default value is `10000`. `failure_cache.ttl`:: The duration for which failures are cached. Valid time units are ""ns"", ""us"" (or ""µs""), ""ms"", ""s"", ""m"", ""h"". Default value is `1m`. `nameservers`:: A list of nameservers to query. If there are multiple servers, the resolver queries them in the order listed. If none are specified then it will read the nameservers listed in `/etc/resolv.conf` once at initialization. On Windows you must always supply at least one nameserver. `timeout`:: The duration after which a DNS query will timeout. This is timeout for each DNS request so if you have 2 nameservers then the total timeout will be 2 times this value. Valid time units are ""ns"", ""us"" (or ""µs""), ""ms"", ""s"", ""m"", ""h"". Default value is `500ms`. `tag_on_failure`:: A list of tags to add to the event when any lookup fails. The tags are only added once even if multiple lookups fail. By default no tags are added upon failure. [[add-process-metadata]] === Add process metadata The Add process metadata processor enriches events with information from running processes, identified by their process ID (PID). [source,yaml] ------------------------------------------------------------------------------- processors: - add_process_metadata: match_pids: [system.process.ppid] target: system.process.parent ------------------------------------------------------------------------------- The fields added to the event look as follows: [source,json] ------------------------------------------------------------------------------- ""process"": { ""name"": ""systemd"", ""title"": ""/usr/lib/systemd/systemd --switched-root --system --deserialize 22"", ""exe"": ""/usr/lib/systemd/systemd"", ""args"": [""/usr/lib/systemd/systemd"", ""--switched-root"", ""--system"", ""--deserialize"", ""22""], ""pid"": 1, ""ppid"": 0, ""start_time"": ""2018-08-22T08:44:50.684Z"", } ------------------------------------------------------------------------------- Optionally, the process environment can be included, too: [source,json] ------------------------------------------------------------------------------- ... ""env"": { ""HOME"": ""/"", ""TERM"": ""linux"", ""BOOT_IMAGE"": ""/boot/vmlinuz-4.11.8-300.fc26.x86_64"", ""LANG"": ""en_US.UTF-8"", } ... ------------------------------------------------------------------------------- It has the following settings: `match_pids`:: List of fields to lookup for a PID. The processor will search the list sequentially until the field is found in the current event, and the PID lookup will be applied to the value of this field. `target`:: (Optional) Destination prefix where the `process` object will be created. The default is the event's root. `include_fields`:: (Optional) List of fields to add. By default, the processor will add all the available fields except `process.env`. `ignore_missing`:: (Optional) When set to `false`, events that don't contain any of the fields in match_pids will be discarded and an error will be generated. By default, this condition is ignored. `overwrite_keys`:: (Optional) By default, if a target field already exists, it will not be overwritten and an error will be logged. If `overwrite_keys` is set to `true`, this condition will be ignored. `restricted_fields`:: (Optional) By default, the `process.env` field is not output, to avoid leaking sensitive data. If `restricted_fields` is `true`, the field will be present in the output. ifdef::has_script_processor[] [[processor-script]] === Script Processor experimental[] The script processor executes Javascript code to process an event. The processor uses a pure Go implementation of ECMAScript 5.1 and has no external dependencies. This can be useful in situations where one of the other processors doesn't provide the functionality you need to filter events. The processor can be configured by embedding Javascript in your configuration file or by pointing the processor at external file(s). [source,yaml] ---- processors: - script: lang: javascript id: my_filter source: > function process(event) { event.Tag(""js""); } ---- This loads `filter.js` from disk. [source,yaml] ---- processors: - script: lang: javascript id: my_filter file: ${path.config}/filter.js ---- Parameters can be passed to the script by adding `params` to the config. This allows for a script to be made reusable. When using `params` the code must define a `register(params)` function to receive the parameters. [source,yaml] ---- processors: - script: lang: javascript id: my_filter params: threshold: 15 source: > var params = {threshold: 42}; function register(scriptParams) { params = scriptParams; } function process(event) { if (event.Get(""severity"") < params.threshold) { event.Cancel(); } } ---- If the script defines a `test()` function it will be invoked when the processor is loaded. Any exceptions thrown will cause the processor to fail to load. This can be used to make assertions about the behavior of the script. [source,javascript] ---- function process(event) { if (event.Get(""event.code"") === 1102) { event.Put(""event.action"", ""cleared""); } } function test() { var event = process(new Event({event: {code: 1102})); if (event.Get(""event.action"") !== ""cleared"") { throw ""expected event.action === cleared""; } } ---- [float] ==== Configuration options The `script` processor has the following configuration settings: `lang`:: This field is required and its value must be `javascript`. `tag`:: This is an optional identifier that is added to log messages. If defined it enables metrics logging for this instance of the processor. The metrics include the number of exceptions and a histogram of the execution times for the `process` function. `source`:: Inline Javascript source code. `file`:: Path to a script file to load. Relative paths are interpreted as relative to the `path.config` directory. Globs are expanded. `files`:: List of script files to load. The scripts are concatenated together. Relative paths are interpreted as relative to the `path.config` directory. And globs are expanded. `params`:: A dictionary of parameters that are passed to the `register` of the script. `tag_on_exception`:: Tag to add to events in case the Javascript code causes an exception while processing an event. Defaults to `_js_exception`. `timeout`:: This sets an execution timeout for the `process` function. When the `process` function takes longer than the `timeout` period the function is interrupted. You can set this option to prevent a script from running for too long (like preventing an infinite `while` loop). By default there is no timeout. [float] ==== Event API The `Event` object passed to the `process` method has the following API. [frame=""topbot"",options=""header""] |=== |Method |Description |`Get(string)` |Get a value from the event (either a scalar or an object). If the key does not exist `null` is returned. If no key is provided then an object containing all fields is returned. *Example*: `var value = event.Get(key);` |`Put(string, value)` |Put a value into the event. If the key was already set then the previous value is returned. It throws an exception if the key cannot be set because one of the intermediate values is not an object. *Example*: `var old = event.Put(key, value);` |`Rename(string, string)` |Rename a key in the event. The target key must not exist. It returns true if the source key was successfully renamed to the target key. *Example*: `var success = event.Rename(""source"", ""target"");` |`Delete(string)` |Delete a field from the event. It returns true on success. *Example*: `var deleted = event.Delete(""user.email"");` |`Cancel()` |Flag the event as cancelled which causes the processor to drop event. *Example*: `event.Cancel(); return;` |`Tag(string)` |Append a tag to the `tags` field if the tag does not already exist. Throws an exception if `tags` exists and is not a string or a list of strings. *Example*: `event.Tag(""user_event"");` |`AppendTo(string, string)` |`AppendTo` is a specialized `Put` method that converts the existing value to an array and appends the value if it does not already exist. If there is an existing value that's not a string or array of strings then an exception is thrown. *Example*: `event.AppendTo(""error.message"", ""invalid file hash"");` |=== endif::[] [[extract-array]] === Extract array experimental[] The `extract_array` processor populates fields with values read from an array field. The following example will populate `source.ip` with the first element of the `my_array` field, `destination.ip` with the second element, and `network.transport` with the third. [source,yaml] ----------------------------------------------------- processors: - extract_array: field: my_array mappings: source.ip: 0 destination.ip: 1 network.transport: 2 ----------------------------------------------------- The following settings are supported: `field`:: The array field whose elements are to be extracted. `mappings`:: Maps each field name to an array index. Use 0 for the first element in the array. Multiple fields can be mapped to the same array element. `ignore_missing`:: (Optional) Whether to ignore events where the array field is missing. The default is `false`, which will fail processing of an event if the specified field does not exist. Set it to `true` to ignore this condition. `overwrite_keys`:: Whether the target fields specified in the mapping are overwritten if they already exist. The default is `false`, which will fail processing if a target field already exists. `fail_on_error`:: (Optional) If set to `true` and an error happens, changes to the event are reverted, and the original event is returned. If set to `false`, processing continues despite errors. Default is `true`. `omit_empty`:: (Optional) Whether empty values are extracted from the array. If set to `true`, instead of the target field being set to an empty value, it is left unset. The empty string (`""""`), an empty array (`[]`) or an empty object (`{}`) are considered empty values. Default is `false`. ",12481,False,2023.0027922804413,median "[[_auth_spi]] == Authentication SPI {project_name} includes a range of different authentication mechanisms: kerberos, password, otp and others. These mechanisms may not meet all of your requirements and you may want to plug in your own custom ones. {project_name} provides an authentication SPI that you can use to write new plugins. The Admin Console supports applying, ordering, and configuring these new mechanisms. {project_name} also supports a simple registration form. Different aspects of this form can be enabled and disabled for example Recaptcha support can be turned off and on. The same authentication SPI can be used to add another page to the registration flow or reimplement it entirely. There's also an additional fine-grained SPI you can use to add specific validations and user extensions to the built in registration form. A required action in {project_name} is an action that a user has to perform after he authenticates. After the action is performed successfully, the user doesn't have to perform the action again. {project_name} comes with some built in required actions like ""reset password"". This action forces the user to change their password after they have logged in. You can write and plug in your own required actions. WARNING: If your authenticator or required action implementation is using some user attributes as the metadata attributes for linking/establishing the user identity, then please make sure that users are not able to edit the attributes and the corresponding attributes are read-only. See the details in the link:{adminguide_link}#_read_only_user_attributes[Threat model mitigation chapter]. === Terms To first learn about the Authentication SPI, let's go over some of the terms used to describe it. Authentication Flow:: A flow is a container for all authentications that must happen during login or registration. If you go to the Admin Console authentication page, you can view all the defined flows in the system and what authenticators they are made up of. Flows can contain other flows. You can also bind a new different flow for browser login, direct grant access, and registration. Authenticator:: An authenticator is a pluggable component that hold the logic for performing the authentication or action within a flow. It is usually a singleton. Execution:: An execution is an object that binds the authenticator to the flow and the authenticator to the configuration of the authenticator. Flows contain execution entries. Execution Requirement:: Each execution defines how an authenticator behaves in a flow. The requirement defines whether the authenticator is enabled, disabled, conditional, required, or an alternative. An alternative requirement means that the authenticator is enough to validate the flow it's in, but isn't necessary. For example, in the built-in browser flow, cookie authentication, the Identity Provider Redirector, and the set of all authenticators in the forms subflow are all alternative. As they are executed in a sequential top-to-bottom order, if one of them is successful, the flow is successful, and any following execution in the flow (or sub-flow) is not evaluated. Authenticator Config:: This object defines the configuration for the Authenticator for a specific execution within an authentication flow. Each execution can have a different config. Required Action:: After authentication completes, the user might have one or more one-time actions he must complete before he is allowed to login. The user might be required to set up an OTP token generator or reset an expired password or even accept a Terms and Conditions document. === Algorithm overview Let's talk about how this all works for browser login. Let's assume the following flows, executions and sub flows. [source] ---- Cookie - ALTERNATIVE Kerberos - ALTERNATIVE Forms subflow - ALTERNATIVE Username/Password Form - REQUIRED Conditional OTP subflow - CONDITIONAL Condition - User Configured - REQUIRED OTP Form - REQUIRED ---- In the top level of the form we have 3 executions of which all are alternatively required. This means that if any of these are successful, then the others do not have to execute. The Username/Password form is not executed if there is an SSO Cookie set or a successful Kerberos login. Let's walk through the steps from when a client first redirects to keycloak to authenticate the user. . The OpenID Connect or SAML protocol provider unpacks relevant data, verifies the client and any signatures. It creates an AuthenticationSessionModel. It looks up what the browser flow should be, then starts executing the flow. . The flow looks at the cookie execution and sees that it is an alternative. It loads the cookie provider. It checks to see if the cookie provider requires that a user already be associated with the authentication session. Cookie provider does not require a user. If it did, the flow would abort and the user would see an error screen. Cookie provider then executes. Its purpose is to see if there is an SSO cookie set. If there is one set, it is validated and the UserSessionModel is verified and associated with the AuthenticationSessionModel. The Cookie provider returns a success() status if the SSO cookie exists and is validated. Since the cookie provider returned success and each execution at this level of the flow is ALTERNATIVE, no other execution is executed and this results in a successful login. If there is no SSO cookie, the cookie provider returns with a status of attempted(). This means there was no error condition, but no success either. The provider tried, but the request just wasn't set up to handle this authenticator. . Next the flow looks at the Kerberos execution. This is also an alternative. The kerberos provider also does not require a user to be already set up and associated with the AuthenticationSessionModel so this provider is executed. Kerberos uses the SPNEGO browser protocol. This requires a series of challenge/responses between the server and client exchanging negotiation headers. The kerberos provider does not see any negotiate header, so it assumes that this is the first interaction between the server and client. It therefore creates an HTTP challenge response to the client and sets a forceChallenge() status. A forceChallenge() means that this HTTP response cannot be ignored by the flow and must be returned to the client. If instead the provider returned a challenge() status, the flow would hold the challenge response until all other alternatives are attempted. So, in this initial phase, the flow would stop and the challenge response would be sent back to the browser. If the browser then responds with a successful negotiate header, the provider associates the user with the AuthenticationSession and the flow ends because the rest of the executions on this level of the flow are all alternatives. Otherwise, again, the kerberos provider sets an attempted() status and the flow continues. . The next execution is a subflow called Forms. The executions for this subflow are loaded and the same processing logic occurs. . The first execution in the Forms subflow is the UsernamePassword provider. This provider also does not require for a user to already be associated with the flow. This provider creates a challenge HTTP response and sets its status to challenge(). This execution is required, so the flow honors this challenge and sends the HTTP response back to the browser. This response is a rendering of the Username/Password HTML page. The user enters in their username and password and clicks submit. This HTTP request is directed to the UsernamePassword provider. If the user entered an invalid username or password, a new challenge response is created and a status of failureChallenge() is set for this execution. A failureChallenge() means that there is a challenge, but that the flow should log this as an error in the error log. This error log can be used to lock accounts or IP Addresses that have had too many login failures. If the username and password is valid, the provider associated the UserModel with the AuthenticationSessionModel and returns a status of success(). . The next execution is a subflow called Conditional OTP. The executions for this subflow are loaded and the same processing logic occurs. Its Requirement is Conditional. This means that the flow will first evaluate all conditional executors that it contains. Conditional executors are authenticators that implement `ConditionalAuthenticator`, and must implement the method `boolean matchCondition(AuthenticationFlowContext context)`. A conditional subflow will call the `matchCondition` method of all conditional executions it contains, and if all of them evaluate to true, it will act as if it was a required subflow. If not, it will act as if it was a disabled subflow. Conditional authenticators are only used for this purpose, and are not used as authenticators. This means that even if the conditional authenticator evaluates to ""true"", then this will not mark a flow or subflow as successful. For example, a flow containing only a Conditional subflow with only a conditional authenticator will never allow a user to log in. . The first execution of the Conditional OTP subflow is the Condition - User Configured. This provider requires that a user has been associated with the flow. This requirement is satisfied because the UsernamePassword provider already associated the user with the flow. This provider's `matchCondition` method will evaluate the `configuredFor` method for all other Authenticators in its current subflow. If the subflow contains executors with their Requirement set to required, then the `matchCondition` method will only evaluate to true if all the required authenticators' `configuredFor` method evaluate to true. Otherwise, the `matchCondition` method will evaluate to true if any alternative authenticator evaluates to true. . The next execution is the OTP Form. This provider also requires that a user has been associated with the flow. This requirement is satisfied because the UsernamePassword provider already associated the user with the flow. Since a user is required for this provider, the provider is also asked if the user is configured to use this provider. If user is not configured, then the flow will then set up a required action that the user must perform after authentication is complete. For OTP, this means the OTP setup page. If the user is configured, he will be asked to enter his otp code. In our scenario, because of the conditional sub-flow, the user will never see the OTP login page, unless the Conditional OTP subflow is set to Required. . After the flow is complete, the authentication processor creates a UserSessionModel and associates it with the AuthenticationSessionModel. It then checks to see if the user is required to complete any required actions before logging in. . First, each required action's evaluateTriggers() method is called. This allows the required action provider to figure out if there is some state that might trigger the action to be fired. For example, if your realm has a password expiration policy, it might be triggered by this method. . Each required action associated with the user that has its requiredActionChallenge() method called. Here the provider sets up an HTTP response which renders the page for the required action. This is done by setting a challenge status. . If the required action is ultimately successful, then the required action is removed from the user's required actions list. . After all required actions have been resolved, the user is finally logged in. [[_auth_spi_walkthrough]] === Authenticator SPI walk through In this section, we'll take a look at the Authenticator interface. For this, we are going to implement an authenticator that requires that a user enter in the answer to a secret question like ""What is your mother's maiden name?"". This example is fully implemented and contained in the examples/providers/authenticator directory of the demo distribution of {project_name}. To create an authenticator, you must at minimum implement the org.keycloak.authentication.AuthenticatorFactory and Authenticator interfaces. The Authenticator interface defines the logic. The AuthenticatorFactory is responsible for creating instances of an Authenticator. They both extend a more generic Provider and ProviderFactory set of interfaces that other {project_name} components like User Federation do. Some authenticators, like the CookieAuthenticator don't rely on a Credential that the user has or knows to authenticate the user. However, some authenticators, such as the PasswordForm authenticator or the OTPFormAuthenticator rely on the user inputting some information and verifying that information against some information in the database. For the PasswordForm for example, the authenticator will verify the hash of the password against a hash stored in the database, while the OTPFormAuthenticator will verify the OTP received against the one generated from the shared secret stored in the database. These types of authenticators are called CredentialValidators, and will require you to implement a few more classes: * A class that extends org.keycloak.credential.CredentialModel, and that can generate the correct format of the credential in the database * A class implementing the org.keycloak.credential.CredentialProvider and interface, and a class implementing its CredentialProviderFactory factory interface. The SecretQuestionAuthenticator we'll see in this walk through is a CredentialValidator, so we'll see how to implement all these classes. ==== Packaging classes and deployment You will package your classes within a single jar. This jar must contain a file named `org.keycloak.authentication.AuthenticatorFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified class name of each AuthenticatorFactory implementation you have in the jar. For example: [source,java] ---- org.keycloak.examples.authenticator.SecretQuestionAuthenticatorFactory org.keycloak.examples.authenticator.AnotherProviderFactory ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the providers directory. ==== Extending the CredentialModel class In {project_name}, credentials are stored in the database in the Credentials table. It has the following structure: ---- ----------------------------- | ID | ----------------------------- | user_ID | ----------------------------- | credential_type | ----------------------------- | created_date | ----------------------------- | user_label | ----------------------------- | secret_data | ----------------------------- | credential_data | ----------------------------- | priority | ----------------------------- ---- Where: * `ID` is the primary key of the credential. * `user_ID` is the foreign key linking the credential to a user. * `credential_type` is a string set during the creation that must reference an existing credential type. * `created_date` is the creation timestamp (in long format) of the credential. * `user_label` is the editable name of the credential by the user * `secret_data` contains a static json with the information that cannot be transmitted outside of {project_name} * `credential_data` contains a json with the static information of the credential that can be shared in the Admin Console or via the REST API. * `priority` defines how ""preferred"" a credential is for a user, to determine which credential to present when a user has multiple choices. As the secret_data and credential_data fields are designed to contain json, it is up to you to determine how to structure, read and write into these fields, allowing you a lot of flexibility. For this example, we are going to use a very simple credential data, containing only the question asked to the user: [source] ---- { ""question"":""aQuestion"" } ---- with an equally simple secret data, containing only the secret answer: [source] ---- { ""answer"":""anAnswer"" } ---- Here the answer will be kept in plain text in the database for the sake of simplicity, but it would also be possible to have a salted hash for the answer, as is the case for passwords in {project_name}. In this case, the secret data would also have to contain a field for the salt, and the credential data information about the algorithm such as the type of algorithm used and the number of iterations used. For more details you can consult the implementation of the `org.keycloak.models.credential.PasswordCredentialModel` class. In our case we create the class `SecretQuestionCredentialModel`: [source,java] ---- public class SecretQuestionCredentialModel extends CredentialModel { public static final String TYPE = ""SECRET_QUESTION""; private final SecretQuestionCredentialData credentialData; private final SecretQuestionSecretData secretData; ---- Where `TYPE` is the credential_type we write in the database. For consistency, we make sure that this String is always the one referenced when getting the type for this credential. The classes `SecretQuestionCredentialData` and `SecretQuestionSecretData` are used to marshal and unmarshal the json: [source,java] ---- public class SecretQuestionCredentialData { private final String question; @JsonCreator public SecretQuestionCredentialData(@JsonProperty(""question"") String question) { this.question = question; } public String getQuestion() { return question; } } ---- [source,java] ---- public class SecretQuestionSecretData { private final String answer; @JsonCreator public SecretQuestionSecretData(@JsonProperty(""answer"") String answer) { this.answer = answer; } public String getAnswer() { return answer; } } ---- To be fully usable, the `SecretQuestionCredentialModel` objects must both contain the raw json data from its parent class, and the unmarshalled objects in its own attributes. This leads us to create a method which reads from a simple CredentialModel, such as is created when reading from the database, to make a `SecretQuestionCredentialModel`: [source,java] ---- private SecretQuestionCredentialModel(SecretQuestionCredentialData credentialData, SecretQuestionSecretData secretData) { this.credentialData = credentialData; this.secretData = secretData; } public static SecretQuestionCredentialModel createFromCredentialModel(CredentialModel credentialModel){ try { SecretQuestionCredentialData credentialData = JsonSerialization.readValue(credentialModel.getCredentialData(), SecretQuestionCredentialData.class); SecretQuestionSecretData secretData = JsonSerialization.readValue(credentialModel.getSecretData(), SecretQuestionSecretData.class); SecretQuestionCredentialModel secretQuestionCredentialModel = new SecretQuestionCredentialModel(credentialData, secretData); secretQuestionCredentialModel.setUserLabel(credentialModel.getUserLabel()); secretQuestionCredentialModel.setCreatedDate(credentialModel.getCreatedDate()); secretQuestionCredentialModel.setType(TYPE); secretQuestionCredentialModel.setId(credentialModel.getId()); secretQuestionCredentialModel.setSecretData(credentialModel.getSecretData()); secretQuestionCredentialModel.setCredentialData(credentialModel.getCredentialData()); return secretQuestionCredentialModel; } catch (IOException e){ throw new RuntimeException(e); } } ---- And a method to create a `SecretQuestionCredentialModel` from the question and answer: [source,java] ---- private SecretQuestionCredentialModel(String question, String answer) { credentialData = new SecretQuestionCredentialData(question); secretData = new SecretQuestionSecretData(answer); } public static SecretQuestionCredentialModel createSecretQuestion(String question, String answer) { SecretQuestionCredentialModel credentialModel = new SecretQuestionCredentialModel(question, answer); credentialModel.fillCredentialModelFields(); return credentialModel; } private void fillCredentialModelFields(){ try { setCredentialData(JsonSerialization.writeValueAsString(credentialData)); setSecretData(JsonSerialization.writeValueAsString(secretData)); setType(TYPE); setCreatedDate(Time.currentTimeMillis()); } catch (IOException e) { throw new RuntimeException(e); } } ---- ==== Implementing a CredentialProvider As with all Providers, to allow {project_name} to generate the CredentialProvider, we require a CredentialProviderFactory. For this requirement we create the SecretQuestionCredentialProviderFactory, whose `create` method will be called when a SecretQuestionCredentialProvider is asked for: [source,java] ---- public class SecretQuestionCredentialProviderFactory implements CredentialProviderFactory { public static final String PROVIDER_ID = ""secret-question""; @Override public String getId() { return PROVIDER_ID; } @Override public CredentialProvider create(KeycloakSession session) { return new SecretQuestionCredentialProvider(session); } } ---- The CredentialProvider interface takes a generic parameter that extends a CredentialModel. In our case we to use the SecretQuestionCredentialModel we created: [source,java] ---- public class SecretQuestionCredentialProvider implements CredentialProvider, CredentialInputValidator { private static final Logger logger = Logger.getLogger(SecretQuestionCredentialProvider.class); protected KeycloakSession session; public SecretQuestionCredentialProvider(KeycloakSession session) { this.session = session; } private UserCredentialStore getCredentialStore() { return session.userCredentialManager(); } ---- We also want to implement the CredentialInputValidator interface, as this allows {project_name} to know that this provider can also be used to validate a credential for an Authenticator. For the CredentialProvider interface, the first method that needs to be implemented is the `getType()` method. This will simply return the `SecretQuestionCredentialModel`'s TYPE String: [source,java] ---- @Override public String getType() { return SecretQuestionCredentialModel.TYPE; } ---- The second method is to create a `SecretQuestionCredentialModel` from a `CredentialModel`. For this method we simply call the existing static method from `SecretQuestionCredentialModel`: [source,java] ---- @Override public SecretQuestionCredentialModel getCredentialFromModel(CredentialModel model) { return SecretQuestionCredentialModel.createFromCredentialModel(model); } ---- Finally, we have the methods to create a credential and delete a credential. These methods call the KeycloakSession's `userCredentialManager`, which is responsible for knowing where to read or write the credential, for example local storage or federated storage. [source,java] ---- @Override public CredentialModel createCredential(RealmModel realm, UserModel user, SecretQuestionCredentialModel credentialModel) { if (credentialModel.getCreatedDate() == null) { credentialModel.setCreatedDate(Time.currentTimeMillis()); } return getCredentialStore().createCredential(realm, user, credentialModel); } @Override public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) { return getCredentialStore().removeStoredCredential(realm, user, credentialId); } ---- For the CredentialInputValidator, the main method to implement is the `isValid`, which tests whether a credential is valid for a given user in a given realm. This is the method that is called by the Authenticator when it seeks to validate the user's input. Here we simply need to check that the input String is the one recorded in the Credential: [source,java] ---- @Override public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { if (!(input instanceof UserCredentialModel)) { logger.debug(""Expected instance of UserCredentialModel for CredentialInput""); return false; } if (!input.getType().equals(getType())) { return false; } String challengeResponse = input.getChallengeResponse(); if (challengeResponse == null) { return false; } CredentialModel credentialModel = getCredentialStore().getStoredCredentialById(realm, user, input.getCredentialId()); SecretQuestionCredentialModel sqcm = getCredentialFromModel(credentialModel); return sqcm.getSecretQuestionSecretData().getAnswer().equals(challengeResponse); } ---- The other two methods to implement are a test if the CredentialProvider supports the given credential type and a test to check if the credential type is configured for a given user. For our case, the latter test simply means checking if the user has a credential of the SECRET_QUESTION type: [source,java] ---- @Override public boolean supportsCredentialType(String credentialType) { return getType().equals(credentialType); } @Override public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { if (!supportsCredentialType(credentialType)) return false; return !getCredentialStore().getStoredCredentialsByType(realm, user, credentialType).isEmpty(); } ---- ==== Implementing an authenticator When implementing an authenticator that uses Credentials to authenticate a user, you should have the authenticator implement the CredentialValidator interface. This interfaces takes a class extending a CredentialProvider as a parameter, and will allow {project_name} to directly call the methods from the CredentialProvider. The only method that needs to be implemented is `getCredentialProvider` method, which in our example allows the SecretQuestionAuthenticator to retrieve the SecretQuestionCredentialProvider: [source,java] ---- public SecretQuestionCredentialProvider getCredentialProvider(KeycloakSession session) { return (SecretQuestionCredentialProvider)session.getProvider(CredentialProvider.class, SecretQuestionCredentialProviderFactory.PROVIDER_ID); } ---- When implementing the Authenticator interface, the first method that needs to be implemented is the requiresUser() method. For our example, this method must return true as we need to validate the secret question associated with the user. A provider like kerberos would return false from this method as it can resolve a user from the negotiate header. This example, however, is validating a specific credential of a specific user. The next method to implement is the configuredFor() method. This method is responsible for determining if the user is configured for this particular authenticator. In our case, we can just call the method implemented in the SecretQuestionCredentialProvider [source,java] ---- @Override public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { return getCredentialProvider(session).isConfiguredFor(realm, user, getType(session)); } ---- The next method to implement on the Authenticator is setRequiredActions(). If configuredFor() returns false and our example authenticator is required within the flow, this method will be called, but only if the associated AuthenticatorFactory's `isUserSetupAllowed` method returns true. The setRequiredActions() method is responsible for registering any required actions that must be performed by the user. In our example, we need to register a required action that will force the user to set up the answer to the secret question. We will implement this required action provider later in this chapter. Here is the implementation of the setRequiredActions() method. [source,java] ---- @Override public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) { user.addRequiredAction(""SECRET_QUESTION_CONFIG""); } ---- Now we are getting into the meat of the Authenticator implementation. The next method to implement is authenticate(). This is the initial method the flow invokes when the execution is first visited. What we want is that if a user has answered the secret question already on their browser's machine, then the user doesn't have to answer the question again, making that machine ""trusted"". The authenticate() method isn't responsible for processing the secret question form. Its sole purpose is to render the page or to continue the flow. [source,java] ---- @Override public void authenticate(AuthenticationFlowContext context) { if (hasCookie(context)) { context.success(); return; } Response challenge = context.form() .createForm(""secret-question.ftl""); context.challenge(challenge); } protected boolean hasCookie(AuthenticationFlowContext context) { Cookie cookie = context.getHttpRequest().getHttpHeaders().getCookies().get(""SECRET_QUESTION_ANSWERED""); boolean result = cookie != null; if (result) { System.out.println(""Bypassing secret question because cookie is set""); } return result; } ---- The hasCookie() method checks to see if there is already a cookie set on the browser which indicates that the secret question has already been answered. If that returns true, we just mark this execution's status as SUCCESS using the AuthenticationFlowContext.success() method and returning from the authentication() method. If the hasCookie() method returns false, we must return a response that renders the secret question HTML form. AuthenticationFlowContext has a form() method that initializes a Freemarker page builder with appropriate base information needed to build the form. This page builder is called `org.keycloak.login.LoginFormsProvider`. The LoginFormsProvider.createForm() method loads a Freemarker template file from your login theme. Additionally you can call the LoginFormsProvider.setAttribute() method if you want to pass additional information to the Freemarker template. We'll go over this later. Calling LoginFormsProvider.createForm() returns a JAX-RS Response object. We then call AuthenticationFlowContext.challenge() passing in this response. This sets the status of the execution as CHALLENGE and if the execution is Required, this JAX-RS Response object will be sent to the browser. So, the HTML page asking for the answer to a secret question is displayed to the user and the user enters in the answer and clicks submit. The action URL of the HTML form will send an HTTP request to the flow. The flow will end up invoking the action() method of our Authenticator implementation. [source,java] ---- @Override public void action(AuthenticationFlowContext context) { boolean validated = validateAnswer(context); if (!validated) { Response challenge = context.form() .setError(""badSecret"") .createForm(""secret-question.ftl""); context.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, challenge); return; } setCookie(context); context.success(); } ---- If the answer is not valid, we rebuild the HTML Form with an additional error message. We then call AuthenticationFlowContext.failureChallenge() passing in the reason for the value and the JAX-RS response. failureChallenge() works the same as challenge(), but it also records the failure so it can be analyzed by any attack detection service. If validation is successful, then we set a cookie to remember that the secret question has been answered and we call AuthenticationFlowContext.success(). The validation itself gets the data that was received from the form, and calls the isValid method from the SecretQuestionCredentialProvider. You'll notice that there's a section of the code concerning getting the credential Id. This is because if {project_name} is configured to allow multiple types of alternative authenticators, or if the user could record multiple credentials of the SECRET_QUESTION type (for example if we allowed to choose from several questions, and we allowed the user to have answers for more than one of those questions), then {project_name} needs to know which credential is being used to log the user. In case there is more than one credential, {project_name} allows the user to choose during the login which credential is being used, and the information is transmitted by the form to the Authenticator. In case the form doesn't present this information, credential id used is given by the CredentialProvider's `default getDefaultCredential` method, which will return the ""most preferred"" credential of the correct type of the user, [source,java] ---- protected boolean validateAnswer(AuthenticationFlowContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); String secret = formData.getFirst(""secret_answer""); String credentialId = formData.getFirst(""credentialId""); if (credentialId == null || credentialId.isEmpty()) { credentialId = getCredentialProvider(context.getSession()) .getDefaultCredential(context.getSession(), context.getRealm(), context.getUser()).getId(); } UserCredentialModel input = new UserCredentialModel(credentialId, getType(context.getSession()), secret); return getCredentialProvider(context.getSession()).isValid(context.getRealm(), context.getUser(), input); } ---- Next method is the setCookie(). This is an example of providing configuration for the Authenticator. In this case we want the max age of the cookie to be configurable. [source,java] ---- protected void setCookie(AuthenticationFlowContext context) { AuthenticatorConfigModel config = context.getAuthenticatorConfig(); int maxCookieAge = 60 * 60 * 24 * 30; // 30 days if (config != null) { maxCookieAge = Integer.valueOf(config.getConfig().get(""cookie.max.age"")); } URI uri = context.getUriInfo().getBaseUriBuilder().path(""realms"").path(context.getRealm().getName()).build(); addCookie(context, ""SECRET_QUESTION_ANSWERED"", ""true"", uri.getRawPath(), null, null, maxCookieAge, false, true); } ---- We obtain an AuthenticatorConfigModel from the AuthenticationFlowContext.getAuthenticatorConfig() method. If configuration exists we pull the max age config out of it. We will see how we can define what should be configured when we talk about the AuthenticatorFactory implementation. The config values can be defined within the Admin Console if you set up config definitions in your AuthenticatorFactory implementation. [source,java] ---- @Override public CredentialTypeMetadata getCredentialTypeMetadata(CredentialTypeMetadataContext metadataContext) { return CredentialTypeMetadata.builder() .type(getType()) .category(CredentialTypeMetadata.Category.TWO_FACTOR) .displayName(SecretQuestionCredentialProviderFactory.PROVIDER_ID) .helpText(""secret-question-text"") .createAction(SecretQuestionAuthenticatorFactory.PROVIDER_ID) .removeable(false) .build(session); } ---- The last method to implement in the SecretQuestionCredentialProvider class is getCredentialTypeMetadata(CredentialTypeMetadataContext metadataContext), which is an abstract method of the CredentialProvider interface. Each Credential provider has to provide and implement this method. The method returns an instance of CredentialTypeMetadata, which should at least include type and category of authenticator, displayName and removable item. In this example, the builder takes type of authenticator from method getType(), category is Two Factor (the authenticator can be used as second factor of authentication) and removable, which is set up to false (user can't remove some previously registered credentials). Other items of builder are helpText (will be shown to the user on various screens), createAction (the providerID of the required action, which can be used by the user to create new credential) or updateAction (same as createAction, but instead of creating the new credential, it will update the credential). ==== Implementing an AuthenticatorFactory The next step in this process is to implement an AuthenticatorFactory. This factory is responsible for instantiating an Authenticator. It also provides deployment and configuration metadata about the Authenticator. The getId() method is just the unique name of the component. The create() method is called by the runtime to allocate and process the Authenticator. [source,java] ---- public class SecretQuestionAuthenticatorFactory implements AuthenticatorFactory, ConfigurableAuthenticatorFactory { public static final String PROVIDER_ID = ""secret-question-authenticator""; private static final SecretQuestionAuthenticator SINGLETON = new SecretQuestionAuthenticator(); @Override public String getId() { return PROVIDER_ID; } @Override public Authenticator create(KeycloakSession session) { return SINGLETON; } ---- The next thing the factory is responsible for is to specify the allowed requirement switches. While there are four different requirement types: ALTERNATIVE, REQUIRED, CONDITIONAL, DISABLED, AuthenticatorFactory implementations can limit which requirement options are shown in the Admin Console when defining a flow. CONDITIONAL should only always be used for subflows, and unless there's a good reason for doing otherwise, the requirement on a authenticator should be REQUIRED, ALTERNATIVE and DISABLED: [source,java] ---- private static AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = { AuthenticationExecutionModel.Requirement.REQUIRED, AuthenticationExecutionModel.Requirement.ALTERNATIVE, AuthenticationExecutionModel.Requirement.DISABLED }; @Override public AuthenticationExecutionModel.Requirement[] getRequirementChoices() { return REQUIREMENT_CHOICES; } ---- The AuthenticatorFactory.isUserSetupAllowed() is a flag that tells the flow manager whether or not Authenticator.setRequiredActions() method will be called. If an Authenticator is not configured for a user, the flow manager checks isUserSetupAllowed(). If it is false, then the flow aborts with an error. If it returns true, then the flow manager will invoke Authenticator.setRequiredActions(). [source,java] ---- @Override public boolean isUserSetupAllowed() { return true; } ---- The next few methods define how the Authenticator can be configured. The isConfigurable() method is a flag which specifies to the Admin Console on whether the Authenticator can be configured within a flow. The getConfigProperties() method returns a list of ProviderConfigProperty objects. These objects define a specific configuration attribute. [source,java] ---- @Override public List getConfigProperties() { return configProperties; } private static final List configProperties = new ArrayList(); static { ProviderConfigProperty property; property = new ProviderConfigProperty(); property.setName(""cookie.max.age""); property.setLabel(""Cookie Max Age""); property.setType(ProviderConfigProperty.STRING_TYPE); property.setHelpText(""Max age in seconds of the SECRET_QUESTION_COOKIE.""); configProperties.add(property); } ---- Each ProviderConfigProperty defines the name of the config property. This is the key used in the config map stored in AuthenticatorConfigModel. The label defines how the config option will be displayed in the Admin Console. The type defines if it is a String, Boolean, or other type. The Admin Console will display different UI inputs depending on the type. The help text is what will be shown in the tooltip for the config attribute in the Admin Console. Read the javadoc of ProviderConfigProperty for more detail. The rest of the methods are for the Admin Console. getHelpText() is the tooltip text that will be shown when you are picking the Authenticator you want to bind to an execution. getDisplayType() is the text that will be shown in the Admin Console when listing the Authenticator. getReferenceCategory() is just a category the Authenticator belongs to. ==== Adding an authenticator form {project_name} comes with a Freemarker <<_themes,theme and template engine>>. The createForm() method you called within authenticate() of your Authenticator class, builds an HTML page from a file within your login theme: `secret-question.ftl`. This file should be added to the `theme-resources/templates` in your JAR, see <<_theme_resource,Theme Resource Provider>> for more details. Let's take a bigger look at secret-question.ftl Here's a small code snippet: [source,java] ----
---- Any piece of text enclosed in `${}` corresponds to an attribute or template funtion. If you see the form's action, you see it points to `${url.loginAction}`. This value is automatically generated when you invoke the AuthenticationFlowContext.form() method. You can also obtain this value by calling the AuthenticationFlowContext.getActionURL() method in Java code. You'll also see `${properties.someValue}`. These correspond to properties defined in your theme.properties file of our theme. `${msg(""someValue"")}` corresponds to the internationalized message bundles (.properties files) included with the login theme messages/ directory. If you're just using english, you can just add the value of the `loginSecretQuestion`. This should be the question you want to ask the user. When you call AuthenticationFlowContext.form() this gives you a LoginFormsProvider instance. If you called, `LoginFormsProvider.setAttribute(""foo"", ""bar"")`, the value of ""foo"" would be available for reference in your form as `${foo}`. The value of an attribute can be any Java bean as well. If you look at the top of the file, you'll see that we are importing a template: [source,java] ---- <#import ""select.ftl"" as layout> ---- Importing this template, instead of the standard `template.ftl` allows {project_name} to display a dropdown box that allows the user to select a different credential or execution. [[_adding_authenticator]] ==== Adding an authenticator to a flow Adding an Authenticator to a flow must be done in the Admin Console. If you go to the Authentication menu item and go to the Flow tab, you will be able to view the currently defined flows. You cannot modify built in flows, so, to add the Authenticator we've created you have to copy an existing flow or create your own. Our hope is that the user interface is sufficiently clear so that you can determine how to create a flow and add the Authenticator. For more details, see the `Authentication Flows` chapter in link:{adminguide_link}[{adminguide_name}] . After you've created your flow, you have to bind it to the login action you want to bind it to. If you go to the Authentication menu and go to the Bindings tab you will see options to bind a flow to the browser, registration, or direct grant flow. === Required action walkthrough In this section we will discuss how to define a required action. In the Authenticator section you may have wondered, ""How will we get the user's answer to the secret question entered into the system?"". As we showed in the example, if the answer is not set up, a required action will be triggered. This section discusses how to implement the required action for the Secret Question Authenticator. ==== Packaging classes and deployment You will package your classes within a single jar. This jar does not have to be separate from other provider classes but it must contain a file named `org.keycloak.authentication.RequiredActionFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified classname of each RequiredActionFactory implementation you have in the jar. For example: [source,java] ---- org.keycloak.examples.authenticator.SecretQuestionRequiredActionFactory ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the `standalone/deployments` directory. ==== Implement the RequiredActionProvider Required actions must first implement the RequiredActionProvider interface. The RequiredActionProvider.requiredActionChallenge() is the initial call by the flow manager into the required action. This method is responsible for rendering the HTML form that will drive the required action. [source,java] ---- @Override public void requiredActionChallenge(RequiredActionContext context) { Response challenge = context.form().createForm(""secret_question_config.ftl""); context.challenge(challenge); } ---- You see that RequiredActionContext has similar methods to AuthenticationFlowContext. The form() method allows you to render the page from a Freemarker template. The action URL is preset by the call to this form() method. You just need to reference it within your HTML form. I'll show you this later. The challenge() method notifies the flow manager that a required action must be executed. The next method is responsible for processing input from the HTML form of the required action. The action URL of the form will be routed to the RequiredActionProvider.processAction() method [source,java] ---- @Override public void processAction(RequiredActionContext context) { String answer = (context.getHttpRequest().getDecodedFormParameters().getFirst(""answer"")); UserCredentialValueModel model = new UserCredentialValueModel(); model.setValue(answer); model.setType(SecretQuestionAuthenticator.CREDENTIAL_TYPE); context.getUser().updateCredentialDirectly(model); context.success(); } ---- The answer is pulled out of the form post. A UserCredentialValueModel is created and the type and value of the credential are set. Then UserModel.updateCredentialDirectly() is invoked. Finally, RequiredActionContext.success() notifies the container that the required action was successful. ==== Implement the RequiredActionFactory This class is really simple. It is just responsible for creating the required action provider instance. [source,java] ---- public class SecretQuestionRequiredActionFactory implements RequiredActionFactory { private static final SecretQuestionRequiredAction SINGLETON = new SecretQuestionRequiredAction(); @Override public RequiredActionProvider create(KeycloakSession session) { return SINGLETON; } @Override public String getId() { return SecretQuestionRequiredAction.PROVIDER_ID; } @Override public String getDisplayText() { return ""Secret Question""; } ---- The getDisplayText() method is just for the Admin Console when it wants to display a friendly name for the required action. ==== Enable required action The final thing you have to do is go into the Admin Console. Click on the Authentication left menu. Click on the Required Actions tab. Click on the Register button and choose your new Required Action. Your new required action should now be displayed and enabled in the required actions list. === Modifying or extending the registration form It is entirely possible for you to implement your own flow with a set of Authenticators to totally change how registration is done in {project_name}. But what you'll usually want to do is just add a little bit of validation to the out of the box registration page. An additional SPI was created to be able to do this. It basically allows you to add validation of form elements on the page as well as to initialize UserModel attributes and data after the user has been registered. We'll look at both the implementation of the user profile registration processing as well as the registration Google Recaptcha plugin. ==== Implementation FormAction interface The core interface you have to implement is the FormAction interface. A FormAction is responsible for rendering and processing a portion of the page. Rendering is done in the buildPage() method, validation is done in the validate() method, post validation operations are done in success(). Let's first take a look at buildPage() method of the Recaptcha plugin. [source,java] ---- @Override public void buildPage(FormContext context, LoginFormsProvider form) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); if (captchaConfig == null || captchaConfig.getConfig() == null || captchaConfig.getConfig().get(SITE_KEY) == null || captchaConfig.getConfig().get(SITE_SECRET) == null ) { form.addError(new FormMessage(null, Messages.RECAPTCHA_NOT_CONFIGURED)); return; } String siteKey = captchaConfig.getConfig().get(SITE_KEY); form.setAttribute(""recaptchaRequired"", true); form.setAttribute(""recaptchaSiteKey"", siteKey); form.addScript(""https://www.google.com/recaptcha/api.js""); } ---- The Recaptcha buildPage() method is a callback by the form flow to help render the page. It receives a form parameter which is a LoginFormsProvider. You can add additional attributes to the form provider so that they can be displayed in the HTML page generated by the registration Freemarker template. The code above is from the registration recaptcha plugin. Recaptcha requires some specific settings that must be obtained from configuration. FormActions are configured in the exact same as Authenticators are. In this example, we pull the Google Recaptcha site key from configuration and add it as an attribute to the form provider. Our registration template file can read this attribute now. Recaptcha also has the requirement of loading a JavaScript script. You can do this by calling LoginFormsProvider.addScript() passing in the URL. For user profile processing, there is no additional information that it needs to add to the form, so its buildPage() method is empty. The next meaty part of this interface is the validate() method. This is called immediately upon receiving a form post. Let's look at the Recaptcha's plugin first. [source,java] ---- @Override public void validate(ValidationContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); List errors = new ArrayList<>(); boolean success = false; String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE); if (!Validation.isBlank(captcha)) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); String secret = captchaConfig.getConfig().get(SITE_SECRET); success = validateRecaptcha(context, success, captcha, secret); } if (success) { context.success(); } else { errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED)); formData.remove(G_RECAPTCHA_RESPONSE); context.validationError(formData, errors); return; } } ---- Here we obtain the form data that the Recaptcha widget adds to the form. We obtain the Recaptcha secret key from configuration. We then validate the recaptcha. If successful, ValidationContext.success() is called. If not, we invoke ValidationContext.validationError() passing in the formData (so the user doesn't have to re-enter data), we also specify an error message we want displayed. The error message must point to a message bundle property in the internationalized message bundles. For other registration extensions validate() might be validating the format of a form element, for example an alternative email attribute. Let's also look at the user profile plugin that is used to validate email address and other user information when registering. [source,java] ---- @Override public void validate(ValidationContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); List errors = new ArrayList<>(); String eventError = Errors.INVALID_REGISTRATION; if (Validation.isBlank(formData.getFirst((RegistrationPage.FIELD_FIRST_NAME)))) { errors.add(new FormMessage(RegistrationPage.FIELD_FIRST_NAME, Messages.MISSING_FIRST_NAME)); } if (Validation.isBlank(formData.getFirst((RegistrationPage.FIELD_LAST_NAME)))) { errors.add(new FormMessage(RegistrationPage.FIELD_LAST_NAME, Messages.MISSING_LAST_NAME)); } String email = formData.getFirst(Validation.FIELD_EMAIL); if (Validation.isBlank(email)) { errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.MISSING_EMAIL)); } else if (!Validation.isEmailValid(email)) { formData.remove(Validation.FIELD_EMAIL); errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.INVALID_EMAIL)); } if (context.getSession().users().getUserByEmail(email, context.getRealm()) != null) { formData.remove(Validation.FIELD_EMAIL); errors.add(new FormMessage(RegistrationPage.FIELD_EMAIL, Messages.EMAIL_EXISTS)); } if (errors.size() > 0) { context.validationError(formData, errors); return; } else { context.success(); } } ---- As you can see, this validate() method of user profile processing makes sure that the email, first, and last name are filled in the form. It also makes sure that email is in the right format. If any of these validations fail, an error message is queued up for rendering. Any fields in error are removed from the form data. Error messages are represented by the FormMessage class. The first parameter of the constructor of this class takes the HTML element id. The input in error will be highlighted when the form is re-rendered. The second parameter is a message reference id. This id must correspond to a property in one of the localized message bundle files. in the theme. After all validations have been processed then, the form flow then invokes the FormAction.success() method. For recaptcha this is a no-op, so we won't go over it. For user profile processing, this method fills in values in the registered user. [source,java] ---- @Override public void success(FormContext context) { UserModel user = context.getUser(); MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); user.setFirstName(formData.getFirst(RegistrationPage.FIELD_FIRST_NAME)); user.setLastName(formData.getFirst(RegistrationPage.FIELD_LAST_NAME)); user.setEmail(formData.getFirst(RegistrationPage.FIELD_EMAIL)); } ---- Pretty simple implementation. The UserModel of the newly registered user is obtained from the FormContext. The appropriate methods are called to initialize UserModel data. Finally, you are also required to define a FormActionFactory class. This class is implemented similarly to AuthenticatorFactory, so we won't go over it. ==== Packaging the action You will package your classes within a single jar. This jar must contain a file named `org.keycloak.authentication.FormActionFactory` and must be contained in the `META-INF/services/` directory of your jar. This file must list the fully qualified class name of each FormActionFactory implementation you have in the jar. For example: [source] ---- org.keycloak.authentication.forms.RegistrationProfile org.keycloak.authentication.forms.RegistrationRecaptcha ---- This services/ file is used by {project_name} to scan the providers it has to load into the system. To deploy this jar, just copy it to the `standalone/deployments` directory. ==== Adding FormAction to the registration flow Adding a FormAction to a registration page flow must be done in the Admin Console. If you go to the Authentication menu item and go to the Flow tab, you will be able to view the currently defined flows. You cannot modify built in flows, so, to add the Authenticator we've created you have to copy an existing flow or create your own. I'm hoping the UI is intuitive enough so that you can figure out for yourself how to create a flow and add the FormAction. Basically you'll have to copy the registration flow. Then click Actions menu to the right of the Registration Form, and pick ""Add execution"" to add a new execution. You'll pick the FormAction from the selection list. Make sure your FormAction comes after ""Registration User Creation"" by using the down buttons to move it if your FormAction isn't already listed after ""Registration User Creation"". You want your FormAction to come after user creation because the success() method of Registration User Creation is responsible for creating the new UserModel. After you've created your flow, you have to bind it to registration. If you go to the Authentication menu and go to the Bindings tab you will see options to bind a flow to the browser, registration, or direct grant flow. === Modifying forgot password/credential flow {project_name} also has a specific authentication flow for forgot password, or rather credential reset initiated by a user. If you go to the Admin Console flows page, there is a ""reset credentials"" flow. By default, {project_name} asks for the email or username of the user and sends an email to them. If the user clicks on the link, then they are able to reset both their password and OTP (if an OTP has been set up). You can disable automatic OTP reset by disabling the ""Reset OTP"" authenticator in the flow. You can add additional functionality to this flow as well. For example, many deployments would like for the user to answer one or more secret questions in additional to sending an email with a link. You could expand on the secret question example that comes with the distro and incorporate it into the reset credential flow. One thing to note if you are extending the reset credentials flow. The first ""authenticator"" is just a page to obtain the username or email. If the username or email exists, then the AuthenticationFlowContext.getUser() will return the located user. Otherwise this will be null. This form *WILL NOT* re-ask the user to enter in an email or username if the previous email or username did not exist. You need to prevent attackers from being able to guess valid users. So, if AuthenticationFlowContext.getUser() returns null, you should proceed with the flow to make it look like a valid user was selected. I suggest that if you want to add secret questions to this flow, you should ask these questions after the email is sent. In other words, add your custom authenticator after the ""Send Reset Email"" authenticator. === Modifying first broker login flow First Broker Login flow is used during first login with some identity provider. Term `First Login` means that there is not yet existing {project_name} account linked with the particular authenticated identity provider account. [role=""_additional-resource""] .Additional resources * See the `Identity Brokering` chapter in link:{adminguide_link}[{adminguide_name}] . [[_client_authentication]] === Authentication of clients {project_name} actually supports pluggable authentication for https://openid.net/specs/openid-connect-core-1_0.html[OpenID Connect] client applications. Authentication of client (application) is used under the hood by the {project_name} adapter during sending any backchannel requests to the {project_name} server (like the request for exchange code to access token after successful authentication or request to refresh token). But the client authentication can be also used directly by you during `Direct Access grants` (represented by OAuth2 `Resource Owner Password Credentials Flow`) or during `Service account` authentication (represented by OAuth2 `Client Credentials Flow`). [role=""_additional-resource""] .Additional resources * For more details about {project_name} adapter and OAuth2 flows see link:{adapterguide_link}[{adapterguide_name}]. ==== Default implementations Actually {project_name} has 2 default implementations of client authentication: Traditional authentication with client_id and client_secret:: This is default mechanism mentioned in the https://openid.net/specs/openid-connect-core-1_0.html[OpenID Connect] or https://datatracker.ietf.org/doc/html/rfc6749[OAuth2] specification and {project_name} supports it since it's early days. The public client needs to include `client_id` parameter with its ID in the POST request (so it's defacto not authenticated) and the confidential client needs to include `Authorization: Basic` header with the clientId and clientSecret used as username and password. Authentication with signed JWT:: This is based on the https://datatracker.ietf.org/doc/html/rfc7523[JWT Bearer Token Profiles for OAuth 2.0] specification. The client/adapter generates the https://datatracker.ietf.org/doc/html/rfc7519[JWT] and signs it with his private key. The {project_name} then verifies the signed JWT with the client's public key and authenticates client based on it. See the demo example and especially the `examples/preconfigured-demo/product-app` for the example application showing the application using client authentication with signed JWT. ==== Implement your own client authenticator For plug your own client authenticator, you need to implement few interfaces on both client (adapter) and server side. Client side:: Here you need to implement `org.keycloak.adapters.authentication.ClientCredentialsProvider` and put the implementation either to: * your WAR file into WEB-INF/classes . But in this case, the implementation can be used just for this single WAR application * Some JAR file, which will be added into WEB-INF/lib of your WAR * Some JAR file, which will be used as jboss module and configured in jboss-deployment-structure.xml of your WAR. In all cases, you also need to create the file `META-INF/services/org.keycloak.adapters.authentication.ClientCredentialsProvider` either in the WAR or in your JAR. Server side:: Here you need to implement `org.keycloak.authentication.ClientAuthenticatorFactory` and `org.keycloak.authentication.ClientAuthenticator` . You also need to add the file `META-INF/services/org.keycloak.authentication.ClientAuthenticatorFactory` with the name of the implementation classes. See <<_auth_spi_walkthrough,authenticators>> for more details. ",12520,False,2030.3070574799547,median "/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 ""shuffle/splitter.h"" #include #include #include #include #include #include #include #include #include #include ""shuffle/utils.h"" #include ""utils/macros.h"" #if defined(COLUMNAR_PLUGIN_USE_AVX512) #include #else #include #endif namespace sparkcolumnarplugin { namespace shuffle { using arrow::internal::checked_cast; SplitOptions SplitOptions::Defaults() { return SplitOptions(); } #if defined(COLUMNAR_PLUGIN_USE_AVX512) inline __m256i CountPartitionIdOccurrence(const std::vector& partition_id, int32_t row) { __m128i partid_cnt_low; __m128i partid_cnt_high; int32_t tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7; partid_cnt_low = _mm_xor_si128(partid_cnt_low, partid_cnt_low); tmp1 = (partition_id[row + 1] ^ partition_id[row]) == 0; partid_cnt_low = _mm_insert_epi32(partid_cnt_low, tmp1, 1); tmp2 = (partition_id[row + 2] ^ partition_id[row]) == 0; tmp2 += (partition_id[row + 2] ^ partition_id[row + 1]) == 0; partid_cnt_low = _mm_insert_epi32(partid_cnt_low, tmp2, 2); tmp3 = (partition_id[row + 3] ^ partition_id[row]) == 0; tmp3 += (partition_id[row + 3] ^ partition_id[row + 1]) == 0; tmp3 += (partition_id[row + 3] ^ partition_id[row + 2]) == 0; partid_cnt_low = _mm_insert_epi32(partid_cnt_low, tmp3, 3); tmp4 = (partition_id[row + 4] ^ partition_id[row]) == 0; tmp4 += (partition_id[row + 4] ^ partition_id[row + 1]) == 0; tmp4 += (partition_id[row + 4] ^ partition_id[row + 2]) == 0; tmp4 += (partition_id[row + 4] ^ partition_id[row + 3]) == 0; partid_cnt_high = _mm_insert_epi32(partid_cnt_high, tmp4, 0); tmp5 = (partition_id[row + 5] ^ partition_id[row]) == 0; tmp5 += (partition_id[row + 5] ^ partition_id[row + 1]) == 0; tmp5 += (partition_id[row + 5] ^ partition_id[row + 2]) == 0; tmp5 += (partition_id[row + 5] ^ partition_id[row + 3]) == 0; tmp5 += (partition_id[row + 5] ^ partition_id[row + 4]) == 0; partid_cnt_high = _mm_insert_epi32(partid_cnt_high, tmp5, 1); tmp6 = (partition_id[row + 6] ^ partition_id[row]) == 0; tmp6 += (partition_id[row + 6] ^ partition_id[row + 1]) == 0; tmp6 += (partition_id[row + 6] ^ partition_id[row + 2]) == 0; tmp6 += (partition_id[row + 6] ^ partition_id[row + 3]) == 0; tmp6 += (partition_id[row + 6] ^ partition_id[row + 4]) == 0; tmp6 += (partition_id[row + 6] ^ partition_id[row + 5]) == 0; partid_cnt_high = _mm_insert_epi32(partid_cnt_high, tmp6, 2); tmp7 = (partition_id[row + 7] ^ partition_id[row]) == 0; tmp7 += (partition_id[row + 7] ^ partition_id[row + 1]) == 0; tmp7 += (partition_id[row + 7] ^ partition_id[row + 2]) == 0; tmp7 += (partition_id[row + 7] ^ partition_id[row + 3]) == 0; tmp7 += (partition_id[row + 7] ^ partition_id[row + 4]) == 0; tmp7 += (partition_id[row + 7] ^ partition_id[row + 5]) == 0; tmp7 += (partition_id[row + 7] ^ partition_id[row + 6]) == 0; partid_cnt_high = _mm_insert_epi32(partid_cnt_high, tmp7, 3); __m256i partid_cnt_8x = _mm256_castsi128_si256(partid_cnt_low); partid_cnt_8x = _mm256_inserti128_si256(partid_cnt_8x, partid_cnt_high, 1); return partid_cnt_8x; } inline void PrefetchDstAddr(__m512i dst_addr_8x, int32_t scale) { _mm_prefetch( (void*)(_mm_extract_epi64(_mm512_extracti64x2_epi64(dst_addr_8x, 0), 0) + scale), _MM_HINT_T0); _mm_prefetch( (void*)(_mm_extract_epi64(_mm512_extracti64x2_epi64(dst_addr_8x, 0), 1) + scale), _MM_HINT_T0); _mm_prefetch( (void*)(_mm_extract_epi64(_mm512_extracti64x2_epi64(dst_addr_8x, 1), 0) + scale), _MM_HINT_T0); _mm_prefetch( (void*)(_mm_extract_epi64(_mm512_extracti64x2_epi64(dst_addr_8x, 1), 1) + scale), _MM_HINT_T0); _mm_prefetch( (void*)(_mm_extract_epi64(_mm512_extracti64x2_epi64(dst_addr_8x, 2), 0) + scale), _MM_HINT_T0); _mm_prefetch( (void*)(_mm_extract_epi64(_mm512_extracti64x2_epi64(dst_addr_8x, 2), 1) + scale), _MM_HINT_T0); _mm_prefetch( (void*)(_mm_extract_epi64(_mm512_extracti64x2_epi64(dst_addr_8x, 3), 0) + scale), _MM_HINT_T0); _mm_prefetch( (void*)(_mm_extract_epi64(_mm512_extracti64x2_epi64(dst_addr_8x, 3), 1) + scale), _MM_HINT_T0); } #endif class Splitter::PartitionWriter { public: explicit PartitionWriter(Splitter* splitter, int32_t partition_id) : splitter_(splitter), partition_id_(partition_id) {} arrow::Status Spill() { RETURN_NOT_OK(EnsureOpened()); RETURN_NOT_OK(WriteRecordBatchPayload(spilled_file_os_.get(), partition_id_)); ClearCache(); return arrow::Status::OK(); } arrow::Status WriteCachedRecordBatchAndClose() { const auto& data_file_os = splitter_->data_file_os_; ARROW_ASSIGN_OR_RAISE(auto before_write, data_file_os->Tell()); if (splitter_->options_.write_schema) { RETURN_NOT_OK(WriteSchemaPayload(data_file_os.get())); } if (spilled_file_opened_) { RETURN_NOT_OK(spilled_file_os_->Close()); RETURN_NOT_OK(MergeSpilled()); } else { if (splitter_->partition_cached_recordbatch_size_[partition_id_] == 0) { return arrow::Status::Invalid(""Partition writer got empty partition""); } } RETURN_NOT_OK(WriteRecordBatchPayload(data_file_os.get(), partition_id_)); RETURN_NOT_OK(WriteEOS(data_file_os.get())); ClearCache(); ARROW_ASSIGN_OR_RAISE(auto after_write, data_file_os->Tell()); partition_length = after_write - before_write; return arrow::Status::OK(); } // metrics int64_t bytes_spilled = 0; int64_t partition_length = 0; int64_t compress_time = 0; private: arrow::Status EnsureOpened() { if (!spilled_file_opened_) { ARROW_ASSIGN_OR_RAISE(spilled_file_, CreateTempShuffleFile(splitter_->NextSpilledFileDir())); ARROW_ASSIGN_OR_RAISE(spilled_file_os_, arrow::io::FileOutputStream::Open(spilled_file_, true)); spilled_file_opened_ = true; } return arrow::Status::OK(); } arrow::Status MergeSpilled() { ARROW_ASSIGN_OR_RAISE( auto spilled_file_is_, arrow::io::MemoryMappedFile::Open(spilled_file_, arrow::io::FileMode::READ)); // copy spilled data blocks ARROW_ASSIGN_OR_RAISE(auto nbytes, spilled_file_is_->GetSize()); ARROW_ASSIGN_OR_RAISE(auto buffer, spilled_file_is_->Read(nbytes)); RETURN_NOT_OK(splitter_->data_file_os_->Write(buffer)); // close spilled file streams and delete the file RETURN_NOT_OK(spilled_file_is_->Close()); auto fs = std::make_shared(); RETURN_NOT_OK(fs->DeleteFile(spilled_file_)); bytes_spilled += nbytes; return arrow::Status::OK(); } arrow::Status WriteSchemaPayload(arrow::io::OutputStream* os) { ARROW_ASSIGN_OR_RAISE(auto payload, splitter_->GetSchemaPayload()); int32_t metadata_length = 0; // unused RETURN_NOT_OK(arrow::ipc::WriteIpcPayload( *payload, splitter_->options_.ipc_write_options, os, &metadata_length)); return arrow::Status::OK(); } arrow::Status WriteRecordBatchPayload(arrow::io::OutputStream* os, int32_t partition_id) { int32_t metadata_length = 0; // unused for (auto& payload : splitter_->partition_cached_recordbatch_[partition_id_]) { RETURN_NOT_OK(arrow::ipc::WriteIpcPayload( *payload, splitter_->options_.ipc_write_options, os, &metadata_length)); payload = nullptr; } return arrow::Status::OK(); } arrow::Status WriteEOS(arrow::io::OutputStream* os) { // write EOS constexpr int32_t kZeroLength = 0; RETURN_NOT_OK(os->Write(&kIpcContinuationToken, sizeof(int32_t))); RETURN_NOT_OK(os->Write(&kZeroLength, sizeof(int32_t))); return arrow::Status::OK(); } void ClearCache() { splitter_->partition_cached_recordbatch_[partition_id_].clear(); splitter_->partition_cached_recordbatch_size_[partition_id_] = 0; } Splitter* splitter_; int32_t partition_id_; std::string spilled_file_; std::shared_ptr spilled_file_os_; bool spilled_file_opened_ = false; }; // ---------------------------------------------------------------------- // Splitter arrow::Result> Splitter::Make( const std::string& short_name, std::shared_ptr schema, int num_partitions, const gandiva::ExpressionVector& expr_vector, SplitOptions options) { if (short_name == ""hash"") { return HashSplitter::Create(num_partitions, std::move(schema), expr_vector, std::move(options)); } else if (short_name == ""rr"") { return RoundRobinSplitter::Create(num_partitions, std::move(schema), std::move(options)); } else if (short_name == ""range"") { return FallbackRangeSplitter::Create(num_partitions, std::move(schema), std::move(options)); } else if (short_name == ""single"") { return RoundRobinSplitter::Create(1, std::move(schema), std::move(options)); } return arrow::Status::NotImplemented(""Partitioning "" + short_name + "" not supported yet.""); } arrow::Result> Splitter::Make( const std::string& short_name, std::shared_ptr schema, int num_partitions, SplitOptions options) { return Make(short_name, std::move(schema), num_partitions, {}, std::move(options)); } arrow::Status Splitter::Init() { const auto& fields = schema_->fields(); ARROW_ASSIGN_OR_RAISE(column_type_id_, ToSplitterTypeId(schema_->fields())); partition_writer_.resize(num_partitions_); partition_id_cnt_.resize(num_partitions_); partition_buffer_size_.resize(num_partitions_); partition_buffer_idx_base_.resize(num_partitions_); partition_buffer_idx_offset_.resize(num_partitions_); partition_cached_recordbatch_.resize(num_partitions_); partition_cached_recordbatch_size_.resize(num_partitions_); partition_lengths_.resize(num_partitions_); raw_partition_lengths_.resize(num_partitions_); for (int i = 0; i < column_type_id_.size(); ++i) { switch (column_type_id_[i]->id()) { case arrow::BinaryType::type_id: case arrow::StringType::type_id: binary_array_idx_.push_back(i); break; case arrow::LargeBinaryType::type_id: case arrow::LargeStringType::type_id: large_binary_array_idx_.push_back(i); break; case arrow::ListType::type_id: list_array_idx_.push_back(i); break; case arrow::LargeListType::type_id: large_list_array_idx_.push_back(i); break; case arrow::NullType::type_id: break; default: fixed_width_array_idx_.push_back(i); break; } } auto num_fixed_width = fixed_width_array_idx_.size(); partition_fixed_width_validity_addrs_.resize(num_fixed_width); partition_fixed_width_value_addrs_.resize(num_fixed_width); partition_fixed_width_buffers_.resize(num_fixed_width); binary_array_empirical_size_.resize(binary_array_idx_.size()); large_binary_array_empirical_size_.resize(large_binary_array_idx_.size()); input_fixed_width_has_null_.resize(num_fixed_width, false); for (auto i = 0; i < num_fixed_width; ++i) { partition_fixed_width_validity_addrs_[i].resize(num_partitions_); partition_fixed_width_value_addrs_[i].resize(num_partitions_); partition_fixed_width_buffers_[i].resize(num_partitions_); } partition_binary_builders_.resize(binary_array_idx_.size()); for (auto i = 0; i < binary_array_idx_.size(); ++i) { partition_binary_builders_[i].resize(num_partitions_); } partition_large_binary_builders_.resize(large_binary_array_idx_.size()); for (auto i = 0; i < large_binary_array_idx_.size(); ++i) { partition_large_binary_builders_[i].resize(num_partitions_); } partition_list_builders_.resize(list_array_idx_.size()); for (auto i = 0; i < list_array_idx_.size(); ++i) { partition_list_builders_[i].resize(num_partitions_); } partition_large_list_builders_.resize(large_list_array_idx_.size()); for (auto i = 0; i < large_list_array_idx_.size(); ++i) { partition_large_list_builders_[i].resize(num_partitions_); } ARROW_ASSIGN_OR_RAISE(configured_dirs_, GetConfiguredLocalDirs()); sub_dir_selection_.assign(configured_dirs_.size(), 0); // Both data_file and shuffle_index_file should be set through jni. // For test purpose, Create a temporary subdirectory in the system temporary // dir with prefix ""columnar-shuffle"" if (options_.data_file.length() == 0) { ARROW_ASSIGN_OR_RAISE(options_.data_file, CreateTempShuffleFile(configured_dirs_[0])); } auto& ipc_write_options = options_.ipc_write_options; ipc_write_options.memory_pool = options_.memory_pool; ipc_write_options.use_threads = false; if (options_.compression_type == arrow::Compression::FASTPFOR) { ARROW_ASSIGN_OR_RAISE(ipc_write_options.codec, arrow::util::Codec::CreateInt32(arrow::Compression::FASTPFOR)); } else if (options_.compression_type == arrow::Compression::LZ4_FRAME) { ARROW_ASSIGN_OR_RAISE(ipc_write_options.codec, arrow::util::Codec::Create(arrow::Compression::LZ4_FRAME)); } else { ARROW_ASSIGN_OR_RAISE(ipc_write_options.codec, arrow::util::Codec::CreateInt32( arrow::Compression::UNCOMPRESSED)); } // initialize tiny batch write options tiny_bach_write_options_ = ipc_write_options; ARROW_ASSIGN_OR_RAISE( tiny_bach_write_options_.codec, arrow::util::Codec::CreateInt32(arrow::Compression::UNCOMPRESSED)); return arrow::Status::OK(); } int64_t batch_nbytes(const arrow::RecordBatch& batch) { int64_t accumulated = 0L; for (const auto& array : batch.columns()) { if (array == nullptr || array->data() == nullptr) { continue; } for (const auto& buf : array->data()->buffers) { if (buf == nullptr) { continue; } accumulated += buf->capacity(); } } return accumulated; } int64_t batch_nbytes(std::shared_ptr batch) { if (batch == nullptr) { return 0; } return batch_nbytes(*batch); } int64_t Splitter::CompressedSize(const arrow::RecordBatch& rb) { auto payload = std::make_shared(); arrow::Status result; result = arrow::ipc::GetRecordBatchPayload(rb, options_.ipc_write_options, payload.get()); if (result.ok()) { return payload->body_length; } else { result.UnknownError(""Failed to get the compressed size.""); return -1; } } arrow::Status Splitter::SetCompressType(arrow::Compression::type compressed_type) { if (compressed_type == arrow::Compression::FASTPFOR) { ARROW_ASSIGN_OR_RAISE(options_.ipc_write_options.codec, arrow::util::Codec::CreateInt32(arrow::Compression::FASTPFOR)); } else if (compressed_type == arrow::Compression::LZ4_FRAME) { ARROW_ASSIGN_OR_RAISE(options_.ipc_write_options.codec, arrow::util::Codec::Create(arrow::Compression::LZ4_FRAME)); } else { ARROW_ASSIGN_OR_RAISE( options_.ipc_write_options.codec, arrow::util::Codec::CreateInt32(arrow::Compression::UNCOMPRESSED)); } return arrow::Status::OK(); } arrow::Status Splitter::Split(const arrow::RecordBatch& rb) { EVAL_START(""split"", options_.thread_id) RETURN_NOT_OK(ComputeAndCountPartitionId(rb)); RETURN_NOT_OK(DoSplit(rb)); EVAL_END(""split"", options_.thread_id, options_.task_attempt_id) return arrow::Status::OK(); } arrow::Status Splitter::Stop() { EVAL_START(""write"", options_.thread_id) // open data file output stream ARROW_ASSIGN_OR_RAISE(data_file_os_, arrow::io::FileOutputStream::Open(options_.data_file, true)); // stop PartitionWriter and collect metrics for (auto pid = 0; pid < num_partitions_; ++pid) { RETURN_NOT_OK(CacheRecordBatch(pid, true)); if (partition_cached_recordbatch_size_[pid] > 0) { if (partition_writer_[pid] == nullptr) { partition_writer_[pid] = std::make_shared(this, pid); } } if (partition_writer_[pid] != nullptr) { const auto& writer = partition_writer_[pid]; TIME_NANO_OR_RAISE(total_write_time_, writer->WriteCachedRecordBatchAndClose()); partition_lengths_[pid] = writer->partition_length; total_bytes_written_ += writer->partition_length; total_bytes_spilled_ += writer->bytes_spilled; total_compress_time_ += writer->compress_time; } else { partition_lengths_[pid] = 0; } } // close data file output Stream RETURN_NOT_OK(data_file_os_->Close()); EVAL_END(""write"", options_.thread_id, options_.task_attempt_id) return arrow::Status::OK(); } arrow::Status Splitter::CacheRecordBatch(int32_t partition_id, bool reset_buffers) { if (partition_buffer_idx_base_[partition_id] > 0) { auto fixed_width_idx = 0; auto binary_idx = 0; auto large_binary_idx = 0; auto list_idx = 0; auto large_list_idx = 0; auto num_fields = schema_->num_fields(); auto num_rows = partition_buffer_idx_base_[partition_id]; auto buffer_sizes = 0; std::vector> arrays(num_fields); for (int i = 0; i < num_fields; ++i) { switch (column_type_id_[i]->id()) { case arrow::BinaryType::type_id: case arrow::StringType::type_id: { auto& builder = partition_binary_builders_[binary_idx][partition_id]; if (reset_buffers) { RETURN_NOT_OK(builder->Finish(&arrays[i])); builder->Reset(); } else { auto data_size = builder->value_data_length(); RETURN_NOT_OK(builder->Finish(&arrays[i])); builder->Reset(); RETURN_NOT_OK(builder->Reserve(num_rows)); RETURN_NOT_OK(builder->ReserveData(data_size)); } binary_idx++; break; } case arrow::LargeBinaryType::type_id: case arrow::LargeStringType::type_id: { auto& builder = partition_large_binary_builders_[large_binary_idx][partition_id]; if (reset_buffers) { RETURN_NOT_OK(builder->Finish(&arrays[i])); builder->Reset(); } else { auto data_size = builder->value_data_length(); RETURN_NOT_OK(builder->Finish(&arrays[i])); builder->Reset(); RETURN_NOT_OK(builder->Reserve(num_rows)); RETURN_NOT_OK(builder->ReserveData(data_size)); } large_binary_idx++; break; } case arrow::ListType::type_id: { auto& builder = partition_list_builders_[list_idx][partition_id]; if (reset_buffers) { RETURN_NOT_OK(builder->Finish(&arrays[i])); builder->Reset(); } else { RETURN_NOT_OK(builder->Finish(&arrays[i])); builder->Reset(); RETURN_NOT_OK(builder->Reserve(num_rows)); } list_idx++; break; } case arrow::LargeListType::type_id: { auto& builder = partition_large_list_builders_[large_list_idx][partition_id]; if (reset_buffers) { RETURN_NOT_OK(builder->Finish(&arrays[i])); builder->Reset(); } else { RETURN_NOT_OK(builder->Finish(&arrays[i])); builder->Reset(); RETURN_NOT_OK(builder->Reserve(num_rows)); } large_list_idx++; break; } case arrow::NullType::type_id: { arrays[i] = arrow::MakeArray(arrow::ArrayData::Make( arrow::null(), num_rows, {nullptr, nullptr}, num_rows)); break; } default: { auto& buffers = partition_fixed_width_buffers_[fixed_width_idx][partition_id]; if (reset_buffers) { arrays[i] = arrow::MakeArray( arrow::ArrayData::Make(schema_->field(i)->type(), num_rows, {std::move(buffers[0]), std::move(buffers[1])})); buffers = {nullptr, nullptr}; partition_fixed_width_validity_addrs_[fixed_width_idx][partition_id] = nullptr; partition_fixed_width_value_addrs_[fixed_width_idx][partition_id] = nullptr; } else { arrays[i] = arrow::MakeArray(arrow::ArrayData::Make( schema_->field(i)->type(), num_rows, {buffers[0], buffers[1]})); } fixed_width_idx++; break; } } } auto batch = arrow::RecordBatch::Make(schema_, num_rows, std::move(arrays)); int64_t raw_size = batch_nbytes(batch); raw_partition_lengths_[partition_id] += raw_size; auto payload = std::make_shared(); if (num_rows <= options_.batch_compress_threshold) { TIME_NANO_OR_RAISE(total_compress_time_, arrow::ipc::GetRecordBatchPayload( *batch, tiny_bach_write_options_, payload.get())); } else { TIME_NANO_OR_RAISE(total_compress_time_, arrow::ipc::GetRecordBatchPayload( *batch, options_.ipc_write_options, payload.get())); } partition_cached_recordbatch_size_[partition_id] += payload->body_length; partition_cached_recordbatch_[partition_id].push_back(std::move(payload)); partition_buffer_idx_base_[partition_id] = 0; } return arrow::Status::OK(); } arrow::Status Splitter::AllocatePartitionBuffers(int32_t partition_id, int32_t new_size) { // try to allocate new auto num_fields = schema_->num_fields(); auto fixed_width_idx = 0; auto binary_idx = 0; auto large_binary_idx = 0; auto list_idx = 0; auto large_list_idx = 0; std::vector> new_binary_builders; std::vector> new_large_binary_builders; std::vector> new_list_builders; std::vector> new_large_list_builders; std::vector> new_value_buffers; std::vector> new_validity_buffers; for (auto i = 0; i < num_fields; ++i) { switch (column_type_id_[i]->id()) { case arrow::BinaryType::type_id: case arrow::StringType::type_id: { auto builder = std::make_shared(options_.memory_pool); assert(builder != nullptr); RETURN_NOT_OK(builder->Reserve(new_size)); RETURN_NOT_OK( builder->ReserveData(binary_array_empirical_size_[binary_idx] * new_size)); new_binary_builders.push_back(std::move(builder)); binary_idx++; break; } case arrow::LargeBinaryType::type_id: case arrow::LargeStringType::type_id: { auto builder = std::make_shared(options_.memory_pool); assert(builder != nullptr); RETURN_NOT_OK(builder->Reserve(new_size)); RETURN_NOT_OK(builder->ReserveData( large_binary_array_empirical_size_[large_binary_idx] * new_size)); new_large_binary_builders.push_back(std::move(builder)); large_binary_idx++; break; } case arrow::ListType::type_id: { auto child_type = std::dynamic_pointer_cast(column_type_id_[i])->value_type(); std::unique_ptr child_builder; RETURN_NOT_OK(MakeBuilder(options_.memory_pool, child_type, &child_builder)); auto builder = std::make_shared(options_.memory_pool, std::move(child_builder)); assert(builder != nullptr); RETURN_NOT_OK(builder->Reserve(new_size)); new_list_builders.push_back(std::move(builder)); list_idx++; break; } case arrow::LargeListType::type_id: { auto child_type = std::dynamic_pointer_cast(column_type_id_[i]) ->value_type(); std::unique_ptr child_builder; RETURN_NOT_OK(MakeBuilder(options_.memory_pool, child_type, &child_builder)); auto builder = std::make_shared( options_.memory_pool, std::move(child_builder)); assert(builder != nullptr); RETURN_NOT_OK(builder->Reserve(new_size)); new_large_list_builders.push_back(std::move(builder)); large_list_idx++; break; } case arrow::NullType::type_id: break; default: { std::shared_ptr value_buffer; if (column_type_id_[i]->id() == arrow::BooleanType::type_id) { ARROW_ASSIGN_OR_RAISE(value_buffer, arrow::AllocateResizableBuffer( arrow::BitUtil::BytesForBits(new_size), options_.memory_pool)); } else { ARROW_ASSIGN_OR_RAISE( value_buffer, arrow::AllocateResizableBuffer( new_size * (arrow::bit_width(column_type_id_[i]->id()) / 8), options_.memory_pool)); } new_value_buffers.push_back(std::move(value_buffer)); if (input_fixed_width_has_null_[fixed_width_idx]) { std::shared_ptr validity_buffer; ARROW_ASSIGN_OR_RAISE( validity_buffer, arrow::AllocateResizableBuffer(arrow::BitUtil::BytesForBits(new_size), options_.memory_pool)); new_validity_buffers.push_back(std::move(validity_buffer)); } else { new_validity_buffers.push_back(nullptr); } fixed_width_idx++; break; } } } // point to newly allocated buffers fixed_width_idx = binary_idx = large_binary_idx = 0; list_idx = 0; large_list_idx = 0; for (auto i = 0; i < num_fields; ++i) { switch (column_type_id_[i]->id()) { case arrow::BinaryType::type_id: case arrow::StringType::type_id: partition_binary_builders_[binary_idx][partition_id] = std::move(new_binary_builders[binary_idx]); binary_idx++; break; case arrow::LargeBinaryType::type_id: case arrow::LargeStringType::type_id: partition_large_binary_builders_[large_binary_idx][partition_id] = std::move(new_large_binary_builders[large_binary_idx]); large_binary_idx++; break; case arrow::ListType::type_id: partition_list_builders_[list_idx][partition_id] = std::move(new_list_builders[list_idx]); list_idx++; break; case arrow::LargeListType::type_id: partition_large_list_builders_[large_list_idx][partition_id] = std::move(new_large_list_builders[large_list_idx]); large_list_idx++; break; case arrow::NullType::type_id: break; default: partition_fixed_width_value_addrs_[fixed_width_idx][partition_id] = const_cast(new_value_buffers[fixed_width_idx]->data()); if (input_fixed_width_has_null_[fixed_width_idx]) { partition_fixed_width_validity_addrs_[fixed_width_idx][partition_id] = const_cast(new_validity_buffers[fixed_width_idx]->data()); } else { partition_fixed_width_validity_addrs_[fixed_width_idx][partition_id] = nullptr; } partition_fixed_width_buffers_[fixed_width_idx][partition_id] = { std::move(new_validity_buffers[fixed_width_idx]), std::move(new_value_buffers[fixed_width_idx])}; fixed_width_idx++; break; } } partition_buffer_size_[partition_id] = new_size; return arrow::Status::OK(); } arrow::Status Splitter::AllocateNew(int32_t partition_id, int32_t new_size) { auto status = AllocatePartitionBuffers(partition_id, new_size); int32_t retry = 0; while (status.IsOutOfMemory() && retry < 3) { // retry allocate std::cout << status.ToString() << std::endl << std::to_string(++retry) << "" retry to allocate new buffer for partition "" << std::to_string(partition_id) << std::endl; int64_t spilled_size; ARROW_ASSIGN_OR_RAISE(auto partition_to_spill, SpillLargestPartition(&spilled_size)); if (partition_to_spill == -1) { std::cout << ""Failed to allocate new buffer for partition "" << std::to_string(partition_id) << "". No partition buffer to spill."" << std::endl; return status; } status = AllocatePartitionBuffers(partition_id, new_size); } if (status.IsOutOfMemory()) { std::cout << ""Failed to allocate new buffer for partition "" << std::to_string(partition_id) << "". Out of memory."" << std::endl; } return status; } arrow::Status Splitter::SpillFixedSize(int64_t size, int64_t* actual) { int64_t current_spilled = 0L; int32_t try_count = 0; while (current_spilled < size && try_count < 5) { try_count++; int64_t single_call_spilled; ARROW_ASSIGN_OR_RAISE(int32_t spilled_partition_id, SpillLargestPartition(&single_call_spilled)) if (spilled_partition_id == -1) { break; } current_spilled += single_call_spilled; } *actual = current_spilled; return arrow::Status::OK(); } arrow::Status Splitter::SpillPartition(int32_t partition_id) { if (partition_writer_[partition_id] == nullptr) { partition_writer_[partition_id] = std::make_shared(this, partition_id); } TIME_NANO_OR_RAISE(total_spill_time_, partition_writer_[partition_id]->Spill()); return arrow::Status::OK(); } arrow::Result Splitter::SpillLargestPartition(int64_t* size) { // spill the largest partition auto max_size = 0; int32_t partition_to_spill = -1; for (auto i = 0; i < num_partitions_; ++i) { if (partition_cached_recordbatch_size_[i] > max_size) { max_size = partition_cached_recordbatch_size_[i]; partition_to_spill = i; } } if (partition_to_spill != -1) { RETURN_NOT_OK(SpillPartition(partition_to_spill)); #ifdef DEBUG std::cout << ""Spilled partition "" << std::to_string(partition_to_spill) << "", "" << std::to_string(max_size) << "" bytes released"" << std::endl; #endif *size = max_size; } else { *size = 0; } return partition_to_spill; } arrow::Status Splitter::DoSplit(const arrow::RecordBatch& rb) { // for the first input record batch, scan binary arrays and large binary // arrays to get their empirical sizes uint32_t size_per_row = 0; if (!empirical_size_calculated_) { auto num_rows = rb.num_rows(); for (int i = 0; i < binary_array_idx_.size(); ++i) { auto arr = std::static_pointer_cast(rb.column(binary_array_idx_[i])); auto length = arr->value_offset(num_rows) - arr->value_offset(0); binary_array_empirical_size_[i] = length / num_rows; size_per_row += binary_array_empirical_size_[i]; } for (int i = 0; i < large_binary_array_idx_.size(); ++i) { auto arr = std::static_pointer_cast( rb.column(large_binary_array_idx_[i])); auto length = arr->value_offset(num_rows) - arr->value_offset(0); large_binary_array_empirical_size_[i] = length / num_rows; size_per_row += large_binary_array_empirical_size_[i]; } empirical_size_calculated_ = true; } for (auto col = 0; col < fixed_width_array_idx_.size(); ++col) { auto col_idx = fixed_width_array_idx_[col]; size_per_row += arrow::bit_width(column_type_id_[col]->id()) / 8; if (rb.column_data(col_idx)->GetNullCount() != 0) { input_fixed_width_has_null_[col] = true; } } int64_t prealloc_row_cnt = options_.offheap_per_task > 0 && size_per_row > 0 ? options_.offheap_per_task / 4 / size_per_row / num_partitions_ : options_.buffer_size; // prepare partition buffers and spill if necessary for (auto pid = 0; pid < num_partitions_; ++pid) { if (partition_id_cnt_[pid] > 0 && partition_buffer_idx_base_[pid] + partition_id_cnt_[pid] > partition_buffer_size_[pid]) { auto new_size = std::min((int32_t)prealloc_row_cnt, options_.buffer_size); // make sure the splitted record batch can be filled if (partition_id_cnt_[pid] > new_size) new_size = partition_id_cnt_[pid]; if (options_.prefer_spill) { if (partition_buffer_size_[pid] == 0) { // first allocate? RETURN_NOT_OK(AllocatePartitionBuffers(pid, new_size)); } else { // not first allocate, spill if (partition_id_cnt_[pid] > partition_buffer_size_[pid]) { // need reallocate? // TODO(): CacheRecordBatch will try to reset builder buffer // AllocatePartitionBuffers will then Reserve memory for builder based on last // recordbatch, the logic on reservation size should be cleaned up RETURN_NOT_OK(CacheRecordBatch(pid, true)); RETURN_NOT_OK(SpillPartition(pid)); RETURN_NOT_OK(AllocatePartitionBuffers(pid, new_size)); } else { RETURN_NOT_OK(CacheRecordBatch(pid, false)); RETURN_NOT_OK(SpillPartition(pid)); } } } else { RETURN_NOT_OK(CacheRecordBatch(pid, true)); #ifdef DEBUG std::cout << ""Attempt to allocate partition buffer, partition id: "" + std::to_string(pid) + "", old buffer size: "" + std::to_string(partition_buffer_size_[pid]) + "", new buffer size: "" + std::to_string(new_size) + "", input record batch size: "" + std::to_string(rb.num_rows()) << std::endl; #endif RETURN_NOT_OK(AllocateNew(pid, new_size)); } } } #ifdef DEBUG std::cout << ""Total bytes allocated: "" << options_.memory_pool->bytes_allocated() << std::endl; #endif #if defined(COLUMNAR_PLUGIN_USE_AVX512) RETURN_NOT_OK(SplitFixedWidthValueBufferAVX(rb)); #else RETURN_NOT_OK(SplitFixedWidthValueBuffer(rb)); #endif RETURN_NOT_OK(SplitFixedWidthValidityBuffer(rb)); RETURN_NOT_OK(SplitBinaryArray(rb)); RETURN_NOT_OK(SplitLargeBinaryArray(rb)); RETURN_NOT_OK(SplitListArray(rb)); RETURN_NOT_OK(SplitLargeListArray(rb)); // update partition buffer base for (auto pid = 0; pid < num_partitions_; ++pid) { partition_buffer_idx_base_[pid] += partition_id_cnt_[pid]; } return arrow::Status::OK(); } arrow::Status Splitter::SplitFixedWidthValueBuffer(const arrow::RecordBatch& rb) { const auto num_rows = rb.num_rows(); for (auto col = 0; col < fixed_width_array_idx_.size(); ++col) { std::fill(std::begin(partition_buffer_idx_offset_), std::end(partition_buffer_idx_offset_), 0); auto col_idx = fixed_width_array_idx_[col]; auto src_addr = const_cast(rb.column_data(col_idx)->buffers[1]->data()); const auto& dst_addrs = partition_fixed_width_value_addrs_[col]; switch (column_type_id_[col_idx]->id()) { #define PROCESS(SHUFFLE_TYPE, _CTYPE) \\ case SHUFFLE_TYPE::type_id: \\ for (auto row = 0; row < num_rows; ++row) { \\ auto pid = partition_id_[row]; \\ auto dst_offset = \\ partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]; \\ reinterpret_cast::CType*>( \\ dst_addrs[pid])[dst_offset] = \\ reinterpret_cast::CType*>(src_addr)[row]; \\ partition_buffer_idx_offset_[pid]++; \\ _mm_prefetch(&reinterpret_cast::CType*>( \\ dst_addrs[pid])[dst_offset + 1], \\ _MM_HINT_T0); \\ } \\ break; PROCESS(arrow::Int8Type, uint8_t) PROCESS(arrow::UInt8Type, uint8_t) PROCESS(arrow::Int16Type, uint16_t) PROCESS(arrow::UInt16Type, uint16_t) PROCESS(arrow::Int32Type, uint32_t) PROCESS(arrow::UInt32Type, uint32_t) PROCESS(arrow::FloatType, uint32_t) PROCESS(arrow::Date32Type, uint32_t) PROCESS(arrow::Time32Type, uint32_t) PROCESS(arrow::Int64Type, uint64_t) PROCESS(arrow::UInt64Type, uint64_t) PROCESS(arrow::DoubleType, uint64_t) PROCESS(arrow::Date64Type, uint64_t) PROCESS(arrow::Time64Type, uint64_t) PROCESS(arrow::TimestampType, uint64_t) #undef PROCESS case arrow::Decimal128Type::type_id: for (auto row = 0; row < num_rows; ++row) { auto pid = partition_id_[row]; auto dst_offset = (partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]) << 1; reinterpret_cast(dst_addrs[pid])[dst_offset] = reinterpret_cast(src_addr)[row << 1]; reinterpret_cast(dst_addrs[pid])[dst_offset | 1] = reinterpret_cast(src_addr)[row << 1 | 1]; partition_buffer_idx_offset_[pid]++; _mm_prefetch(&reinterpret_cast(dst_addrs[pid])[dst_offset + 2], _MM_HINT_T0); } break; case arrow::BooleanType::type_id: for (auto row = 0; row < num_rows; ++row) { auto pid = partition_id_[row]; auto dst_offset = partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]; dst_addrs[pid][dst_offset >> 3] ^= (dst_addrs[pid][dst_offset >> 3] >> (dst_offset & 7) ^ src_addr[row >> 3] >> (row & 7)) << (dst_offset & 7); partition_buffer_idx_offset_[pid]++; } break; default: return arrow::Status::Invalid(""Column type "" + schema_->field(col_idx)->type()->ToString() + "" is not fixed width""); } } return arrow::Status::OK(); } #if defined(COLUMNAR_PLUGIN_USE_AVX512) arrow::Status Splitter::SplitFixedWidthValueBufferAVX(const arrow::RecordBatch& rb) { __m256i inc_one = _mm256_load_si256((__m256i*)(ONES)); const auto num_rows = rb.num_rows(); for (auto col = 0; col < fixed_width_array_idx_.size(); ++col) { std::fill(std::begin(partition_buffer_idx_offset_), std::end(partition_buffer_idx_offset_), 0); auto col_idx = fixed_width_array_idx_[col]; auto src_addr = const_cast(rb.column_data(col_idx)->buffers[1]->data()); const auto& dst_addrs = partition_fixed_width_value_addrs_[col]; switch (column_type_id_[col_idx]) { #define PROCESS(SHUFFLE_TYPE, CTYPE) \\ case Type::SHUFFLE_TYPE: \\ for (auto row = 0; row < num_rows; ++row) { \\ auto pid = partition_id_[row]; \\ auto dst_offset = \\ partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]; \\ reinterpret_cast(dst_addrs[pid])[dst_offset] = \\ reinterpret_cast(src_addr)[row]; \\ partition_buffer_idx_offset_[pid]++; \\ _mm_prefetch(&reinterpret_cast(dst_addrs[pid])[dst_offset + 1], \\ _MM_HINT_T0); \\ } \\ break; PROCESS(SHUFFLE_1BYTE, uint8_t) PROCESS(SHUFFLE_2BYTE, uint16_t) #undef PROCESS case Type::SHUFFLE_4BYTE: { auto rows = num_rows - num_rows % 8; auto src_addr_32 = reinterpret_cast(src_addr); for (auto row = 0; row < rows; row += 8) { __m256i partid_cnt_8x = CountPartitionIdOccurrence(partition_id_, row); // partition id is 32 bit, 8 partition id __m256i partid_8x = _mm256_loadu_si256((__m256i*)(partition_id_.data() + row)); // dst_base and dst_offset are 32 bit __m256i dst_idx_base_8x = _mm256_i32gather_epi32(partition_buffer_idx_base_.data(), partid_8x, 4); __m256i dst_idx_offset_8x = _mm256_i32gather_epi32(partition_buffer_idx_offset_.data(), partid_8x, 4); dst_idx_offset_8x = _mm256_add_epi32(dst_idx_offset_8x, partid_cnt_8x); __m256i dst_idx_8x = _mm256_add_epi32(dst_idx_base_8x, dst_idx_offset_8x); // dst base address is 64 bit __m512i dst_addr_base_8x = _mm512_i32gather_epi64(partid_8x, dst_addrs.data(), 8); // calculate dst address, dst_addr = dst_base_addr + dst_idx*4 //_mm512_cvtepu32_epi64: zero extend dst_offset 32bit -> 64bit //_mm512_slli_epi64(_, 2): each 64bit dst_offset << 2 __m512i dst_addr_offset_8x = _mm512_slli_epi64(_mm512_cvtepu32_epi64(dst_idx_8x), 2); __m512i dst_addr_8x = _mm512_add_epi64(dst_addr_base_8x, dst_addr_offset_8x); // source value is 32 bit __m256i src_val_8x = _mm256_loadu_si256((__m256i*)(src_addr_32 + row)); // scatter _mm512_i64scatter_epi32(nullptr, dst_addr_8x, src_val_8x, 1); // update partition_buffer_idx_offset_ partid_cnt_8x = _mm256_add_epi32(partid_cnt_8x, inc_one); for (int i = 0; i < 8; ++i) { partition_buffer_idx_offset_[partition_id_[row + i]]++; } PrefetchDstAddr(dst_addr_8x, 4); } for (auto row = rows; row < num_rows; ++row) { auto pid = partition_id_[row]; reinterpret_cast(dst_addrs[pid])[partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]] = (src_addr_32)[row]; partition_buffer_idx_offset_[pid]++; } } break; case Type::SHUFFLE_8BYTE: { auto rows = num_rows - num_rows % 8; auto src_addr_64 = reinterpret_cast(src_addr); for (auto row = 0; row < rows; row += 8) { __m256i partid_cnt_8x = CountPartitionIdOccurrence(partition_id_, row); // partition id is 32 bit, 8 partition id __m256i partid_8x = _mm256_loadu_si256((__m256i*)(partition_id_.data() + row)); // dst_base and dst_offset are 32 bit __m256i dst_idx_base_8x = _mm256_i32gather_epi32(partition_buffer_idx_base_.data(), partid_8x, 4); __m256i dst_idx_offset_8x = _mm256_i32gather_epi32(partition_buffer_idx_offset_.data(), partid_8x, 4); dst_idx_offset_8x = _mm256_add_epi32(dst_idx_offset_8x, partid_cnt_8x); __m256i dst_idx_8x = _mm256_add_epi32(dst_idx_base_8x, dst_idx_offset_8x); // dst base address is 64 bit __m512i dst_addr_base_8x = _mm512_i32gather_epi64(partid_8x, dst_addrs.data(), 8); // calculate dst address, dst_addr = dst_base_addr + dst_idx*8 //_mm512_cvtepu32_epi64: zero extend dst_offset 32bit -> 64bit //_mm512_slli_epi64(_, 3): each 64bit dst_offset << 3 __m512i dst_addr_offset_8x = _mm512_slli_epi64(_mm512_cvtepu32_epi64(dst_idx_8x), 3); __m512i dst_addr_8x = _mm512_add_epi64(dst_addr_base_8x, dst_addr_offset_8x); // source value is 64 bit __m512i src_val_8x = _mm512_loadu_si512((__m512i*)(src_addr_64 + row)); // scatter _mm512_i64scatter_epi64(nullptr, dst_addr_8x, src_val_8x, 1); // update partition_buffer_idx_offset_ partid_cnt_8x = _mm256_add_epi32(partid_cnt_8x, inc_one); for (int i = 0; i < 8; ++i) { partition_buffer_idx_offset_[partition_id_[row + i]]++; } PrefetchDstAddr(dst_addr_8x, 8); } // handle the rest for (auto row = rows; row < num_rows; ++row) { auto pid = partition_id_[row]; reinterpret_cast(dst_addrs[pid])[partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]] = (src_addr_64)[row]; partition_buffer_idx_offset_[pid]++; } } break; case Type::SHUFFLE_DECIMAL128: for (auto row = 0; row < num_rows; ++row) { auto pid = partition_id_[row]; auto dst_offset = (partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]) << 1; reinterpret_cast(dst_addrs[pid])[dst_offset] = reinterpret_cast(src_addr)[row << 1]; reinterpret_cast(dst_addrs[pid])[dst_offset | 1] = reinterpret_cast(src_addr)[row << 1 | 1]; partition_buffer_idx_offset_[pid]++; _mm_prefetch(&reinterpret_cast(dst_addrs[pid])[dst_offset + 2], _MM_HINT_T0); } break; case Type::SHUFFLE_BIT: for (auto row = 0; row < num_rows; ++row) { auto pid = partition_id_[row]; auto dst_offset = partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]; dst_addrs[pid][dst_offset >> 3] ^= (dst_addrs[pid][dst_offset >> 3] >> (dst_offset & 7) ^ src_addr[row >> 3] >> (row & 7)) << (dst_offset & 7); partition_buffer_idx_offset_[pid]++; } break; default: return arrow::Status::Invalid(""Column type "" + schema_->field(col_idx)->type()->ToString() + "" is not fixed width""); } } return arrow::Status::OK(); } #endif arrow::Status Splitter::SplitFixedWidthValidityBuffer(const arrow::RecordBatch& rb) { const auto num_rows = rb.num_rows(); for (auto col = 0; col < fixed_width_array_idx_.size(); ++col) { auto col_idx = fixed_width_array_idx_[col]; auto& dst_addrs = partition_fixed_width_validity_addrs_[col]; if (rb.column_data(col_idx)->GetNullCount() == 0) { for (auto pid = 0; pid < num_partitions_; ++pid) { if (partition_id_cnt_[pid] > 0 && dst_addrs[pid] != nullptr) { arrow::BitUtil::SetBitsTo(dst_addrs[pid], partition_buffer_idx_base_[pid], partition_id_cnt_[pid], true); } } } else { for (auto pid = 0; pid < num_partitions_; ++pid) { if (partition_id_cnt_[pid] > 0 && dst_addrs[pid] == nullptr) { // init bitmap if it's null auto new_size = partition_id_cnt_[pid] > options_.buffer_size ? partition_id_cnt_[pid] : options_.buffer_size; ARROW_ASSIGN_OR_RAISE( auto validity_buffer, arrow::AllocateResizableBuffer(arrow::BitUtil::BytesForBits(new_size), options_.memory_pool)); dst_addrs[pid] = const_cast(validity_buffer->data()); arrow::BitUtil::SetBitsTo(dst_addrs[pid], 0, partition_buffer_idx_base_[pid], true); partition_fixed_width_buffers_[col][pid][0] = std::move(validity_buffer); } } auto src_addr = const_cast(rb.column_data(col_idx)->buffers[0]->data()); std::fill(std::begin(partition_buffer_idx_offset_), std::end(partition_buffer_idx_offset_), 0); for (auto row = 0; row < num_rows; ++row) { auto pid = partition_id_[row]; auto dst_offset = partition_buffer_idx_base_[pid] + partition_buffer_idx_offset_[pid]; dst_addrs[pid][dst_offset >> 3] ^= (dst_addrs[pid][dst_offset >> 3] >> (dst_offset & 7) ^ src_addr[row >> 3] >> (row & 7)) << (dst_offset & 7); partition_buffer_idx_offset_[pid]++; } } } return arrow::Status::OK(); } arrow::Status Splitter::SplitBinaryArray(const arrow::RecordBatch& rb) { for (int i = 0; i < binary_array_idx_.size(); ++i) { RETURN_NOT_OK(AppendBinary( std::static_pointer_cast(rb.column(binary_array_idx_[i])), partition_binary_builders_[i], rb.num_rows())); } return arrow::Status::OK(); } arrow::Status Splitter::SplitLargeBinaryArray(const arrow::RecordBatch& rb) { for (int i = 0; i < large_binary_array_idx_.size(); ++i) { RETURN_NOT_OK(AppendBinary( std::static_pointer_cast( rb.column(large_binary_array_idx_[i])), partition_large_binary_builders_[i], rb.num_rows())); } return arrow::Status::OK(); } #define PROCESS_SUPPORTED_TYPES(PROCESS) \\ PROCESS(arrow::BooleanType) \\ PROCESS(arrow::UInt8Type) \\ PROCESS(arrow::Int8Type) \\ PROCESS(arrow::UInt16Type) \\ PROCESS(arrow::Int16Type) \\ PROCESS(arrow::UInt32Type) \\ PROCESS(arrow::Int32Type) \\ PROCESS(arrow::UInt64Type) \\ PROCESS(arrow::Int64Type) \\ PROCESS(arrow::FloatType) \\ PROCESS(arrow::DoubleType) \\ PROCESS(arrow::Date32Type) \\ PROCESS(arrow::Date64Type) \\ PROCESS(arrow::Decimal128Type) \\ PROCESS(arrow::StringType) \\ PROCESS(arrow::BinaryType) arrow::Status Splitter::SplitListArray(const arrow::RecordBatch& rb) { for (int i = 0; i < list_array_idx_.size(); ++i) { auto src_arr = std::static_pointer_cast(rb.column(list_array_idx_[i])); switch (src_arr->value_type()->id()) { #define PROCESS(InType) \\ case InType::type_id: { \\ auto status = AppendList( \\ src_arr, partition_list_builders_[i], rb.num_rows()); \\ if (!status.ok()) return status; \\ } break; PROCESS_SUPPORTED_TYPES(PROCESS) #undef PROCESS default: { return arrow::Status::NotImplemented( ""AppendList internal type not supported, type is "", src_arr->value_type()->ToString()); } break; } } return arrow::Status::OK(); } arrow::Status Splitter::SplitLargeListArray(const arrow::RecordBatch& rb) { for (int i = 0; i < large_list_array_idx_.size(); ++i) { auto src_arr = std::static_pointer_cast( rb.column(large_list_array_idx_[i])); switch (src_arr->value_type()->id()) { #define PROCESS(InType) \\ case InType::type_id: { \\ return AppendList( \\ src_arr, partition_list_builders_[i], rb.num_rows()); \\ } break; PROCESS_SUPPORTED_TYPES(PROCESS) #undef PROCESS default: { return arrow::Status::NotImplemented( ""AppendList internal type not supported, type is "", src_arr->value_type()->ToString()); } break; } } return arrow::Status::OK(); } #undef PROCESS_SUPPORTED_TYPES template arrow::Status Splitter::AppendBinary( const std::shared_ptr& src_arr, const std::vector>& dst_builders, int64_t num_rows) { using offset_type = typename T::offset_type; if (src_arr->null_count() == 0) { for (auto row = 0; row < num_rows; ++row) { offset_type length; auto value = src_arr->GetValue(row, &length); const auto& builder = dst_builders[partition_id_[row]]; RETURN_NOT_OK(builder->Reserve(1)); RETURN_NOT_OK(builder->ReserveData(length)); builder->UnsafeAppend(value, length); } } else { for (auto row = 0; row < num_rows; ++row) { if (src_arr->IsValid(row)) { offset_type length; auto value = src_arr->GetValue(row, &length); const auto& builder = dst_builders[partition_id_[row]]; RETURN_NOT_OK(builder->Reserve(1)); RETURN_NOT_OK(builder->ReserveData(length)); builder->UnsafeAppend(value, length); } else { dst_builders[partition_id_[row]]->AppendNull(); } } } return arrow::Status::OK(); } template arrow::Status Splitter::AppendList( const std::shared_ptr& src_arr, const std::vector>& dst_builders, int64_t num_rows) { using offset_type = typename T::offset_type; using ValueBuilderType = typename arrow::TypeTraits::BuilderType; using ValueArrayType = typename arrow::TypeTraits::ArrayType; std::vector dst_values_builders; for (auto builder : dst_builders) { dst_values_builders.push_back( checked_cast(builder->value_builder())); } auto src_arr_values = std::dynamic_pointer_cast(src_arr->values()); if (src_arr->values()->null_count() == 0) { for (auto row = 0; row < num_rows; ++row) { auto src_arr_values_offset = src_arr->value_offset(row); auto src_arr_values_length = src_arr->value_offset(row + 1) - src_arr_values_offset; RETURN_NOT_OK(dst_builders[partition_id_[row]]->Append()); for (auto i = 0; i < src_arr_values_length; i++) { RETURN_NOT_OK(dst_values_builders[partition_id_[row]]->Append( src_arr_values->GetView(src_arr_values_offset + i))); } } } else { for (auto row = 0; row < num_rows; ++row) { if (src_arr->IsValid(row)) { auto src_arr_values_offset = src_arr->value_offset(row); auto src_arr_values_length = src_arr->value_offset(row + 1) - src_arr_values_offset; RETURN_NOT_OK(dst_builders[partition_id_[row]]->Append()); for (auto i = 0; i < src_arr_values_length; i++) { if (src_arr_values->IsValid(src_arr_values_offset + i)) { RETURN_NOT_OK(dst_values_builders[partition_id_[row]]->Append( src_arr_values->GetView(src_arr_values_offset + i))); } else { RETURN_NOT_OK(dst_values_builders[partition_id_[row]]->AppendNull()); } } } else { RETURN_NOT_OK(dst_builders[partition_id_[row]]->AppendNull()); } } } return arrow::Status::OK(); } std::string Splitter::NextSpilledFileDir() { auto spilled_file_dir = GetSpilledShuffleFileDir(configured_dirs_[dir_selection_], sub_dir_selection_[dir_selection_]); sub_dir_selection_[dir_selection_] = (sub_dir_selection_[dir_selection_] + 1) % options_.num_sub_dirs; dir_selection_ = (dir_selection_ + 1) % configured_dirs_.size(); return spilled_file_dir; } arrow::Result> Splitter::GetSchemaPayload() { if (schema_payload_ != nullptr) { return schema_payload_; } schema_payload_ = std::make_shared(); arrow::ipc::DictionaryFieldMapper dict_file_mapper; // unused RETURN_NOT_OK(arrow::ipc::GetSchemaPayload(*schema_, options_.ipc_write_options, dict_file_mapper, schema_payload_.get())); return schema_payload_; } // ---------------------------------------------------------------------- // RoundRobinSplitter arrow::Result> RoundRobinSplitter::Create( int32_t num_partitions, std::shared_ptr schema, SplitOptions options) { std::shared_ptr res( new RoundRobinSplitter(num_partitions, std::move(schema), std::move(options))); RETURN_NOT_OK(res->Init()); return res; } arrow::Status RoundRobinSplitter::ComputeAndCountPartitionId( const arrow::RecordBatch& rb) { std::fill(std::begin(partition_id_cnt_), std::end(partition_id_cnt_), 0); partition_id_.resize(rb.num_rows()); for (auto& pid : partition_id_) { pid = pid_selection_; partition_id_cnt_[pid_selection_]++; pid_selection_ = (pid_selection_ + 1) % num_partitions_; } return arrow::Status::OK(); } // ---------------------------------------------------------------------- // HashSplitter arrow::Result> HashSplitter::Create( int32_t num_partitions, std::shared_ptr schema, const gandiva::ExpressionVector& expr_vector, SplitOptions options) { std::shared_ptr res( new HashSplitter(num_partitions, std::move(schema), std::move(options))); RETURN_NOT_OK(res->Init()); RETURN_NOT_OK(res->CreateProjector(expr_vector)); return res; } arrow::Status HashSplitter::CreateProjector( const gandiva::ExpressionVector& expr_vector) { // same seed as spark's auto hash = gandiva::TreeExprBuilder::MakeLiteral((int32_t)42); for (const auto& expr : expr_vector) { switch (expr->root()->return_type()->id()) { case arrow::NullType::type_id: break; case arrow::BooleanType::type_id: case arrow::Int8Type::type_id: case arrow::Int16Type::type_id: case arrow::Int32Type::type_id: case arrow::FloatType::type_id: case arrow::Date32Type::type_id: hash = gandiva::TreeExprBuilder::MakeFunction( ""hash32_spark"", {expr->root(), hash}, arrow::int32()); break; case arrow::Int64Type::type_id: case arrow::DoubleType::type_id: hash = gandiva::TreeExprBuilder::MakeFunction( ""hash64_spark"", {expr->root(), hash}, arrow::int32()); break; case arrow::StringType::type_id: hash = gandiva::TreeExprBuilder::MakeFunction( ""hashbuf_spark"", {expr->root(), hash}, arrow::int32()); break; default: hash = gandiva::TreeExprBuilder::MakeFunction(""hash32"", {expr->root(), hash}, arrow::int32()); /*return arrow::Status::NotImplemented(""HashSplitter::CreateProjector doesn't support type "", expr->result()->type()->ToString());*/ } } auto hash_expr = gandiva::TreeExprBuilder::MakeExpression(hash, arrow::field(""pid"", arrow::int32())); return gandiva::Projector::Make(schema_, {hash_expr}, &projector_); } arrow::Status HashSplitter::ComputeAndCountPartitionId(const arrow::RecordBatch& rb) { auto num_rows = rb.num_rows(); partition_id_.resize(num_rows); std::fill(std::begin(partition_id_cnt_), std::end(partition_id_cnt_), 0); arrow::ArrayVector outputs; TIME_NANO_OR_RAISE(total_compute_pid_time_, projector_->Evaluate(rb, options_.memory_pool, &outputs)); if (outputs.size() != 1) { return arrow::Status::Invalid(""Projector result should have one field, actual is "", std::to_string(outputs.size())); } auto pid_arr = std::dynamic_pointer_cast(outputs.at(0)); if (pid_arr == nullptr) { return arrow::Status::Invalid(""failed to cast outputs.at(0)""); } for (auto i = 0; i < num_rows; ++i) { // positive mod auto pid = pid_arr->Value(i) % num_partitions_; if (pid < 0) pid = (pid + num_partitions_) % num_partitions_; partition_id_[i] = pid; partition_id_cnt_[pid]++; } return arrow::Status::OK(); } // ---------------------------------------------------------------------- // FallBackRangeSplitter arrow::Result> FallbackRangeSplitter::Create( int32_t num_partitions, std::shared_ptr schema, SplitOptions options) { auto res = std::shared_ptr( new FallbackRangeSplitter(num_partitions, std::move(schema), std::move(options))); RETURN_NOT_OK(res->Init()); return res; } arrow::Status FallbackRangeSplitter::Init() { input_schema_ = std::move(schema_); ARROW_ASSIGN_OR_RAISE(schema_, input_schema_->RemoveField(0)) return Splitter::Init(); } arrow::Status FallbackRangeSplitter::Split(const arrow::RecordBatch& rb) { EVAL_START(""split"", options_.thread_id) RETURN_NOT_OK(ComputeAndCountPartitionId(rb)); ARROW_ASSIGN_OR_RAISE(auto remove_pid, rb.RemoveColumn(0)); RETURN_NOT_OK(DoSplit(*remove_pid)); EVAL_END(""split"", options_.thread_id, options_.task_attempt_id) return arrow::Status::OK(); } arrow::Status FallbackRangeSplitter::ComputeAndCountPartitionId( const arrow::RecordBatch& rb) { if (rb.column(0)->type_id() != arrow::Type::INT32) { return arrow::Status::Invalid(""RecordBatch field 0 should be "", arrow::int32()->ToString(), "", actual is "", rb.column(0)->type()->ToString()); } auto pid_arr = reinterpret_cast(rb.column_data(0)->buffers[1]->data()); auto num_rows = rb.num_rows(); partition_id_.resize(num_rows); std::fill(std::begin(partition_id_cnt_), std::end(partition_id_cnt_), 0); for (auto i = 0; i < num_rows; ++i) { auto pid = pid_arr[i]; if (pid >= num_partitions_) { return arrow::Status::Invalid(""Partition id "", std::to_string(pid), "" is equal or greater than "", std::to_string(num_partitions_)); } partition_id_[i] = pid; partition_id_cnt_[pid]++; } return arrow::Status::OK(); } } // namespace shuffle } // namespace sparkcolumnarplugin ",16171,True,2703.5649554793927,median "= Divelog - Developer Guide v.1.4 :site-section: DeveloperGuide :toc: :toc-title: :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/CS2113-AY1819S1-W13-2/main/tree/master By: `Team CS2113-AY1819S1-W13-2`      Since: `Aug 2018`      Licence: `MIT` //tag::intro[] [[intro]] == Context When a diver goes on a dive, the pressure underwater causes nitrogen to build up in the blood stream. When the diver returns to the surface, he or she has that level of nitrogen in his or her blood. However, due to the atmospheric pressure being lower than underwater, the partial pressure of nitrogen is different. Having too much nitrogen build up can be dangerous particularly if you are planning a second dive or going on a flight as the nitrogen can form bubbles inside one’s bloodstream. In order to solve this problem, divers manually calculate their “pressure groups”. The pressure groups are on a range from A,B,C all the way to Z. Depending on your pressure group you can attempt your next dive. It is generally advised to be below the “B” pressure group before your next dive. Before attempting your next dive, you have to plan your dive first! You want to dive to 15 metres for half an hour after your pressure group from your first dive is D. Are you sure it's safe to do so? Use our Divelog to find out! //end::intro[] == Setting up === Prerequisites . *JDK `9`* or later + [WARNING] JDK `10` on Windows will fail to run tests in <> due to a https://github.com/javafxports/openjdk-jfx/issues/66[JavaFX bug]. Windows developers are highly recommended to use JDK `9`. . *IntelliJ* IDE + // tag::javafx[] [[JavaFXTip]] [NOTE] IntelliJ by default has Gradle and JavaFx plugins installed. + Do not disable them. If you have disabled them, go to `File` > `Settings` > `Plugins` to re-enable them. If there is still error after enabling them, you will need to go to `File` > `Settings` > `Build, Execution, Deployment` > `Compiler` > `Java Compiler` > `Javac options` and add the following: `--add-modules=javafx.fxml`. This is illustrated by the diagram below. image::commandlineparameters.png[width=""800""] // end::javafx[] === Setting up the project in your computer . Fork this repo, and clone the fork to your computer . Open IntelliJ (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project dialog first) . Set up the correct JDK version for Gradle .. Click `Configure` > `Project Defaults` > `Project Structure` .. Click `New...` and find the directory of the JDK . Click `Import Project` . Locate the `build.gradle` file and select it. Click `OK` . Click `Open as Project` . Click `OK` to accept the default settings . Open a console and run the command `gradlew processResources` (Mac/Linux: `./gradlew processResources`). It should finish with the `BUILD SUCCESSFUL` message. + This will generate all resources required by the application and tests. === Verifying the setup . Run the `seedu.divelog.MainApp` and try a few commands . <> to ensure they all pass. === Configurations to do before writing code ==== Configuring the coding style This project follows https://github.com/oss-generic/process/blob/master/docs/CodingStandards.adoc[oss-generic coding standards]. IntelliJ's default style is mostly compliant with ours but it uses a different import order from ours. To rectify, . Go to `File` > `Settings...` (Windows/Linux), or `IntelliJ IDEA` > `Preferences...` (macOS) . Select `Editor` > `Code Style` > `Java` . Click on the `Imports` tab to set the order * For `Class count to use import with '\\*'` and `Names count to use static import with '*'`: Set to `999` to prevent IntelliJ from contracting the import statements * For `Import Layout`: The order is `import static all other imports`, `import java.\\*`, `import javax.*`, `import org.\\*`, `import com.*`, `import all other imports`. Add a `` between each `import` Optionally, you can follow the <> document to configure Intellij to check style-compliance as you write code. ==== Updating documentation to match your fork After forking the repo, the documentation will still have the SE-EDU branding and refer to the `se-edu/addressbook-level4` repo. If you plan to develop this fork as a separate product (i.e. instead of contributing to `se-edu/addressbook-level4`), you should do the following: . Configure the <> in link:{repoURL}/build.gradle[`build.gradle`], such as the `site-name`, to suit your own project. . Replace the URL in the attribute `repoURL` in link:{repoURL}/docs/DeveloperGuide.adoc[`DeveloperGuide.adoc`] and link:{repoURL}/docs/UserGuide.adoc[`UserGuide.adoc`] with the URL of your fork. ==== Setting up CI Set up Travis to perform Continuous Integration (CI) for your fork. See <> to learn how to set it up. After setting up Travis, you can optionally set up coverage reporting for your team fork (see <>). [NOTE] Coverage reporting could be useful for a team repository that hosts the final version but it is not that useful for your personal fork. Optionally, you can set up AppVeyor as a second CI (see <>). [NOTE] Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based) ==== Getting started with coding When you are ready to start coding, 1. Get some sense of the overall design by reading <>. 2. Take a look at <>. == Design [[Design-Architecture]] === Architecture .Architecture Diagram image::Architecture.png[width=""600""] The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component. [TIP] The `.pptx` files used to create diagrams in this document can be found in the link:{repoURL}/docs/diagrams/[diagrams] folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose `Save as picture`. `Main` has only one class called link:{repoURL}/src/main/java/seedu/address/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. Two of those classes play important roles at the architecture level. * `EventsCenter` : This class (written using https://github.com/google/guava/wiki/EventBusExplained[Google's Event Bus library]) is used by components to communicate with other components using events (i.e. a form of _Event Driven_ design) * `LogsCenter` : Used by many classes to write log messages to the App's log file. The rest of the App consists of four components. * <>: The UI of the App. * <>: The command executor. * <>: Holds the data of the App in-memory. * <>: 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 it's API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class. .Class Diagram of the Logic Component image::LogicClassDiagram.png[width=""800""] [discrete] ==== Events-Driven nature of the design The _Sequence Diagram_ below shows how the components interact for the scenario where the user issues the command `delete 1`. .Component interactions for `delete 1` command (part 1) image::SDforDeleteDiveSession.png[width=""800""] [NOTE] Note how the `Model` simply raises a `DiveLogChangedEvent` when the Dive Session data are changed, instead of asking the `Storage` to save the updates to the hard disk. The diagram below shows how the `EventsCenter` reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time. .Component interactions for `delete 1` command (part 2) image::SDforDeleteDiveSessionEventHandling.png[width=""800""] [NOTE] Note how the event is propagated through the `EventsCenter` to the `Storage` and `UI` without `Model` having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components. The sections below give more details of each component. [[Design-Ui]] === UI component .Structure of the UI Component image::UiClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/ui/Ui.java[`Ui.java`] The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `DiveListPanel`, `StatusBarFooter`, `BrowserPanel` 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/address/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. * Binds itself to the data in the `Model` so that the UI can auto-update when data in the `Model` change. * Responds to events raised from various parts of the App and updates the UI accordingly. Some of the choices here was choosing the type of placeholders to use like `labels` etc to store the data. Eventually it boiled down to the nature of the data and how it was to be displayed at the end of the day. [[Design-Logic]] === Logic component [[fig-LogicClassDiagram]] .Structure of the Logic Component image::LogicClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/logic/Logic.java[`Logic.java`] . `Logic` uses the `DiveLogParser` class to parse the user command. . This results in a `Command` object which is executed by the `LogicManager`. . The command execution can affect the `Model` (e.g. adding a diveSession) and/or raise events. . The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`. Given below is the Sequence Diagram for interactions within the `Logic` component for the `execute(""delete 1"")` API call. .Interactions Inside the Logic Component for the `delete 1` Command image::DeleteDiveSessionSdForLogic.png[width=""800""] //tag::Design-Model[] [[Design-Model]] === Model component .Structure of the Model Component image::ModelClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model.java`] The `Model`, * stores a `UserPref` object that represents the user's preferences. * stores the DiveLog data. * enforces relational rules between dive sessions (i.e Dives may not overlap). For more information on this take a look at the section on <>. * 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. Some choices made here include the encapsulation of even simple values such as depth which is stored as a `DepthProfile` object. By doing so suppose we want to extend Depth to support complex dives with multiple depths or different units, we can simply update `DepthProfile` without breaking existing code. Similarly, we also decided to have `DiveSession` implement java's `Comparable` interface as it makes sorting the dives easier. Sorting the dives is an essential part of making sure that the dives retain their integrity. A rough summary of what each class does is as follows: [options=""header""] |========================================= |Class(es) | Role |`DiveSession` | Holds data about the dives. Provides a few getters and setters. |`Time`, `OurDate`, `PressureGroup`, `DepthProfile`, `Location` | Encapsulates simple properties of the dives |`DiveSessionList` | Stores a list of `DiveSessions` and provides properties of the list. |`DiveLog` | Handles updating the DiveSessionList. |`VersionedDiveLog` | Handles undo/redo feature and versioning. |========================================= //end::Design-Model[] [[Design-Storage]] === Storage component .Structure of the Storage Component image::StorageClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/storage/Storage.java[`Storage.java`] The `Storage` component, * can save `UserPref` objects in json format and read it back. * can save the Dive Log data in xml format and read it back. [[Design-Commons]] === Common classes Classes used by multiple components are in the `seedu.addressbook.commons` package. //tag::application-state[] ==== Application State [[application-state]] As of now certain things that are planned in the future require global data. For instance, the `set_units` command. These are stored in the `ApplicationState` singleton. Any other temporary information that is global and stored within the run should be added as a property to {repoURL}/src/main/java/seedu/divelog/commons/core/ApplicationState.java[`ApplicationState.java`] //end::application-state[] == Implementation This section describes some noteworthy details on how certain features are implemented. // tag::undoredo[] === Undo/Redo feature ==== Current Implementation The undo/redo mechanism is facilitated by `VersionedAddressBook`. It extends `AddressBook` with an undo/redo history, stored internally as an `addressBookStateList` and `currentStatePointer`. Additionally, it implements the following operations: * `VersionedAddressBook#commit()` -- Saves the current address book state in its history. * `VersionedAddressBook#undo()` -- Restores the previous address book state from its history. * `VersionedAddressBook#redo()` -- Restores a previously undone address book state from its history. These operations are exposed in the `Model` interface as `Model#commitAddressBook()`, `Model#undoAddressBook()` and `Model#redoAddressBook()` respectively. Given below is an example usage scenario and how the undo/redo mechanism behaves at each step. Step 1. The user launches the application for the first time. The `VersionedAddressBook` will be initialized with the initial address book state, and the `currentStatePointer` pointing to that single address book state. image::UndoRedoStartingStateListDiagram.png[width=""800""] Step 2. The user executes `delete 5` command to delete the 5th diveSession in the address book. The `delete` command calls `Model#commitAddressBook()`, causing the modified state of the address book after the `delete 5` command executes to be saved in the `addressBookStateList`, and the `currentStatePointer` is shifted to the newly inserted address book state. image::UndoRedoNewCommand1StateListDiagram.png[width=""800""] Step 3. The user executes `add n/David ...` to add a new diveSession. The `add` command also calls `Model#commitAddressBook()`, causing another modified address book state to be saved into the `addressBookStateList`. image::UndoRedoNewCommand2StateListDiagram.png[width=""800""] [NOTE] If a command fails its execution, it will not call `Model#commitAddressBook()`, so the address book state will not be saved into the `addressBookStateList`. Step 4. The user now decides that adding the diveSession was a mistake, and decides to undo that action by executing the `undo` command. The `undo` command will call `Model#undoAddressBook()`, which will shift the `currentStatePointer` once to the left, pointing it to the previous address book state, and restores the address book to that state. image::UndoRedoExecuteUndoStateListDiagram.png[width=""800""] [NOTE] If the `currentStatePointer` is at index 0, pointing to the initial Dive Log state, then there are no previous address book states to restore. The `undo` command uses `Model#canUndoAddressBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the undo. The following sequence diagram shows how the undo operation works: image::UndoRedoSequenceDiagram.png[width=""800""] The `redo` command does the opposite -- it calls `Model#redoAddressBook()`, which shifts the `currentStatePointer` once to the right, pointing to the previously undone state, and restores the address book to that state. [NOTE] If the `currentStatePointer` is at index `addressBookStateList.size() - 1`, pointing to the latest address book state, then there are no undone address book states to restore. The `redo` command uses `Model#canRedoAddressBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the redo. Step 5. The user then decides to execute the command `list`. Commands that do not modify the address book, such as `list`, will usually not call `Model#commitAddressBook()`, `Model#undoAddressBook()` or `Model#redoAddressBook()`. Thus, the `addressBookStateList` remains unchanged. image::UndoRedoNewCommand3StateListDiagram.png[width=""800""] Step 6. The user executes `clear`, which calls `Model#commitAddressBook()`. Since the `currentStatePointer` is not pointing at the end of the `addressBookStateList`, all address book states after the `currentStatePointer` will be purged. We designed it this way because it no longer makes sense to redo the `add n/David ...` command. This is the behavior that most modern desktop applications follow. image::UndoRedoNewCommand4StateListDiagram.png[width=""800""] The following activity diagram summarizes what happens when a user executes a new command: image::UndoRedoActivityDiagram.png[width=""650""] ==== Design Considerations ===== Aspect: How undo & redo executes * **Alternative 1 (current choice):** Saves the entire Dive Log. ** Pros: Easy to implement. ** Cons: May have performance issues in terms of memory usage. * **Alternative 2:** Individual command knows how to undo/redo by itself. ** Pros: Will use less memory (e.g. for `delete`, just save the diveSession being deleted). ** Cons: We must ensure that the implementation of each individual command are correct. ===== Aspect: Data structure to support the undo/redo commands * **Alternative 1 (current choice):** Use a list to store the history of address book states. ** Pros: Easy for new Computer Science student undergraduates to understand, who are likely to be the new incoming developers of our project. ** Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update both `HistoryManager` and `VersionedAddressBook`. * **Alternative 2:** Use `HistoryManager` for undo/redo ** Pros: We do not need to maintain a separate list, and just reuse what is already in the codebase. ** Cons: Requires dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as `HistoryManager` now needs to do two different things. // end::undoredo[] // tag::lookuptable[] [[lookuptable]] === Looking Up Dive Tables For Pressure Groups At the heart of the divelog app is the ability to automatically calculate nitrogen pressure groups. To do so we adhere to PADI's dive charts, available here https://elearning.padi.com/company0/tools/RDP_Table%20Met.pdf. These charts provide a lookup table for divers through which they can determine their current pressure group. The underlying implementation for these charts can be found in the `PadiDiveTable` class. A such the dive tales are stored in the `resources` folder as JSON files. They are loaded using the `DiveTableUtil` class via the FASTXML Jackson library. The `PadiDiveTable` itself is a singleton class. This choice was made as it makes sense to load the Dive Tables only once at the stat into memory (although in its current form it is not the case). ==== Design Considerations ===== Aspect: Retrieving Dive Tables * **Alternative 1 (current choice):** Use JSON files ** Pros: Easy to change data within tables. ** Cons: May have performance issues if the tables are too large as it reads from disk. * **Alternative 2:** Hard code the tables ** Pros: Have mildly smaller impact on performance as data is loaded into memory at start up. ** Cons: Very tedious to implement, results in unreadable code. ===== Aspect: Minimising File Reads And Data Duplication * **Alternative 1 (current choice)**: Use a singleton class ** Pros: It is possible to read the file only once and the memory used by the objects will only exist in one place. This saves both memory and disc writes. ** Cons: Can be troublesome to implement. * **Alternative 2: ** Just use `PADIDiveTable` standard classes ** Pros: Easy to implement ** Cons: Wastes memory and performs unnecessary IO. // end::lookuptable[] // tag::CRUD[] === Consistency checks for `DiveSession` objects during Creation/Update At its heart, the application is a dive log. The source code for this application was adopted from an addressbook application. The addressbook has a relatively simple set of rules, DiveLog on the other hand has a more complicated set of rules which have to be followed. This is because the starting pressure group on each dive is dependent on the previous dive's end time and ending pressure group. In turn, the ending pressure group is dependent on the starting pressure group and depth of a dive. This poses a lot of problems as a single update to the system requires recalculating all subsequent dive's pressure groups. Furthermore, it is only after all calculations are complete that the system can make sure that the update is valid. Some possible sources of inconsistency include: * Dives with overlapping time periods - these cause problems in the chain as the PADI tables are only meant to be used by a single diver doing one dive at a time. * Dives that are deemed too deep and too long by PADI - we have no way of determining their nitrogen level apat from the tables. * Dives which cause other dives to become too dangrous. Lets say you add a dive inbetween two dives. This may cause the later dive to be deemed as too dangerous. At the end we have incorporated most of the code into our model. For `add` and `edit` we required atomicity thus the general flow is as follows: . Create a temporary copy of the `DiveSessionList`. . Perform the update/addition on this list and sort it to make calculations easier. . Check if there are any overlapping dives .. If there are overlapping dives throw `DiveOverlapsException`. . Recalculate pressure groups and check for consistency .. If not consistent throw `LimitExceededException` error. . Commit new `DiveSessionList` to divelog. Update `VersionedDivelog` 's current pointer. The flow can be seen in the sequence diagram below: image::ConsistencyCheckSequenceDiagram.png[width: 650px] In terms of calculations, the pressure group properties of the dives themselves will mutate to support ==== Design Considerations Upon failure of calculations it is important that the divelog remains in a consistent state. For instance, when updating the dive log if after adding a dive we see that it is causing issues in the dive log, or if we edit a dive to have overlapping time periods with another dive, the divelog should roll back the latest transaction and throw an error. This calls for atomicity in our Create, Update and Delete. Fortunately, in our case, deleting the dive cannot actually cause a violation as it only makes the dives safer. Thus our design considerations could be summed up as follows: * Ensure consistency in the divelog * Ensure creating and Updating the divelog are atomic ===== Aspect: Ensure consistency in the divelog * *Alternative 1*: implementing rules for consistency in `logic` module. ** Pros: Stronger Separation of Concerns. ** Cons: Will require duplicating code accross `AddCommand` and `EditCommand`. This will lead to inconsistent behaviour between the two and more lines of code to debug. * *Alternative 2*: implementing rules for consistency in `model` module. ** Pros: Only one code base to debug. System will remain consistent. ** Cons: Weaker separation of concerns than if implemented separately. Can also mean a bug effects both add and edit making the system unreliable. ===== Aspect: Ensure creating and updating the divelog are atomic * *Alternative 1*: Creating a temporary copy of the list and mutating the copy ** Pros: Simple to implement and fast. ** Cons: Inefficient * *Alternative 2*: Having a separate data structure that only handles mutation after the edited dive. ** Pros: Will be more efficient. ** Cons: More code will need to be written. Since `VersionedDiveLog` already maintains copies, it is just a matter of passing the reference of the temporary dive list to the system. Furthermore, most divers will not have more than 100 dives. // end::CRUD[] // tag::planning[] [[portover]] === New Feature: Planning Mode (with `portover` capability) From our verbal surveys with test users and from our user stories, we have decided to implement a Planning mode in order for users to plan their dives ahead of their trips safely without worrying about corrupting their current data. ==== Design Considerations * **Alternative 1 (current choice)**: When in planning mode, a counter increments every time a command is called. In addition, there is now a state called planning mode, which shows true if in planning mode and false if in normal mode. + *** When the user chooses to exit and enter `normalmode`, the underlying method calls for a `undo` method and decreases the counter. This will repeat until the counter is zero, whereby then the state of the machine will change back to normal mode. + *** If the user decides to call `portover`, the counter is simply reset to 0 and the state of the machine is changed back to normal mode. *** *Pros:* Uses a method that is already present, `undo`. This means there won't be two implementations of the same method. *** *Cons:* The limitations of this method lie in its sole ability to handle `add`, `delete` and `edit` commands in planning mode. Any other commands are not accepted. * **Alternative 2**: Create a temporary Stack to store commands instead of just a counter. ** Pros: All types of commands can now be used in planning mode, and not just `add`, `delete` and `edit` ** Cons: Extra implementations and considerations have to be taken into account. This might increase coupling between classes. // end::planning[] // tag::sorting[] === Sorting of data We have considered that once a user has a considerable number of dives registered in the app, the user would potentially have difficulty finding dives, even with the `find` function. (as many dives can have the same parameters such as location) To simplify the app usage, this command allows for users to decide the way that the data shown to them is organised. ==== Design Considerations * **Current implementation**: A sort method with a time/date comparator is called every time a new dive is added, deleted or edited. * **Potential improvement to the feature 1**: Add a `sortby` CLI command. ** Method to implement: + *Step 1:* Create a new Command[[GetStartedProgramming-RemarkCommand]] with a Command Parser that reads in the Command Prefix and a [KEYWORD], which will dictate the parameter to sort by. The Command and Parser file should look like below: .Command Parser File Sample image::sortbyparser.png[width=""600""] .Command Class File Sample image::sortbyclass.png[width=""600""] Optional: Create a enum with the parameters you want to sort the data by (E.g Time, Location and Duration) *_Sample Enum_* + _public enum SortCategory { + TIME, LOCATION, DURATION + }_ *Step 2:* Create a sort method preferably in a separate utils class. This method should take in the parameter to sort by. (It will be easier and less prone to mistakes if Step 2 was used) The corresponding comparators should be created. The sort method should look something like b .Sort method Sample image::sortmethod.png[width=""500""] *Step 3:* Ensure that the divelog refreshes / reflects the newly sorted. You can do this by calling for the sort method after every add or edit command. You can also create a new event in commons.events. ** Pros: Once implemented, to increase the number of parameters / methods to sort the data by, simply create a new corresponding comparator, add the respective prefixes the parse for, and to increase the number of parameters included in the Enum file. ** Cons: Can be troublesome to implement in the beginning. **Potential improvement to the feature 2**: Reverse the current order by calling `reverseorder` ** Method to implement: Simply reverse the comparator in the sorting methods, where comparators are stored in a sample method shown in Figure 12. (above) ** Pros: Improved usability and thus better UX. ** Cons: Increased difficulty to maintain as the // end::sorting[] // tag::newparam[] === New Parameters & conditions in a DiveSession ==== Timezone Considering that users would dive in many different parts of the world, we have taken the effort to implement a Timezone parameter to ease users in adding new dives into the Dive Log without the need to convert any time to Local time. + We have decided to utilise the format of UTC, given its universal usage around the world. The UTC timezones range from -12 to +12, including 0. Singapore lies in the timezone of UTC+8. * **Alternative 1 (current choice)**: When calculating Pressure Groups using TimeZone, all time is converted to UTC time before calculating duration, and subsequently pressure groups and its resultant results. ** Pros: There is no confusion of timezones when doing complex calculations. ** Cons: There is a need to convert time from UTC time back to local time. If not taken care of, inaccurate times may be shown. * **Alternative 2: ** Adopt Java SE 9's java.time library ** Pros: There are pre-built algorithms and methods in the library. ** Cons: Takes time to learn and to adopt the methods, which might not be efficient for our light usage. ==== Time and OurDate Time and OurDate are 2 of the new parameters in the Dive Log. In order to be able to calculate the Pressure Groups automatically, there has to be a time and date parameter. We have decided to create our own class. * **Alternative 1 (current choice)**: Use a 4 length String to contain time and 8 length String to contain date. ** Pros: When reading in data from the `ArgumentMultimap`, it requires very little effort in parsing. Also, the use of String allows for versatile typecasting into long, int, or Java SE 7's SimpleDateFormat. Similarly, the use of String and long as main type allows for better versatility among different methods. ** Cons: Data needs to be parsed into Java SE 8's java.date and Java SE 7's SimpleDateFormat in order to calculate time differences. This means that there can potentially be many type conflicts. However, this problem is contained in a helper class `CompareUtils` which handles methods like `checkTimeDifference`, `getLocalDate` and `convertTimeToLocal`. * **Alternative 2: ** Adopt Java SE 9's java.time library ** Pros: More volatile as the library contains many ready-made solutions. Also, java.time also allows for the easy implementation of *local time*, which is one of our improvements made to AB4. ** Cons: Takes time to learn and to adopt the methods, which might not be efficient for our light usage. // end::newparam[] // tag::local_units[] === Localized Units As of `v1.3`, a `set_units` command was added. This allows the user to switch between meters and feet. As shown in the diagram below, the implementation of this command involves altering the `ApplicationState` singleton. Once the `ApplicationState` is updated a `UnitsChangedEvent` is posted to the `EventsCenter`. The `EventsCenter` issues a call to the UI. The relevant parts of the UI will be forced to re-render themselves to match the new units. image::setunitsSequenceDiagram.png[width=450] As of `v1.4` the `ParserUtil#parseDepthProfile(String depth)` also reads this state, and converts the units to meters. Internally all the units are stored as meters. This choice was largely made to keep things simple. The `ApplicationState` also exposes a function to get the current units setting. // end::local_units[] // tag::colourCode[] === Colour coding of the Pressure Groups Through engagement with our test users and from our user stories, the pressure group needed to be obvious and easy to reference to our users, which meant that it had to stand out on the display. These pressure group would let the divers know if their dives was safe and how much leeway they might have in the water. As such, the `BrowserPanel` takes into the account the pressure groups that are supposed to be returned and adds colour to it. ==== Design Considerations * **Current implementation**: When the pressure group returned the the `BrowserPanel` for display to the user, the colour is changed by changing its CSS style. The colour is chosen from green [`#0FFF0F`] to yellow [`#F5FF07`] to red [`#FF0000`]. The colour are in order of normal to moderate and finally, dangerous amount of nitrogen in the blood of the user or their pressure group. The colours are seen in the figure below. ** Pros: The pressure group is clearly distinguished by its severity at one glance. ** Cons: Not all may be able to use it. For example, users who may be colour-blind. .Colour Gradient Chart image::Colour_gradient.png[width=""600""] * **Alternative implementation**: Instead of changing the colour, the text font maybe increased in proportion to the severity of the pressure group. ** Pros: Most people would be able to see it. If the text is very big, the warning regarding its severity will be obvious. ** Cons: May make the UI and screen messy. Will need to have a comparision chart to compare the size to. * **Potential Improvements**: The current implementation could be combined with the alternative implementation, to make the emphasis on the pressure group being severe. For example, the pressure group could be in the red zone (dangerous/severe zone) and the text font would be increased. ** Pros: Makes it even clearer, especially if the pressure group is at dangerous levels. Allows more users to potentially benefit from it. ** Cons: If not properly implemented, it might end up making the UI messy. // end::colourCode[] // tag::Logging[] === 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. App name, logging level) through the configuration file (default: `config.json`). == Documentation We use asciidoc for writing documentation. [NOTE] We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting. === Editing Documentation See <> to learn how to render `.adoc` files locally to preview the end result of your edits. Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your `.adoc` files in real-time. === Publishing Documentation See <> to learn how to deploy GitHub Pages using Travis. === Converting Documentation to PDF format We use https://www.google.com/chrome/browser/desktop/[Google Chrome] for converting documentation to PDF format, as Chrome's PDF engine preserves hyperlinks used in webpages. Here are the steps to convert the project documentation files to PDF format. . Follow the instructions in <> to convert the AsciiDoc files in the `docs/` directory to HTML format. . Go to your generated HTML files in the `build/docs` folder, right click on them and select `Open with` -> `Google Chrome`. . Within Chrome, click on the `Print` option in Chrome's menu. . Set the destination to `Save as PDF`, then click `Save` to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below. .Saving documentation as PDF files in Chrome image::chrome_save_as_pdf.png[width=""300""] [[Docs-SiteWideDocSettings]] === Site-wide Documentation Settings The link:{repoURL}/build.gradle[`build.gradle`] file specifies some project-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how all documentation files within this project are rendered. [TIP] Attributes left unset in the `build.gradle` file will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of site-wide attributes |=== |Attribute name |Description |Default value |`site-name` |The name of the website. If set, the name will be displayed near the top of the page. |_not set_ |`site-githuburl` |URL to the site's repository on https://github.com[GitHub]. Setting this will add a ""View on GitHub"" link in the navigation bar. |_not set_ |`site-seedu` |Define this attribute if the project is an official SE-EDU project. This will render the SE-EDU navigation bar at the top of the page, and add some SE-EDU-specific navigation items. |_not set_ |=== [[Docs-PerFileDocSettings]] === Per-file Documentation Settings Each `.adoc` file may also specify some file-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how the file is rendered. Asciidoctor's https://asciidoctor.org/docs/user-manual/#builtin-attributes[built-in attributes] may be specified and used as well. [TIP] Attributes left unset in `.adoc` files will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of per-file attributes, excluding Asciidoctor's built-in attributes |=== |Attribute name |Description |Default value |`site-section` |Site section that the document belongs to. This will cause the associated item in the navigation bar to be highlighted. One of: `UserGuide`, `DeveloperGuide`, ``LearningOutcomes``{asterisk}, `AboutUs`, `ContactUs` _{asterisk} Official SE-EDU projects only_ |_not set_ |`no-site-header` |Set this attribute to remove the site navigation bar. |_not set_ |=== === Site Template The files in link:{repoURL}/docs/stylesheets[`docs/stylesheets`] are the https://developer.mozilla.org/en-US/docs/Web/CSS[CSS stylesheets] of the site. You can modify them to change some properties of the site's design. The files in link:{repoURL}/docs/templates[`docs/templates`] controls the rendering of `.adoc` files into HTML5. These template files are written in a mixture of https://www.ruby-lang.org[Ruby] and http://slim-lang.com[Slim]. [WARNING] ==== Modifying the template files in link:{repoURL}/docs/templates[`docs/templates`] requires some knowledge and experience with Ruby and Asciidoctor's API. You should only modify them if you need greater control over the site's layout than what stylesheets can provide. The SE-EDU team does not provide support for modified template files. ==== [[Testing]] == Testing === Running Tests There are three ways to run tests. [TIP] The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies. *Method 1: Using IntelliJ JUnit test runner* * To run all tests, right-click on the `src/test/java` folder and choose `Run 'All Tests'` * To run a subset of tests, you can right-click on a test package, test class, or a test and choose `Run 'ABC'` *Method 2: Using Gradle* * Open a console and run the command `gradlew clean allTests` (Mac/Linux: `./gradlew clean allTests`) [NOTE] See <> for more info on how to run tests using Gradle. *Method 3: Using Gradle (headless)* Thanks to the https://github.com/TestFX/TestFX[TestFX] library we use, our GUI tests can be run in the _headless_ mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running. To run tests in headless mode, open a console and run the command `gradlew clean headless allTests` (Mac/Linux: `./gradlew clean headless allTests`) === Types of tests We have two types of tests: . *GUI Tests* - These are tests involving the GUI. They include, .. _System Tests_ that test the entire App by simulating user actions on the GUI. These are in the `systemtests` package. .. _Unit tests_ that test the individual components. These are in `seedu.divelog.ui` package. . *Non-GUI Tests* - These are tests not involving the GUI. They include, .. _Unit tests_ targeting the lowest level methods/classes. + e.g. `seedu.divelog.commons.StringUtilTest` .. _Integration tests_ that are checking the integration of multiple code units (those code units are assumed to be working). + e.g. `seedu.divelog.storage.StorageManagerTest` .. Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together. + e.g. `seedu.divelog.logic.LogicManagerTest` === Troubleshooting Testing **Problem: `HelpWindowTest` fails with a `NullPointerException`.** * Reason: One of its dependencies, `HelpWindow.html` in `src/main/resources/docs` is missing. * Solution: Execute Gradle task `processResources`. == Dev Ops === Build Automation See <> to learn how to use Gradle for build automation. === Continuous Integration We use https://travis-ci.org/[Travis CI] to perform _Continuous Integration_ on our projects. See <> and <> for more details. === Making a Release Here are the steps to create a new release. . Update the version number in link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp.java`]. . Generate a JAR file <>. . Tag the repo with the version number. e.g. `v0.1` . https://help.github.com/articles/creating-releases/[Create a new release using GitHub] and upload the JAR file you created. === Managing Dependencies A project often depends on third-party libraries. For example, Address Book depends on the http://wiki.fasterxml.com/JacksonHome[Jackson library] for XML parsing. Managing these _dependencies_ can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives. + a. Include those libraries in the repo (this bloats the repo size) + b. Require developers to download those libraries manually (this creates extra work for developers) [appendix] == Product Scope *Target user profile*: * Is a beginner Diver * Goes diving frequently. * Has the need to keep track of Nitrogen Levels so that he/she does not end up needing to undergo decompression. *Value proposition*: An automated desktop app to keep track of nitrogen levels for divers. [appendix] == User Stories Priorities: High (must have) - `* * \\*`, Medium (nice to have) - `* \\*`, Low (unlikely to have) - `*`, Null (Not Implementing) - `-` [cols=""2,2,2,2"", options=""header""] .List of user stories |========================================= |Priority |As a... |I want to... | So that I can... |`* * *` |Diver |Know my current pressure group |Plan my next dive safely |`* * *` |Diver |Add dive entries |So that I can know my pressure group. |`**` |Diver |Be able to enter data in local time |Save time when calculating my pressure groups. |`**` |Diver |Plan my dives ahead of performing them |So that I know what a safe limit is. |`*` |Diver |to see where I have been |Reminisce |`-` |Dive master |Check my dive buddy’s logs |Make sure all of us have a safe trip |========================================= [appendix] == Use Cases (For all use cases below, the *System* is the `Dive Log Application` and the *Actor* is the `user`, unless specified otherwise) [discrete] === Use case: Add dive session *MSS* . Diver opens system . System shows him a list of dive sessions . Diver chooses to add a new dive session . System returns and requests for data from Diver . Diver adds time spent at different depths, marine species diver has seen . System confirms the details . Diver confirms the details . System adds the dive session and shows it is successful . Diver confirms . System shows recommended time to next dive or flight + Use case ends. *Extensions* [none] * 3a. The data entered is invalid. (i.e. The diver enters text instead of numeric values for depth.) + [none] ** 3a1. System points to the invalid data and asks user to clarify data. + Use case resumes at step 3. [discrete] === Use case: View details of a dive session *MSS* . Diver opens system . System shows him a list of dive sessions . Diver selects dive session to view details of the dive session . System returns the dive session details [discrete] === Use case: Edit a dive session *MSS* . Diver opens system . System shows him a list of dive sessions . Diver selects dive session to edit . System returns the parameters of the specific dive session . Diver enters the new information of that dive session . System confirms the edit of that dive session. *Extensions* [none] * 5a. The data entered is invalid. (i.e. The diver enters text instead of numeric values for depth.) + [none] ** 5a1. System points to the invalid data entered and asks user to clarify data. + Use case resumes at step 5. [none] * 7b. The user realizes the input is invalid. He enters undo. + [none] ** 7b1. System rolls back the last edit. === Use case: Remove a dive session *MSS* . Diver opens system . System shows him a list of dive sessions . Diver selects the dive session to remove . System confirms the deletion . Diver confirms. . System removes dive session. *Extensions* [none] * 5a. Diver cancels. + [none] ** 5a1. System does not make any changes to current state. + Use case ends here. === Use case: Check current pressure group *MSS* . Diver opens system . System shows him a list of dive sessions . Diver requests system for his current pressure group . System displays his current pressure group, the time needed to the next pressure group, and the time needed for him to reach his desired pressure group as well as the recommended time to his next dive or flight. [appendix] == Non Functional Requirements . Should work on any <> as long as it has Java `9` or higher installed. . Should be able to hold up to 1000 dive sessions without a noticeable sluggishness in performance for typical usage. . Should allow users to select and view dives in addition to the command line. . Should be able to calculate the pressure groups as specified by PADI’s dive table. . Should have a simple tutorial walk through to orientate the users if it is their first time running the application [appendix] == Glossary [[mainstream-os]] Mainstream OS:: Windows, Linux, Unix, OS-X [[private-contact-detail]] Private contact detail:: A contact detail that is not meant to be shared with others [appendix] //tag::product-survey[] == Product Survey A few similar products exist out there. Firstly, one of the team members (Arjo) uses a paper equivalent of such a dive log. This dive log records all the necessary information and provides a user with the basic safety information of the PG being provided as fields. However, the pressure group information must be hand calculated leading to error or negligence. image::paper_notebook.jpg[width=""300""] Linus Torvalds, the benevolent dictator of the linux kernel and mastermind behind git has also created a dive log program. Linus’s program, known as Subsurface, is written in C++ and uses the Qt library allowing for cross-platform usage. image::subsurface_1.png[width=""300""] Subsurface has a comprehensive interface for entering a lot of details. It allows the user to enter things such as the depth, who the dive master was, dive buddy’s name and equipment. It also has a nice satellite map to show where you are planning the dive. The plot on the right hand side illustrates the depth. This includes the so called “safety stop” where the diver allows some of the nitrogen to be released from his bloodstream before surfacing. The plot also is capable of showing a nitrogen profile and a rough estimate of how much oxygen should be kept in reserve for each part of the dive. All of this make it a very complete product with the exception that its initial learning curve is fairly steep. image::subsurface_2.png[width=""300""] When the user first opens the dive log he or she is greeted with this screen, which is not very indicative of what exactly is going on. It takes the user a few attempts to figure out how to add a dive as the add dive is nested very deep inside the menu. It also does not display the pressure group anywhere. This can be confusing for beginner divers as they rely on pressure groups to ensure their own safety. //end::product-survey[] [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 dives. The window size may not be optimum. === A few things to note about dives The aim of this app is to make nitrogen level calculations of a diver very natural. As such testing the app requires certain understanding about dives. The https://github.com/CS2113-AY1819S1-W13-2/main/blob/master/docs/UserGuide.adoc[user guide] outlines the conditions under which dives may be rejected from being added to the system. === Deleting a diveSession . Deleting a diveSession while all dives are listed .. Prerequisites: List all dives using the `list` command. Multiple dives in the list. .. Test case: `delete 1` + Expected: First contact is deleted from the list. Details of the deleted contact shown in the status message. Timestamp in the status bar is updated. .. Test case: `delete 0` + Expected: No diveSession 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) _{give more}_ + Expected: Similar to previous. === Saving data . Dealing with missing/corrupted data files .. Data is stored in the `data/` subdirectory of the current working directory. .. Corrupted data will cause the application to overwrite the file. ",12169,False,2039.665526422685,median "// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // = NetBeans IDEでのGitサポートの使用 :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: NetBeans IDEでのGitサポートの使用 - Apache NetBeans :keywords: Apache NetBeans, Tutorials, NetBeans IDEでのGitサポートの使用 NetBeans IDEはGitバージョン管理クライアントをサポートしています。IDEのGitサポートにより、IDE内のプロジェクトから直接バージョン管理タスクを実行できます。このドキュメントでは、バージョン管理ソフトウェアを使用する場合の標準的なワークフローを説明することによって、IDEの基本的なバージョン管理タスクの実行方法を示します。 Gitは、小さなプロジェクトから非常に大きなプロジェクトまであらゆるものを高速かつ効率的に処理するように設計された、無料かつオープン・ソースの分散バージョン管理システムです。すべてのGitクローンは、ネットワーク・アクセスや中央のサーバーに依存せずに、完全な履歴およびリビジョン・トラック機能を備え、すべてを完備したリポジトリです。分岐やマージの実行は高速で簡単です。Gitはファイルのバージョン管理に使用され、Mercurial、Subversion、CVS、Perforceなどのツールによく似ています。 === 内容 image::images/netbeans-stamp-80-74.png[title=""このページの内容は、NetBeans IDE 7.4および8.0に適用されます""] * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> == 要件 *このチュートリアルを完了するには、次のソフトウェアとリソースが必要です。* |=== |ソフトウェアまたはリソース |必須バージョン |link:https://netbeans.org/downloads/index.html[+NetBeans IDE+] |バージョン7.4または8.0 |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+Java Development Kit+] (JDK) |バージョン7または8 |=== == Gitリポジトリの初期化 まだソース管理されていない既存のファイルからGitリポジトリを初期化するには、次の手順を完了する必要があります。 1. 「プロジェクト」ウィンドウで、バージョン管理されていないプロジェクトを選択し、プロジェクト名を右クリックします。 2. コンテキスト・メニューで「 ``バージョン管理`` 」>「 ``Gitリポジトリの初期化`` 」(または、メイン・メニューの「 ``チーム`` 」>「 ``Git`` 」>「 ``初期化`` 」)を選択します。 [.feature] -- image::images/initialize-git-repo-small.png[role=""left"", link=""images/initialize-git-repo.png""] -- 3. 「 ``Gitリポジトリの初期化`` 」ダイアログ・ボックスで、バージョン管理されるファイルの保存先リポジトリへのパスを指定するか、「参照」をクリックして、必要なディレクトリを参照します。 4. 「OK」をクリックします。 ``.git`` サブフォルダは、上のステップ3で指定したフォルダ(デフォルトでNetBeansプロジェクト・フォルダ)に作成され、プロジェクト・スナップショットのすべてのデータが格納されるGitリポジトリです。Gitは指定されたフォルダ内のすべてのファイルのバージョン管理を開始します。 「 ``ウィンドウ`` 」>「 ``出力`` 」>「 ``出力`` 」を開いて、ローカル作業ディレクトリ下のリポジトリの作成の進捗に関するIDEのレポートを表示できます。 image::images/output-init.png[] すべてのプロジェクト・ファイルが作業ツリーで「 ``追加済み`` 」とマークされます。ファイル・<>を表示するには、「プロジェクト」ウィンドウ内のファイル名の上にカーソルを置きます。次の図に示すように、作業ツリーのファイルのステータスが、斜線の右側に緑で表示されます。 image::images/new-locally.png[] Gitリポジトリの初期化後、Gitリポジトリにファイルを<>するか、または直接それらを<>します。 == Gitリポジトリのクローン 既存のGitリポジトリのコピーを取得するには、それをクローンする必要があります。IDEでリポジトリをクローン・ウィザードを起動する前に、GitリポジトリのURLがわかっていることを確認します。 1. メイン・メニューから「 ``チーム`` 」>「 ``Git`` 」>「 ``クローン`` 」を選択します。リポジトリをクローン・ウィザードが表示されます。 [.feature] -- image::images/clone-wizard-small.png[role=""left"", link=""images/clone-wizard.png""] -- 2. リポジトリ・ページで、Gitリポジトリの場所へのパス、ユーザー名、およびパスワードを指定します(必要に応じて、今後のためにそれらを保存できます)。 3. (オプション)「プロキシ構成」をクリックし、「オプション」ダイアログ・ボックスを表示して、プロキシ・サーバー設定を設定します。終了したら「OK」をクリックします。 4. 「次」をクリックして、ウィザードの次のステップに切り替えます。 5. リモート分岐ページで、ローカル・リポジトリにフェッチ(ダウンロード)するリポジトリ分岐を選択します。「次」をクリックします。 6. 出力先ディレクトリ・ページで、次を指定します。 * 「親ディレクトリ」フィールドでは、ハード・ドライブ上にクローンされるリポジトリ用のディレクトリへのパス(または、「参照」ボタンをクリックし、ディレクトリに移動する)。 「親ディレクトリ」フィールドには、すべてのNetBeansプロジェクトが格納されるデフォルトの ``NetBeansProjects`` ディレクトリへのパスが事前入力されています。 * 「クローン名」フィールドの、元のプロジェクトをクローンするローカル・フォルダの名前。 デフォルトで、「クローン名」には実際のGitリポジトリ名が入力されています。 * 「分岐のチェックアウト」フィールドで、作業ツリーにチェックアウトする分岐を選択します。 * 「リモート名」フィールドの、クローンする元のリポジトリを表す名前。 ``origin`` はクローンするリポジトリのデフォルトのエイリアスです。これは推奨される値です。 * 「クローン後にNetBeansプロジェクトをスキャン」チェックボックスを選択されたままにして、クローンの終了直後に、事後スキャンをアクティブ化します。(プラグインはクローンされたリソースでNetBeansプロジェクトを検索し、見つかったプロジェクトを開くように提案します。) 7. 「終了」をクリックします。 Gitリポジトリのクローン後、ウィザードで選択したフォルダ内にメタデータ ``.git`` フォルダが作成されます。 === SSHプロトコルによるGitHubからのリポジトリのクローン SSHプロトコルによってGitHubからリポジトリをクローンするには、次のように進みます。 *注意:* SSHによってクローンするには、GitHubアカウントを持っており、プロジェクト・メンバーである必要があります。 1. メイン・メニューから「 ``チーム`` 」>「 ``Git`` 」>「 ``クローン`` 」を選択します。リポジトリをクローン・ウィザードが表示されます。 2. リポジトリをクローン・ウィザードのリモート・リポジトリ・ページで、「リポジトリURL」フィールドに、必要なリポジトリへのパス、たとえば ``git@github.com:tstupka/koliba.git`` などを指定します。 3. 「ユーザー名」テキスト・フィールドに ``git`` が指定されていることを確認します。 4. 「秘密/公開鍵」オプションを選択します。 5. (*Gitサーバーへの自動化されたSSHアクセスにSSHエージェントまたはPageantを使用中の場合はスキップします。*)SSH秘密鍵およびパス・フレーズを使用してGitサーバーにアクセスするには次の手順を実行します。 1. 鍵ファイルへのパス、たとえば ``C:\\Users\\key`` などを指定します。 *注意:* OpenSSH秘密鍵形式が必要です。Microsoft Windowsに対応のPuTTYgenで生成された鍵は、IDEを使用する前に、OpenSSH形式に変換する必要があります。 2. 鍵ファイルのパス・フレーズ、たとえば ``abcd`` などを入力します。 3. (オプション)必要に応じて、「パス・フレーズを保存」オプションを選択します。 6. (*Gitサーバーへの自動化されたSSHアクセスにSSHエージェントまたはPageantを使用中の場合に適用されます。*)正しく構成されたSSHエージェントまたはPageant経由でIDEからGitサーバーへの認証されたアクセスを得るには、「秘密鍵ファイル」および「パス・フレーズ」フィールドを空のままにします。 7. (オプション)「プロキシ構成」をクリックし、「オプション」ダイアログ・ボックスを表示して、プロキシ・サーバー設定を設定します。終了したら「OK」をクリックします。 [.feature] -- image::images/github-repo-small.png[role=""left"", link=""images/github-repo.png""] -- 8. 「次」をクリックします。 9. リモート分岐ページで、ローカル・リポジトリにフェッチ(ダウンロード)するリポジトリ分岐、たとえば ``master`` などを選択します。 [.feature] -- image::images/github-branches-small.png[role=""left"", link=""images/github-branches.png""] -- 10. 「次」をクリックします。 11. 出力先ディレクトリ・ページで、次を指定します。 * 「親ディレクトリ」フィールドでは、ハード・ドライブ上にクローンされるリポジトリ用のディレクトリへのパス(または、「参照」ボタンをクリックし、ディレクトリに移動する)。 「親ディレクトリ」フィールドには、すべてのNetBeansプロジェクトが格納されるデフォルトの ``NetBeansProjects`` ディレクトリへのパスが事前入力されています。 * 「クローン名」フィールドの、元のプロジェクトをクローンするローカル・フォルダの名前。 デフォルトで、「クローン名」には実際のGitリポジトリ名が入力されています。 * 「分岐のチェックアウト」フィールドで、作業ツリーにチェックアウトする分岐を選択します。 * 「リモート名」フィールドの、クローンする元のリポジトリを表す名前。 ``origin`` はクローンするリポジトリのデフォルトのエイリアスです。これは推奨される値です。 * 「クローン後にNetBeansプロジェクトをスキャン」チェックボックスを選択されたままにして、クローンの終了直後に、事後スキャンをアクティブ化します。(プラグインはクローンされたリソースでNetBeansプロジェクトを検索し、見つかったプロジェクトを開くように提案します。) [.feature] -- image::images/github-destination-small.png[role=""left"", link=""images/github-destination.png""] -- 12. 「終了」をクリックします。 リポジトリがクローンされると、「クローン完了」メッセージが表示されます。 image::images/clone-completed.png[] 13. 目的のオプションを選択します。 == Gitリポジトリへのファイルの追加 新しいファイルのトラックを開始し、さらに、Gitリポジトリ内のすでにトラックされているファイルへの変更をステージングするには、それをリポジトリに追加する必要があります。 Gitリポジトリにファイルが追加されると、IDEはプロジェクトのスナップショットを作成し、最初に索引に保存します。コミットが実行されると、IDEはそれらのスナップショットをHEADに保存します。IDEでは、次の表に説明する2つのワークフローから選択できます。 |=== |ワークフローの説明 |新規または変更済のファイルを索引に明示的に追加し、索引でステージングされているファイルのみをHEADにコミットします。 |新規または変更済のファイルの索引への追加をスキップし、必要なファイルを直接HEADにコミットします。 |ワークフローに従う手順 | 1. 「プロジェクト」ウィンドウで、追加するファイルを右クリックします。 2. コンテキスト・メニューで「 ``Git`` 」>「 ``追加`` 」を選択します。 これにより、コミットする前に、ファイルの内容が索引に追加されます。 3. 「プロジェクト」ウィンドウで、コミットするファイルを右クリックします。 4. 「コミット」ダイアログ・ボックスで、「HEADと索引間の変更」(image::images/changes-head-index.png[])トグル・ボタンを選択します。 これにより、すでにステージングされているファイルの一覧が表示されます。 5. 下の<>の項で説明するように、ファイルをコミットします。 | 1. 「プロジェクト」ウィンドウで、コミットするファイルを右クリックします。 2. コンテキスト・メニューで、「 ``Git`` 」>「 ``コミット`` 」を選択します。 3. 「コミット」ダイアログ・ボックスで、「索引と作業ツリー間の変更」(image::images/changes-head-wt.png[])トグル・ボタンを選択します。 これにより、ステージングされていないファイルの一覧が表示されます。 4. 下の<>の項で説明するように、ファイルをコミットします。 |=== *注意:* 次の図に示すように、HEAD内のファイルの<>が、斜線の左側に緑で表示されます。 image::images/new.png[] アクションは、フォルダに対して起動した場合に、NetBeans IDEフラット・フォルダ内容構造を順守しながら、再帰的に動作します。 == ファイルの編集 Gitバージョン管理プロジェクトをIDEで開くと、ソースの変更を開始できます。NetBeans IDEで開く任意のプロジェクトと同様に、(「プロジェクト」(Ctrl-1)、「ファイル」(Ctrl-2)、「お気に入り」(Ctrl-3)ウィンドウなどの) IDEのウィンドウで表示されているファイルのノードをダブルクリックすると、ファイルをソース・エディタで開くことができます。 IDEでソース・ファイルを操作する場合、自由に使用できる様々なUIコンポーネントがあります。これらは、表示およびバージョン管理コマンドの操作で役立ちます。 * <> * <> * <> === ソース・エディタでの変更の表示 IDEのソース・エディタでバージョン管理されたファイルを開くと、Gitリポジトリからの基本バージョンに照らしあわせながら、そのファイルに行われた変更がリアル・タイムで表示されます。作業に伴って、IDEはソース・エディタのマージンに色分けを使用し、次の情報を伝えます。 |=== |*青* (     ) |古いリビジョンの後で変更された行を示します。 |*緑* (     ) |古いリビジョンの後で追加された行を示します。 |*赤* (     ) |古いリビジョンの後で除去された行を示します。 |=== ソース・エディタの左側のマージンには、行ごとに発生した変更が表示されています。行を変更すると、その変更がすぐに左側のマージンに表示されます。 image::images/left-margin.png[] *注意:* マージンの色グループをクリックして、バージョン管理コマンドをコールできます。たとえば、下の図は、赤いアイコンをクリックすると使用可能なウィジェットを示しており、ローカル・コピーから行が除去されたことを示します。 image::images/left-widgets.png[] ソース・エディタの右側のマージンには、上から下に向かって、ファイル全体に行われた変更の概要が表示されます。ファイルに変更を行うと、すぐに色分けが生成されます。 image::images/right-margin.png[] *注意*: マージンの特定の場所をクリックすると、インライン・カーソルがファイルのその場所にすぐに移動します。影響を受ける行数を表示するには、右側のマージンの色つきアイコンの上にマウスを動かします。 image::images/right-lines-number.png[] === ファイルのステータス情報の表示 「プロジェクト」(Ctrl-1)、「ファイル」(Ctrl-2)、「お気に入り」(Ctrl-3)または「バージョン管理」ビューで作業する場合、IDEには、ファイルのステータス情報を表示するのに役立つ視覚機能がいくつかあります。次の例では、バッジ(例: image::images/blue-badge.png[])、ファイル名の色、および隣接するステータス・ラベルすべての相互の対応方法を確認し、ファイルに対するバージョン管理情報をトラックする単純だが効果的な方法について説明します。 image::images/file-status.png[] バッジ、色分け、ファイル・ステータス・ラベル、およびおそらく最も重要なGit差分ビューアはすべて、IDEでのバージョン管理情報を効率的に表示し、管理する能力に貢献します。 * <> * <> * <> ==== バッジと色分け バッジはプロジェクト、フォルダおよびパッケージ・ノードに適用され、そのノードに含まれているファイルのステータスを示します。 バッジに使用される色のスキームを次の表に示します。 |=== |UIコンポーネント |説明 |*青のバッジ*(image::images/blue-badge.png[]) |作業ツリー内の変更、追加、または削除されたファイルの存在を示します。パッケージの場合、このバッジは、パッケージ自体にのみ適用され、そのサブパッケージには適用されません。プロジェクトまたはフォルダの場合、このバッジはその項目または含まれるサブフォルダ内の内容の変更を示します。 |*赤のバッジ*(image::images/red-badge.png[]) |_競合する_ファイルを含むプロジェクト、フォルダまたはパッケージをマークします。パッケージの場合、このバッジは、パッケージ自体にのみ適用され、そのサブパッケージには適用されません。プロジェクトまたはフォルダの場合、このバッジはその項目または含まれるサブフォルダ内の競合を示しています。 |=== 色分けは、リポジトリに照らして、現在のステータスを示す目的でファイル名に適用されます。 |=== |色 |例 |説明 |*特定の色なし(黒)* |image::images/black-text.png[] |ファイルに変更がないことを示します。 |*青* |image::images/blue-text.png[] |ファイルがローカルに変更されたことを示します。 |*緑* |image::images/green-text.png[] |ファイルがローカルに追加されたことを示します。 |*赤* |image::images/red-text.png[] |ファイルにマージの競合があることを示します。 |*グレー* |image::images/gray-text.png[] |ファイルがGitによって無視され、バージョン管理コマンド(更新やコミットなど)に含まれないことを示します。ファイルはバージョン管理されている場合、無視できません。 |=== ==== ファイル・ステータス・ラベル IDEはファイルの2つのステータス値を表示します。 * ファイルの作業ツリーと索引状態の相違を示すステータス。 * ファイルの索引状態と現在のHEADコミットの相違を示すステータス。 ファイル・ステータス・ラベルは、バージョン管理ファイルのステータスを、IDEのウィンドウにテキストで示します。 |=== |ステータス・ラベル |意味 |*-* |変更なし |*A* |追加済 |*U* |更新済であるが未マージ |*M* |変更 |*D* |削除済 |*I* |無視 |*R* |名前変更済 |=== デフォルトで、IDEは、ファイルをウィンドウに一覧表示するときに、そのファイルの右側にステータス情報(新規、変更済、無視など)およびフォルダ情報をグレー・テキストで表示します。 image::images/file-labels.png[] マージの競合があるファイルは未マージステータスを示し、一般にユーザーの明示的なアクションによって解決されるまで、赤い色で注釈が付けられます。マージされていないファイルのステータス・ラベルは、シナリオによって異なります(たとえば、 ``A/A`` - 未マージ、両方追加済)。 ファイル・ステータス・ラベルは、メイン・メニューから「 ``表示`` 」>「 ``バージョン・ラベルを表示`` 」を選択して、オンとオフを切り替えできます。 ==== Gitバージョン管理ビュー Gitバージョン管理ビューは、ローカルの作業ツリーの選択されたフォルダ内でファイルに行われた変更のすべてを、リアル・タイムで一覧表示します。これはIDEの下のパネルにデフォルトで開き、追加、削除または変更されたファイルを一覧表示します。 バージョン管理ビューを開くには、(「プロジェクト」ウィンドウ、「ファイル」ウィンドウまたは「お気に入り」ウィンドウなどから)バージョン管理ファイルまたはフォルダを選択し、右クリック・メニューから「 ``Git`` 」>「 ``変更を表示`` 」を選択するか、またはメイン・メニューから「 ``チーム`` 」>「 ``変更を表示`` 」を選択します。IDEの最下部に次のウィンドウが表示されます。 [.feature] -- image::images/versioning-view-small.png[role=""left"", link=""images/versioning-view.png""] -- デフォルトでは、バージョン管理ビューは、作業ツリー内の選択されたパッケージまたはフォルダ内の変更されたすべてのファイルを一覧表示します。ツールバーのボタンを使用して、索引とHEAD、作業ツリーと索引、または作業ツリーとHEAD間で相違があるファイルの一覧を表示するように選択できます。一覧表示されたファイルの上にある列の見出しをクリックして、名前、ステータス、または場所でファイルをソートすることもできます。 「バージョン管理」ビューのツールバーには、一覧に表示されているすべてのファイルに対して一般的なGitタスクを呼び出すことができるボタンも用意されています。次の表は、「バージョン管理」ビューのツールバーにあるGitコマンドをまとめています。 |=== |アイコン |名前 |機能 |image::images/changes-head-wt.png[] |*HEADと作業ツリー間の変更* |すでにステージングされているか、変更または作成のみされていて、まだステージングされていないファイルの一覧を表示します。 |image::images/changes-head-index.png[] |*HEADと索引間の変更* |ステージングされているファイルの一覧を表示します。 |image::images/changes-index-wt.png[] |*索引と作業ツリー間の変更* |ステージング済の状態と作業ツリーの状態に相違があるファイルを表示します。 |image::images/refresh.png[] |*ステータスのリフレッシュ* |選択したファイルとフォルダのステータスをリフレッシュします。「バージョン管理」ビューに表示されたファイルは、外部で行われた可能性のある任意の変更を反映してリフレッシュできます。 |image::images/open-diff.png[] |*差分を開く* |差分ビューアを開くと、ローカルのコピーとリポジトリで保持されているバージョンを並べた比較が表示されます。 |image::images/update.png[] |*変更内容を元に戻す* |「<>」ダイアログ・ボックスを表示します。 |image::images/commit-button.png[] |*変更をコミット* |「<>」ダイアログ・ボックスを表示します。 |=== 「バージョン管理」ビューで、変更したファイルに対応する表の行を選択し、右クリック・メニューからコマンドを選択すると、他のGitコマンドにアクセスできます。 [.feature] -- image::images/versioning-right-click-small.png[role=""left"", link=""images/versioning-right-click.png""] -- === ファイル・リビジョンの比較 ファイル・バージョンの比較は、バージョン管理されているプロジェクトでの作業で共通のタスクです。IDEでは、「差分」コマンドを使用して、リビジョンを比較できます。 *注意:* 複数の比較モード(「HEADとの差分」、「トラック済との差分」、「差分の対象」)がIDEで使用可能です。 1. バージョン管理されたファイルまたはフォルダを選択します(「 ``プロジェクト`` 」、「 ``ファイル`` 」、「 ``お気に入り`` 」ウィンドウなどから)。 2. メイン・メニューから「 ``チーム`` 」>「 ``差分`` 」>「 ``HEADとの差分`` 」を選択します。 選択したファイルとリビジョンについてグラフィカルな差分ビューアがIDEのメイン・ウィンドウで開きます。差分ビューアには2つのコピーが並んだパネルに表示されます。右側により現在に近いコピーが表示されるため、作業ツリーに対してリポジトリ・リビジョンを比較すると、右パネルに作業ツリーが表示されます。 [.feature] -- image::images/diff-viewer-small.png[role=""left"", link=""images/diff-viewer.png""] -- 差分ビューアは、バージョン管理の変更を表示する場所に使用されているのと同じ<>を利用します。前に表示したスクリーン・ショットの緑色のブロックは、より現在に近いリビジョンに追加された内容を示します。赤いブロックは、前のリビジョンの内容が、より最近のリビジョンから除去されたことを示します。青は、強調表示された行で変更が発生したことを示します。 *注意:* 他のリビジョンは、差分ビューア・ツールバーの下の「 ``差分`` 」および「 ``送信先`` 」ドロップダウン・リストから選択できます。 差分ビューアのツールバーには、一覧に表示されているすべてのファイルに対して一般的なGitタスクを呼び出すことができるボタンも用意されています。次の表は、差分ビューアのツールバーにあるGitコマンドをまとめています。 |=== |アイコン |名前 |機能 |image::images/changes-head-wt.png[] |*HEADと作業ツリー間の変更* |すでにステージングされているか、変更または作成のみされていて、まだステージングされていないファイルの一覧を表示します。 |image::images/changes-head-index.png[] |*HEADと索引間の変更* |ステージングされているファイルの一覧を表示します。 |image::images/changes-index-wt.png[] |*索引と作業ツリー間の変更* |ステージング済の状態と作業ツリーの状態に相違があるファイルを表示します。 |image::images/nextdiff.png[] |*次の差分へ* |ファイル内の次の差分を表示します。 |image::images/prevdiff.png[] |*前の差分へ* |ファイル内の前の差分を表示します。 |image::images/refresh.png[] |*ステータスのリフレッシュ* |選択したファイルとフォルダのステータスをリフレッシュします。「バージョン管理」ウィンドウに表示されたファイルは、外部で行われた可能性のある任意の変更を反映してリフレッシュできます。 |image::images/update.png[] |*変更内容を元に戻す* |「<>」ダイアログ・ボックスを表示します。 |image::images/commit-button.png[] |*変更をコミット* |「<>」ダイアログ・ボックスを表示します。 |=== 作業ツリー内のローカル・コピーで差分の取得を実行する場合、IDEの差分ビューア内から直接変更を行うことができます。これを行うには、カーソルを差分ビューアの右ペインに置き、それに従ってファイルを変更するか、または強調表示された各変更の前後で表示されるインライン・アイコンを使用します。 |=== |アイコン |名前 |機能 |image::images/insert.png[] |*置換* |強調表示されたテキストを作業ツリー・コピーに挿入します。 |image::images/arrow.png[] |*すべて移動* |ローカル作業ツリー・コピー全体を元に戻します。 |image::images/remove.png[] |*除去* |ローカル作業ツリー・コピーから強調表示されたテキストを除去します。 |=== === 変更を元に戻す 作業ツリー内の選択したファイルに行ったローカルの変更をスローし、それらのファイルを索引またはHEAD内のファイルで置き換えるには、次を実行します。 1. バージョン管理されたファイルまたはフォルダを選択します(「 ``プロジェクト`` 」、「 ``ファイル`` 」、「 ``お気に入り`` 」ウィンドウなどから)。 2. メイン・メニューから「 ``チーム`` 」>「 ``変更内容を元に戻す`` 」を選択します。 「 ``変更内容を元に戻す`` 」ダイアログ・ボックスが表示されます。 image::images/revert.png[] 3. 追加のオプション(「 ``索引のコミットされていない変更のみをHEADに戻す`` 」など)を指定します。 4. 「元に戻す」をクリックします。 IDEによって、選択したファイルが上の<>で指定したファイルで置き換えられます。 == リポジトリへのソースのコミット ファイルをGitリポジトリにコミットするには、次を実行します。 1. 「 ``プロジェクト`` 」ウィンドウで、コミットするファイルを右クリックします。 2. コンテキスト・メニューで、「 ``Git`` 」>「 ``コミット`` 」を選択します。 「 ``コミット`` 」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/commit-small.png[role=""left"", link=""images/commit.png""] -- 「 ``コミット`` 」ダイアログ・ボックスには次のコンポーネントが含まれます。 * コミットされる変更を説明するための「 ``コミット・メッセージ`` 」テキスト領域 * 必要に応じて、変更を行ったユーザーと物理的にファイルをコミットしたユーザーを区別できる「 ``作成者`` 」および「 ``コミッタ`` 」ドロップダウン・リスト。 * 「 ``コミットするファイル`` 」セクションには、次が表示されます。 * 変更されたすべてのファイル * 作業ツリーで(ローカルで)削除されたすべてのファイル * すべての新規ファイル(Gitリポジトリにまだ存在しないファイル) * 名前を変更したすべてのファイル。 実際のコミットが実行されるモードを切り替える2つのトグル・ボタンがここで利用できます。 |=== |UIコンポーネント |名前 |説明 |image::images/changes-head-index.png[] |*HEADと索引間の変更* |ステージングされているファイルの一覧を表示します。 |image::images/changes-head-wt.png[] |*HEADと作業ツリー間の変更* |すでにステージングされているか、変更または作成のみされていて、まだステージングされていないファイルの一覧を表示します。 |=== *注意*: ここで、コミットから個々のファイルを除外するかどうかを指定するには、「 ``コミット`` 」という最初の列のチェックボックスを選択解除するか、「 ``コミット・アクション`` 」列のファイル行を右クリックし、ポップアップ・メニューから「 ``コミットから除外`` 」を選択します。ここで差分ビューアを表示するには、「 ``コミット・アクション`` 」列のファイル行を右クリックし、ポップアップ・メニューから「 ``差分`` 」を選択します。 * コミットされる変更に関する問題をトラックするための「 ``問題を更新`` 」セクション。 *注意*: IDEで問題のトラックを開始するには、JIRAまたはSubversionプラグインをインストールする必要があります。 3. 「 ``コミット・メッセージ`` 」テキスト領域にコミット・メッセージを入力します。または、次のいずれかを実行できます。 * 右上隅にある「 ``最近のメッセージ`` 」(image::images/recent-msgs.png[])アイコンをクリックして、以前使用したメッセージのリストを表示して選択します。 * 右上隅にある「 ``テンプレートをロード`` 」(image::images/msg-template.png[])アイコンをクリックして、メッセージ・テンプレートを選択します。 4. 個々のファイルのアクションを指定して「 ``コミット`` 」をクリックします。 IDEによってコミットが実行され、スナップショットがリポジトリに保存されます。コミット・アクションが実行されると、インタフェースの右下にあるIDEのステータス・バーが表示されます。コミットに成功すると、「 ``プロジェクト`` 」、「 ``ファイル`` 」および「 ``お気に入り`` 」ウィンドウのバージョン管理バッジが消え、コミットされたファイルの色分けが黒に戻ります。 == 分岐の操作 IDEのGitサポートでは、分岐を使用して、コード・ベース全体の様々なバージョンを管理できます。 IDEで分岐を操作する場合、次のアクションがサポートされます。 * <> * <> * <> * <> === 分岐の作成 メイン・トランクを妨げずに、安定化や実験の目的で、別個のバージョンのファイル・システムを操作する場合に、ローカル分岐を作成するには、次の完了を実行します。 1. 「プロジェクト」または「ファイル」ウィンドウで、分岐を作成するリポジトリからプロジェクトまたはフォルダを選択します。 2. メイン・メニューで「チーム」>「分岐/タグ」>「分岐の作成」を選択します。 *注意:* または、バージョン管理されたプロジェクトまたはフォルダを右クリックし、ポップアップ・メニューから「Git」>「分岐/タグ」>「分岐の作成」を選択します。 「分岐の作成」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/create-branch-small.png[role=""left"", link=""images/create-branch.png""] -- 3. 「分岐名」フィールドで、作成する分岐の名前を入力します。 4. コミットID、既存の分岐、またはタグ名を「リビジョン」フィールドに入力して、選択した項目の特定のリビジョンを入力するか、「選択」を押して、リポジトリで管理されているリビジョンの一覧を表示します。 5. (オプション)「リビジョンを選択」ダイアログ・ボックスで、「分岐」を展開し、必要な分岐を選択して、隣接する一覧のコミットIDを指定し、「選択」を押します。 6. 分岐させるリビジョンに固有の「コミットID」、「作成者」、「メッセージ」フィールドの情報を確認して、「作成」をクリックします。 分岐がGitリポジトリの ``「分岐」/「ローカル」`` フォルダに追加されます。 [.feature] -- image::images/branch-added-small.png[role=""left"", link=""images/branch-added.png""] -- === チェックアウト すでに存在する分岐上のファイルを編集する必要がある場合は、分岐をチェックアウトすることによって、ファイルを作業ツリーにコピーできます。 リビジョンをチェックアウトするには、次を実行します。 1. メイン・メニューから「チーム」>「チェックアウト」>「リビジョンのチェックアウト」を選択します。 「選択されたリビジョンをチェックアウト」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/chkout-rev-small.png[role=""left"", link=""images/chkout-rev.png""] -- 2. コミットID、既存の分岐またはタグ名を「リビジョン」フィールドに入力して、必要なリビジョンを指定するか、「選択」を押して、リポジトリで管理されているリビジョンの一覧を表示します。 3. 前のステップで「選択」を押さなかった場合、スキップします。「リビジョンを選択」ダイアログ・ボックスで、「分岐」を展開し、必要な分岐を選択して、必要に応じて、隣接する一覧のコミットIDを指定し、「選択」を押します。 *注意:* 指定したリビジョンが分岐名でマークされていない有効なコミットを表している場合、HEADがデタッチされ、分岐上にいなくなります。 4. チェックアウトされるリビジョンに固有の「コミットID」、「作成者」、「メッセージ」フィールド情報を確認します。 5. チェックアウトしたリビジョンから新しい分岐を作成するには、「新しい分岐としてチェックアウト」オプションを選択し、「分岐名」フィールドに名前を入力します。 6. 「チェックアウト」を押して、リビジョンをチェックアウトします。 作業ツリーおよび索引内のファイルが、指定したリビジョンのバージョンに一致するように更新されます。 *注意:* すでに存在する分岐(いずれかの分岐の一番上にないコミットなど)にファイルを切り替える場合、「チーム」>「Git」>「分岐」>「分岐に切替え」コマンドを使用し、「選択された分岐に切替え」ダイアログ・ボックスで分岐を指定して、(オプションで)新しい分岐としてチェックアウトし、「切替え」を押します。 IDEは、IDEで現在選択されているファイル、フォルダまたはプロジェクトの状況に応じたチェックアウトをサポートしています。索引から、一部のファイル(分岐ではなく)をチェックアウトするには、次の手順を完了します。 1. メイン・メニューから「チーム」>「チェックアウト」>「ファイルのチェックアウト」を選択します。 「選択されたパスをチェックアウト」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/chkout-path-small.png[role=""left"", link=""images/chkout-path.png""] -- 2. 「選択されたリビジョンからのエントリで索引を更新」オプションを選択します。 選択した場合、チェックアウト前に選択したリビジョンの状態で索引が更新されます(作業ツリーと索引の両方の選択したファイルが更新されます)。 3. コミットID、既存の分岐またはタグ名を「リビジョン」フィールドに入力して、必要なリビジョンを指定するか、「選択」を押して、リポジトリで管理されているリビジョンの一覧を表示します。 4. 前のステップで「選択」を押さなかった場合、スキップします。「リビジョンを選択」ダイアログ・ボックスで、「分岐」を展開し、必要な分岐を選択して、必要に応じて、隣接する一覧のリビジョン番号を指定し、「選択」を押します。 5. 「チェックアウト」を押して、チェックアウトを完了します。 === マージ リポジトリ・リビジョンから変更を作業ツリーに移行するには、次のように実行します。 1. メイン・メニューから「チーム」>「分岐/タグ」>「リビジョンをマージ」を選択します。 「リビジョンをマージ」ダイアログ・ボックスが表示されます。 [.feature] -- image::images/merge-small.png[role=""left"", link=""images/merge.png""] -- 2. コミットID、既存の分岐またはタグ名を「リビジョン」フィールドに入力して、必要なリビジョンを指定するか、「選択」を押して、リポジトリで管理されているリビジョンの一覧を表示します。 3. 前のステップで「選択」を押さなかった場合、スキップします。「リビジョンを選択」ダイアログ・ボックスで、「分岐」を展開し、必要な分岐を選択して、必要に応じて、隣接する一覧のコミットIDを指定し、「選択」を押します。 4. 「マージ」を押します。 現在の分岐、作業ツリーの内容、指定した分岐間の3方向のマージが実行されます。 *注意:* マージの競合が発生した場合、競合するファイルが<>でマークされ、競合が示されます。 *注意:* マージ後、変更をHEADに追加するために、変更を<>する必要があります。 === 分岐の削除 不要なローカル分岐を削除するには、次の手順を完了します。 1. メイン・メニューから「チーム」>「リポジトリ・ブラウザ」を選択します。 2. Gitリポジトリ・ブラウザで、削除する分岐を選択します。 *注意:* 分岐は非アクティブである、つまり現在作業ツリーにチェックアウトされていない必要があります。 3. 選択した分岐を右クリックし、ポップアップ・メニューから「分岐を削除」を選択します。 4. 「分岐を削除」ダイアログ・ボックスで、「OK」を押して、分岐の削除を確認します。 分岐がローカル・リポジトリとGitリポジトリ・ブラウザから除去されます。 == リモート・リポジトリの操作 他の開発者と協力する場合、作業を共有する必要があり、これには、インターネットまたはネットワーク上でホストされるリモート・リポジトリとのデータのフェッチ、プッシュ、プルが含まれます。 * <> * <> * <> === フェッチ フェッチは、元のリモート・リポジトリからまだ持っていない変更を取得します。これは、ローカル分岐を変更しません。フェッチはリモート・リポジトリからすべての分岐を取得し、いつでも分岐にマージしたり、単に検査したりすることができます。 更新をフェッチするには、次のように実行します。 1. 「チーム」>「リモート」>「フェッチ」を選択します。 「リモート・リポジトリからフェッチ」ウィザードが表示されます。 [.feature] -- image::images/fetch-small.png[role=""left"", link=""images/fetch.png""] -- 2. ウィザードのリモート・リポジトリ・ページで、構成済のリポジトリ(以前に構成されたリポジトリへのパスを使用する)または「Gitリポジトリの場所を指定」オプション(必要に応じて、まだアクセスされていないリモート・リポジトリへのパス、その名前、ログイン、パスワード、およびプロキシ構成を定義する)を選択し、「次」をクリックします。 3. ウィザードのリモート分岐ページで、変更をフェッチする分岐を選択し、「終了」をクリックします。 リモート分岐のローカル・コピーが作成されます。Gitリポジトリ・ブラウザの「 ``分岐`` 」>「 ``リモート`` 」ディレクトリで、選択した分岐が更新されます。 次に、フェッチした更新をローカル分岐にマージできます。 === プル リモートGitリポジトリから更新をプルすると、リポジトリから変更がフェッチされ、ローカル・リポジトリの現在のHEADにマージされます。 プルを実行するには、次の手順を完了します。 1. 「チーム」>「リモート」>「プル」を選択します。 リモート・リポジトリからプル・ウィザードが表示されます。 [.feature] -- image::images/pull-small.png[role=""left"", link=""images/pull.png""] -- 2. ウィザードのリモート・リポジトリ・ページで、構成済のリポジトリ(以前に構成されたリポジトリへのパスを使用する)または「Gitリポジトリの場所を指定」オプション(必要に応じて、まだアクセスされていないリモート・リポジトリへのパス、その名前、ログインとパスワードを定義する)を選択し、「次」をクリックします。 3. ウィザードのリモート分岐ページで、変更がプルされる分岐を選択し、「終了」をクリックします。 ローカル・リポジトリが元のリポジトリと同期されます。 === プッシュ ローカルGitリポジトリの変更を公開Gitリポジトリに貢献するには、次の手順を実行します。 1. 「チーム」>「リモート」>「プッシュ」を選択します。 リモート・リポジトリへプッシュ・ウィザードが表示されます。 [.feature] -- image::images/push-small.png[role=""left"", link=""images/push.png""] -- 2. ウィザードのリモート・リポジトリ・ページで、構成済のリポジトリ(以前に構成されたリポジトリへのパスを使用する)または「Gitリポジトリの場所を指定」オプション(必要に応じて、まだアクセスされていないリモート・リポジトリへのパス、その名前、ログインとパスワードを定義する)を選択し、「次」をクリックします。 3. ローカル分岐を選択ページで、編集をプッシュする分岐を選択し、「次」をクリックします。 4. ローカル参照を更新ページで、ローカル・リポジトリの「リモート」ディレクトリ内の更新する分岐を選択し、「終了」をクリックします。 指定したリモート・リポジトリの分岐がローカル分岐の最新の状態で更新されます。 == サマリー このチュートリアルでは、IDEのGitサポートを使用する場合の標準的なワークフローを説明することによって、IDEの基本的なバージョン管理タスクの実行方法を示しました。IDEに含まれるGit固有の機能の一部を紹介しながら、バージョン管理されたプロジェクトの設定とバージョン管理されたファイルの基本タスクの実行方法を示しました。 link:/about/contact_form.html?to=3&subject=Feedback:%20Using%20Git%20Support%20in%20NetBeans%20IDE[+このチュートリアルに関するご意見をお寄せください+] == 関連項目 関連する資料については、次のドキュメントを参照してください。 * link:clearcase.html[+NetBeans IDEでのClearCaseサポートの使用+] * link:subversion.html[+NetBeans IDEでのSubversionサポートの使用+] * link:mercurial.html[+NetBeans IDEでのMercurialサポートの使用+] * link:cvs.html[+NetBeans IDEでのCVSサポートの使用+] * link:http://www.oracle.com/pls/topic/lookup?ctx=nb8000&id=NBDAG234[+NetBeans IDEによるアプリケーションの開発+]の_バージョン管理によるアプリケーションのバージョニング_ ",12221,True,2523.442616761463,median "// Copyright 2018 The Fuchsia 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/developer/debug/debug_agent/arch_arm64_helpers.h"" #include #include #include ""src/developer/debug/debug_agent/arch_arm64_helpers_unittest.h"" #include ""src/developer/debug/debug_agent/test_utils.h"" #include ""src/developer/debug/ipc/register_test_support.h"" #include ""src/developer/debug/shared/logging/file_line_function.h"" #include ""src/developer/debug/shared/zx_status.h"" #include ""src/lib/fxl/arraysize.h"" namespace debug_agent { namespace arch { namespace { constexpr uint64_t kDbgbvrE = 1u; zx_thread_state_debug_regs_t GetDefaultRegs() { zx_thread_state_debug_regs_t debug_regs = {}; debug_regs.hw_bps_count = 4; return debug_regs; } void SetupHWBreakpointTest(debug_ipc::FileLineFunction file_line, zx_thread_state_debug_regs_t* debug_regs, uint64_t address, zx_status_t expected_result) { zx_status_t result = SetupHWBreakpoint(address, debug_regs); ASSERT_EQ(result, expected_result) << ""["" << file_line.ToString() << ""] "" << ""Got: "" << debug_ipc::ZxStatusToString(result) << "", expected: "" << debug_ipc::ZxStatusToString(expected_result); } void RemoveHWBreakpointTest(debug_ipc::FileLineFunction file_line, zx_thread_state_debug_regs_t* debug_regs, uint64_t address, zx_status_t expected_result) { zx_status_t result = RemoveHWBreakpoint(address, debug_regs); ASSERT_EQ(result, expected_result) << ""["" << file_line.ToString() << ""] "" << ""Got: "" << debug_ipc::ZxStatusToString(result) << "", expected: "" << debug_ipc::ZxStatusToString(expected_result); } // Always aligned address. constexpr uint64_t kAddress1 = 0x10000; constexpr uint64_t kAddress2 = 0x20000; constexpr uint64_t kAddress3 = 0x30000; constexpr uint64_t kAddress4 = 0x40000; constexpr uint64_t kAddress5 = 0x50000; TEST(arm64Helpers, SettingBreakpoints) { auto debug_regs = GetDefaultRegs(); SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); for (size_t i = 1; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } // Adding the same breakpoint should detect that the same already exists. SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); for (size_t i = 1; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } // Continuing adding should append. SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress2, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); for (size_t i = 2; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress3); for (size_t i = 3; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress4, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress3); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } // No more registers left should not change anything. SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress5, ZX_ERR_NO_RESOURCES); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress3); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } } TEST(arm64Helpers, Removing) { auto debug_regs = GetDefaultRegs(); // Previous state verifies the state of this calls. SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK); SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress2, ZX_OK); SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_OK); SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress4, ZX_OK); SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress5, ZX_ERR_NO_RESOURCES); RemoveHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } // Removing same breakpoint should not work. RemoveHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_ERR_OUT_OF_RANGE); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } // Removing an unknown address should warn and change nothing. RemoveHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, 0xaaaaaaa, ZX_ERR_OUT_OF_RANGE); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } RemoveHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, 0u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } // Adding again should work. SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress5, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, 0u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress1, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } // Already exists should not change anything. SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress5, ZX_OK); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_ERR_NO_RESOURCES); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } // No more registers. SetupHWBreakpointTest(FROM_HERE_NO_FUNC, &debug_regs, kAddress3, ZX_ERR_NO_RESOURCES); EXPECT_EQ(debug_regs.hw_bps[0].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[0].dbgbvr, kAddress5); EXPECT_EQ(debug_regs.hw_bps[1].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[1].dbgbvr, kAddress2); EXPECT_EQ(debug_regs.hw_bps[2].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[2].dbgbvr, kAddress1); EXPECT_EQ(debug_regs.hw_bps[3].dbgbcr & kDbgbvrE, 1u); EXPECT_EQ(debug_regs.hw_bps[3].dbgbvr, kAddress4); for (size_t i = 4; i < arraysize(debug_regs.hw_bps); i++) { EXPECT_EQ(debug_regs.hw_bps[i].dbgbcr & kDbgbvrE, 0u); EXPECT_EQ(debug_regs.hw_bps[i].dbgbvr, 0u); } } TEST(ArmHelpers, WriteGeneralRegs) { std::vector regs; regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_x0, 8)); regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_x3, 8)); regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_lr, 8)); regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_pc, 8)); zx_thread_state_general_regs_t out = {}; zx_status_t res = WriteGeneralRegisters(regs, &out); ASSERT_EQ(res, ZX_OK) << ""Expected ZX_OK, got "" << debug_ipc::ZxStatusToString(res); EXPECT_EQ(out.r[0], 0x0102030405060708u); EXPECT_EQ(out.r[1], 0u); EXPECT_EQ(out.r[2], 0u); EXPECT_EQ(out.r[3], 0x0102030405060708u); EXPECT_EQ(out.r[4], 0u); EXPECT_EQ(out.r[29], 0u); EXPECT_EQ(out.lr, 0x0102030405060708u); EXPECT_EQ(out.pc, 0x0102030405060708u); regs.clear(); regs.push_back(CreateUint64Register(debug_ipc::RegisterID::kARMv8_x0, 0xaabb)); regs.push_back(CreateUint64Register(debug_ipc::RegisterID::kARMv8_x15, 0xdead)); regs.push_back(CreateUint64Register(debug_ipc::RegisterID::kARMv8_pc, 0xbeef)); res = WriteGeneralRegisters(regs, &out); ASSERT_EQ(res, ZX_OK) << ""Expected ZX_OK, got "" << debug_ipc::ZxStatusToString(res); EXPECT_EQ(out.r[0], 0xaabbu); EXPECT_EQ(out.r[1], 0u); EXPECT_EQ(out.r[15], 0xdeadu); EXPECT_EQ(out.r[29], 0u); EXPECT_EQ(out.lr, 0x0102030405060708u); EXPECT_EQ(out.pc, 0xbeefu); } TEST(ArmHelpers, InvalidWriteGeneralRegs) { zx_thread_state_general_regs_t out; std::vector regs; // Invalid length. regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_v0, 4)); EXPECT_EQ(WriteGeneralRegisters(regs, &out), ZX_ERR_INVALID_ARGS); // Invalid (non-canonical) register. regs.push_back(CreateRegisterWithData(debug_ipc::RegisterID::kARMv8_w3, 8)); EXPECT_EQ(WriteGeneralRegisters(regs, &out), ZX_ERR_INVALID_ARGS); } TEST(ArmHelpers, WriteVectorRegs) { std::vector regs; std::vector v0_value; v0_value.resize(16); v0_value.front() = 0x42; v0_value.back() = 0x12; regs.emplace_back(debug_ipc::RegisterID::kARMv8_v0, v0_value); std::vector v31_value = v0_value; v31_value.front()++; v31_value.back()++; regs.emplace_back(debug_ipc::RegisterID::kARMv8_v31, v31_value); regs.emplace_back(debug_ipc::RegisterID::kARMv8_fpcr, std::vector{5, 6, 7, 8}); regs.emplace_back(debug_ipc::RegisterID::kARMv8_fpsr, std::vector{9, 0, 1, 2}); zx_thread_state_vector_regs_t out = {}; zx_status_t res = WriteVectorRegisters(regs, &out); ASSERT_EQ(res, ZX_OK) << ""Expected ZX_OK, got "" << debug_ipc::ZxStatusToString(res); EXPECT_EQ(out.v[0].low, 0x0000000000000042u); EXPECT_EQ(out.v[0].high, 0x1200000000000000u); EXPECT_EQ(out.v[31].low, 0x0000000000000043u); EXPECT_EQ(out.v[31].high, 0x1300000000000000u); EXPECT_EQ(out.fpcr, 0x08070605u); EXPECT_EQ(out.fpsr, 0x02010009u); } TEST(ArmHelpers, WriteDebugRegs) { std::vector regs; regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbcr0_el1, std::vector{1, 2, 3, 4}); regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbcr1_el1, std::vector{2, 3, 4, 5}); regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbcr15_el1, std::vector{3, 4, 5, 6}); regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbvr0_el1, std::vector{4, 5, 6, 7, 8, 9, 0, 1}); regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbvr1_el1, std::vector{5, 6, 7, 8, 9, 0, 1, 2}); regs.emplace_back(debug_ipc::RegisterID::kARMv8_dbgbvr15_el1, std::vector{6, 7, 8, 9, 0, 1, 2, 3}); // TODO(bug 40992) Add ARM64 hardware watchpoint registers here. zx_thread_state_debug_regs_t out = {}; zx_status_t res = WriteDebugRegisters(regs, &out); ASSERT_EQ(res, ZX_OK) << ""Expected ZX_OK, got "" << debug_ipc::ZxStatusToString(res); EXPECT_EQ(out.hw_bps[0].dbgbcr, 0x04030201u); EXPECT_EQ(out.hw_bps[1].dbgbcr, 0x05040302u); EXPECT_EQ(out.hw_bps[15].dbgbcr, 0x06050403u); EXPECT_EQ(out.hw_bps[0].dbgbvr, 0x0100090807060504u); EXPECT_EQ(out.hw_bps[1].dbgbvr, 0x0201000908070605u); EXPECT_EQ(out.hw_bps[15].dbgbvr, 0x0302010009080706u); } // Watchpoint Tests -------------------------------------------------------------------------------- // Tests ------------------------------------------------------------------------------------------- TEST(ArmHelpers_SetupWatchpoint, SetupMany) { zx_thread_state_debug_regs regs = {}; ASSERT_TRUE(Check(®s, kAddress1, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {kAddress1, kAddress1 + 1}, 0), 0x1)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, 0, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0})); EXPECT_TRUE(CheckLengths(regs, {1, 0, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0})); ASSERT_TRUE(Check(®s, kAddress1, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_ALREADY_BOUND))); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, 0, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0})); EXPECT_TRUE(CheckLengths(regs, {1, 0, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0})); ASSERT_TRUE(Check(®s, kAddress2, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {kAddress2, kAddress2 + 2}, 1), 0x3)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 0})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, 0, 0})); ASSERT_TRUE(Check(®s, kAddress3, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {kAddress3, kAddress3 + 4}, 2), 0xf)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 0})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, 0})); ASSERT_TRUE(Check(®s, kAddress4, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {kAddress4, kAddress4 + 8}, 3), 0xff)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite})); ASSERT_TRUE(Check(®s, kAddress5, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_NO_RESOURCES))); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {kAddress3, kAddress3 + 4}, kWatchpointCount), ZX_OK); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, 0, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 0, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, 0, kWrite})); ASSERT_TRUE(Check(®s, kAddress5, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {kAddress5, kAddress5 + 8}, 2), 0xff)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress5, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 8, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {kAddress3, kAddress3 + 4}, kWatchpointCount), ZX_ERR_NOT_FOUND); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress5, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 8, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite})); } TEST(ArmHelpers_SetupWatchpoint, Ranges) { zx_thread_state_debug_regs_t regs = {}; // 1-byte alignment. ASSERT_TRUE(ResetCheck(®s, 0x1000, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1000, 0x1001}, 0), 0b00000001)); ASSERT_TRUE(ResetCheck(®s, 0x1001, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1001, 0x1002}, 0), 0b00000010)); ASSERT_TRUE(ResetCheck(®s, 0x1002, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1002, 0x1003}, 0), 0b00000100)); ASSERT_TRUE(ResetCheck(®s, 0x1003, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1003, 0x1004}, 0), 0b00001000)); ASSERT_TRUE(ResetCheck(®s, 0x1004, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1004, 0x1005}, 0), 0b00000001)); ASSERT_TRUE(ResetCheck(®s, 0x1005, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1005, 0x1006}, 0), 0b00000010)); ASSERT_TRUE(ResetCheck(®s, 0x1006, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1006, 0x1007}, 0), 0b00000100)); ASSERT_TRUE(ResetCheck(®s, 0x1007, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1007, 0x1008}, 0), 0b00001000)); ASSERT_TRUE(ResetCheck(®s, 0x1008, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1008, 0x1009}, 0), 0b00000001)); ASSERT_TRUE(ResetCheck(®s, 0x1009, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1009, 0x100a}, 0), 0b00000010)); ASSERT_TRUE(ResetCheck(®s, 0x100a, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100a, 0x100b}, 0), 0b00000100)); ASSERT_TRUE(ResetCheck(®s, 0x100b, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100b, 0x100c}, 0), 0b00001000)); ASSERT_TRUE(ResetCheck(®s, 0x100c, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100c, 0x100d}, 0), 0b00000001)); ASSERT_TRUE(ResetCheck(®s, 0x100d, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100d, 0x100e}, 0), 0b00000010)); ASSERT_TRUE(ResetCheck(®s, 0x100e, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100e, 0x100f}, 0), 0b00000100)); ASSERT_TRUE(ResetCheck(®s, 0x100f, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100f, 0x1010}, 0), 0b00001000)); ASSERT_TRUE(ResetCheck(®s, 0x1010, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1010, 0x1011}, 0), 0b00000001)); // 2-byte alignment. ASSERT_TRUE(ResetCheck(®s, 0x1000, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1000, 0x1002}, 0), 0b00000011)); ASSERT_TRUE(ResetCheck(®s, 0x1001, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1002, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1002, 0x1004}, 0), 0b00001100)); ASSERT_TRUE(ResetCheck(®s, 0x1003, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1004, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1004, 0x1006}, 0), 0b00000011)); ASSERT_TRUE(ResetCheck(®s, 0x1005, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1006, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1006, 0x1008}, 0), 0b00001100)); ASSERT_TRUE(ResetCheck(®s, 0x1007, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1008, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1008, 0x100a}, 0), 0b00000011)); ASSERT_TRUE(ResetCheck(®s, 0x1009, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100a, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100a, 0x100c}, 0), 0b00001100)); ASSERT_TRUE(ResetCheck(®s, 0x100b, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100c, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100c, 0x100e}, 0), 0b00000011)); ASSERT_TRUE(ResetCheck(®s, 0x100d, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100e, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100e, 0x1010}, 0), 0b00001100)); ASSERT_TRUE(ResetCheck(®s, 0x100f, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1010, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1010, 0x1012}, 0), 0b00000011)); // 3-byte alignment. ASSERT_TRUE(ResetCheck(®s, 0x1000, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1001, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1002, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1003, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1004, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1005, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1006, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1007, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1008, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1009, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100a, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100b, 3, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); // 4 byte range. ASSERT_TRUE(ResetCheck(®s, 0x1000, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1000, 0x1004}, 0), 0x0f)); ASSERT_TRUE(ResetCheck(®s, 0x1001, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1002, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1003, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1004, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1004, 0x1008}, 0), 0x0f)); ASSERT_TRUE(ResetCheck(®s, 0x1005, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1006, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1007, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1008, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1008, 0x100c}, 0), 0x0f)); ASSERT_TRUE(ResetCheck(®s, 0x1009, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100a, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100b, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100c, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100c, 0x1010}, 0), 0x0f)); // 5 byte range. ASSERT_TRUE(ResetCheck(®s, 0x1000, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1001, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1002, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1003, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1004, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1005, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1006, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1007, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1008, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1009, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100a, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100b, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100c, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100d, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100e, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100f, 5, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); // 6 byte range. ASSERT_TRUE(ResetCheck(®s, 0x1000, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1001, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1002, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1003, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1004, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1005, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1006, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1007, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1008, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1009, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100a, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100b, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100c, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100d, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100e, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100f, 6, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); // 7 byte range. ASSERT_TRUE(ResetCheck(®s, 0x1000, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1001, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1002, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1003, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1004, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1005, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1006, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1007, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1008, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1009, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100a, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100b, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100c, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100d, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100e, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100f, 7, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); // 8 byte range. ASSERT_TRUE(ResetCheck(®s, 0x1000, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1000, 0x1008}, 0), 0xff)); ASSERT_TRUE(ResetCheck(®s, 0x1001, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1002, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1003, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1004, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1005, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1006, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1007, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x1008, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x1008, 0x1010}, 0), 0xff)); ASSERT_TRUE(ResetCheck(®s, 0x1009, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100a, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100b, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100c, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100d, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100e, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); ASSERT_TRUE(ResetCheck(®s, 0x100f, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_OUT_OF_RANGE))); } TEST(ArmHelpers_SettingWatchpoints, RangeIsDifferentWatchpoint) { zx_thread_state_debug_regs_t regs = {}; ASSERT_TRUE(Check(®s, 0x100, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100, 0x100 + 1}, 0), 0b00000001)); ASSERT_TRUE(CheckAddresses(regs, {0x100, 0, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0})); ASSERT_TRUE(CheckLengths(regs, {1, 0, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0})); ASSERT_TRUE(Check(®s, 0x100, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_ALREADY_BOUND))); ASSERT_TRUE(CheckAddresses(regs, {0x100, 0, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0})); ASSERT_TRUE(CheckLengths(regs, {1, 0, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0})); ASSERT_TRUE(Check(®s, 0x100, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100, 0x100 + 2}, 1), 0b00000011)); ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 0})); ASSERT_TRUE(CheckLengths(regs, {1, 2, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, 0, 0})); ASSERT_TRUE(Check(®s, 0x100, 2, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_ALREADY_BOUND))); ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 0})); ASSERT_TRUE(CheckLengths(regs, {1, 2, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, 0, 0})); ASSERT_TRUE(Check(®s, 0x100, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100, 0x100 + 4}, 2), 0b00001111)); ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0x100, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 0})); ASSERT_TRUE(CheckLengths(regs, {1, 2, 4, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, 0})); ASSERT_TRUE(Check(®s, 0x100, 4, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_ALREADY_BOUND))); ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0x100, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 0})); ASSERT_TRUE(CheckLengths(regs, {1, 2, 4, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, 0})); ASSERT_TRUE(Check(®s, 0x100, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {0x100, 0x100 + 8}, 3), 0b11111111)); ASSERT_TRUE(CheckAddresses(regs, {0x100, 0x100, 0x100, 0x100})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); ASSERT_TRUE(CheckLengths(regs, {1, 2, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kWrite, kWrite, kWrite})); // Deleting is by range too. ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 2}, kWatchpointCount), ZX_OK); EXPECT_TRUE(CheckAddresses(regs, {0x100, 0, 0x100, 0x100})); EXPECT_TRUE(CheckEnabled(regs, {1, 0, 1, 1})); ASSERT_TRUE(CheckLengths(regs, {1, 0, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, kWrite, kWrite})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 2}, kWatchpointCount), ZX_ERR_NOT_FOUND); EXPECT_TRUE(CheckAddresses(regs, {0x100, 0, 0x100, 0x100})); EXPECT_TRUE(CheckEnabled(regs, {1, 0, 1, 1})); ASSERT_TRUE(CheckLengths(regs, {1, 0, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, kWrite, kWrite})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 1}, kWatchpointCount), ZX_OK); EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0x100, 0x100})); EXPECT_TRUE(CheckEnabled(regs, {0, 0, 1, 1})); ASSERT_TRUE(CheckLengths(regs, {0, 0, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {0, 0, kWrite, kWrite})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 1}, kWatchpointCount), ZX_ERR_NOT_FOUND); EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0x100, 0x100})); EXPECT_TRUE(CheckEnabled(regs, {0, 0, 1, 1})); ASSERT_TRUE(CheckLengths(regs, {0, 0, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {0, 0, kWrite, kWrite})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 8}, kWatchpointCount), ZX_OK); EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0x100, 0})); EXPECT_TRUE(CheckEnabled(regs, {0, 0, 1, 0})); ASSERT_TRUE(CheckLengths(regs, {0, 0, 4, 0})); EXPECT_TRUE(CheckTypes(regs, {0, 0, kWrite, 0})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 8}, kWatchpointCount), ZX_ERR_NOT_FOUND); EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0x100, 0})); EXPECT_TRUE(CheckEnabled(regs, {0, 0, 1, 0})); ASSERT_TRUE(CheckLengths(regs, {0, 0, 4, 0})); EXPECT_TRUE(CheckTypes(regs, {0, 0, kWrite, 0})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {0x100, 0x100 + 4}, kWatchpointCount), ZX_OK); EXPECT_TRUE(CheckAddresses(regs, {0, 0, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {0, 0, 0, 0})); ASSERT_TRUE(CheckLengths(regs, {0, 0, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {0, 0, 0, 0})); } TEST(ArmHelpers_SettingWatchpoints, DifferentTypes) { zx_thread_state_debug_regs_t regs = {}; ASSERT_TRUE(Check(®s, kAddress1, 1, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {kAddress1, kAddress1 + 1}, 0), 0x1)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, 0, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 0, 0, 0})); EXPECT_TRUE(CheckLengths(regs, {1, 0, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, 0, 0, 0})); ASSERT_TRUE(Check(®s, kAddress2, 2, debug_ipc::BreakpointType::kRead, CreateResult(ZX_OK, {kAddress2, kAddress2 + 2}, 1), 0x3)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, 0, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 0})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 0, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, 0, 0})); ASSERT_TRUE(Check(®s, kAddress3, 4, debug_ipc::BreakpointType::kReadWrite, CreateResult(ZX_OK, {kAddress3, kAddress3 + 4}, 2), 0xf)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, 0})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 0})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 0})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kReadWrite, 0})); ASSERT_TRUE(Check(®s, kAddress4, 8, debug_ipc::BreakpointType::kRead, CreateResult(ZX_OK, {kAddress4, kAddress4 + 8}, 3), 0xff)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kReadWrite, kRead})); ASSERT_TRUE(Check(®s, kAddress5, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_ERR_NO_RESOURCES))); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress3, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 4, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kReadWrite, kRead})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {kAddress3, kAddress3 + 4}, kWatchpointCount), ZX_OK); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, 0, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 0, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 0, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, 0, kRead})); ASSERT_TRUE(Check(®s, kAddress5, 8, debug_ipc::BreakpointType::kWrite, CreateResult(ZX_OK, {kAddress5, kAddress5 + 8}, 2), 0xff)); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress5, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 8, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kWrite, kRead})); ASSERT_ZX_EQ(RemoveWatchpoint(®s, {kAddress3, kAddress3 + 4}, kWatchpointCount), ZX_ERR_NOT_FOUND); EXPECT_TRUE(CheckAddresses(regs, {kAddress1, kAddress2, kAddress5, kAddress4})); EXPECT_TRUE(CheckEnabled(regs, {1, 1, 1, 1})); EXPECT_TRUE(CheckLengths(regs, {1, 2, 8, 8})); EXPECT_TRUE(CheckTypes(regs, {kWrite, kRead, kWrite, kRead})); } } // namespace } // namespace arch } // namespace debug_agent ",16249,True,3626.279659553199,median "// Copyright 2015 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/backend/code-generator.h"" #include ""src/compiler/backend/instruction-scheduler.h"" namespace v8 { namespace internal { namespace compiler { bool InstructionScheduler::SchedulerSupported() { return true; } int InstructionScheduler::GetTargetInstructionFlags( const Instruction* instr) const { switch (instr->arch_opcode()) { case kMipsAbsD: case kMipsAbsS: case kMipsAdd: case kMipsAddD: case kMipsAddOvf: case kMipsAddPair: case kMipsAddS: case kMipsAnd: case kMipsByteSwap32: case kMipsCeilWD: case kMipsCeilWS: case kMipsClz: case kMipsCmp: case kMipsCmpD: case kMipsCmpS: case kMipsCtz: case kMipsCvtDS: case kMipsCvtDUw: case kMipsCvtDW: case kMipsCvtSD: case kMipsCvtSUw: case kMipsCvtSW: case kMipsDiv: case kMipsDivD: case kMipsDivS: case kMipsDivU: case kMipsExt: case kMipsF64x2Abs: case kMipsF64x2Neg: case kMipsF64x2Sqrt: case kMipsF64x2Add: case kMipsF64x2Sub: case kMipsF64x2Mul: case kMipsF64x2Div: case kMipsF64x2Min: case kMipsF64x2Max: case kMipsF64x2Eq: case kMipsF64x2Ne: case kMipsF64x2Lt: case kMipsF64x2Le: case kMipsF64x2Splat: case kMipsF64x2ExtractLane: case kMipsF64x2ReplaceLane: case kMipsF64x2Pmin: case kMipsF64x2Pmax: case kMipsF64x2Ceil: case kMipsF64x2Floor: case kMipsF64x2Trunc: case kMipsF64x2NearestInt: case kMipsF64x2ConvertLowI32x4S: case kMipsF64x2ConvertLowI32x4U: case kMipsF64x2PromoteLowF32x4: case kMipsI64x2Add: case kMipsI64x2Sub: case kMipsI64x2Mul: case kMipsI64x2Neg: case kMipsI64x2Shl: case kMipsI64x2ShrS: case kMipsI64x2ShrU: case kMipsI64x2BitMask: case kMipsI64x2Eq: case kMipsI64x2Ne: case kMipsI64x2GtS: case kMipsI64x2GeS: case kMipsI64x2Abs: case kMipsI64x2SConvertI32x4Low: case kMipsI64x2SConvertI32x4High: case kMipsI64x2UConvertI32x4Low: case kMipsI64x2UConvertI32x4High: case kMipsI64x2ExtMulLowI32x4S: case kMipsI64x2ExtMulHighI32x4S: case kMipsI64x2ExtMulLowI32x4U: case kMipsI64x2ExtMulHighI32x4U: case kMipsF32x4Abs: case kMipsF32x4Add: case kMipsF32x4Eq: case kMipsF32x4ExtractLane: case kMipsF32x4Le: case kMipsF32x4Lt: case kMipsF32x4Max: case kMipsF32x4Min: case kMipsF32x4Mul: case kMipsF32x4Div: case kMipsF32x4Ne: case kMipsF32x4Neg: case kMipsF32x4Sqrt: case kMipsF32x4RecipApprox: case kMipsF32x4RecipSqrtApprox: case kMipsF32x4ReplaceLane: case kMipsF32x4SConvertI32x4: case kMipsF32x4Splat: case kMipsF32x4Sub: case kMipsF32x4UConvertI32x4: case kMipsF32x4Pmin: case kMipsF32x4Pmax: case kMipsF32x4Ceil: case kMipsF32x4Floor: case kMipsF32x4Trunc: case kMipsF32x4NearestInt: case kMipsF32x4DemoteF64x2Zero: case kMipsFloat32Max: case kMipsFloat32Min: case kMipsFloat32RoundDown: case kMipsFloat32RoundTiesEven: case kMipsFloat32RoundTruncate: case kMipsFloat32RoundUp: case kMipsFloat64ExtractHighWord32: case kMipsFloat64ExtractLowWord32: case kMipsFloat64InsertHighWord32: case kMipsFloat64InsertLowWord32: case kMipsFloat64Max: case kMipsFloat64Min: case kMipsFloat64RoundDown: case kMipsFloat64RoundTiesEven: case kMipsFloat64RoundTruncate: case kMipsFloat64RoundUp: case kMipsFloat64SilenceNaN: case kMipsFloorWD: case kMipsFloorWS: case kMipsI16x8Add: case kMipsI16x8AddSatS: case kMipsI16x8AddSatU: case kMipsI16x8Eq: case kMipsI16x8ExtractLaneU: case kMipsI16x8ExtractLaneS: case kMipsI16x8GeS: case kMipsI16x8GeU: case kMipsI16x8RoundingAverageU: case kMipsI16x8GtS: case kMipsI16x8GtU: case kMipsI16x8MaxS: case kMipsI16x8MaxU: case kMipsI16x8MinS: case kMipsI16x8MinU: case kMipsI16x8Mul: case kMipsI16x8Ne: case kMipsI16x8Neg: case kMipsI16x8ReplaceLane: case kMipsI16x8SConvertI32x4: case kMipsI16x8SConvertI8x16High: case kMipsI16x8SConvertI8x16Low: case kMipsI16x8Shl: case kMipsI16x8ShrS: case kMipsI16x8ShrU: case kMipsI16x8Splat: case kMipsI16x8Sub: case kMipsI16x8SubSatS: case kMipsI16x8SubSatU: case kMipsI16x8UConvertI32x4: case kMipsI16x8UConvertI8x16High: case kMipsI16x8UConvertI8x16Low: case kMipsI16x8Abs: case kMipsI16x8BitMask: case kMipsI16x8Q15MulRSatS: case kMipsI16x8ExtMulLowI8x16S: case kMipsI16x8ExtMulHighI8x16S: case kMipsI16x8ExtMulLowI8x16U: case kMipsI16x8ExtMulHighI8x16U: case kMipsI16x8ExtAddPairwiseI8x16S: case kMipsI16x8ExtAddPairwiseI8x16U: case kMipsI32x4ExtAddPairwiseI16x8S: case kMipsI32x4ExtAddPairwiseI16x8U: case kMipsI32x4Add: case kMipsI32x4Eq: case kMipsI32x4ExtractLane: case kMipsI32x4GeS: case kMipsI32x4GeU: case kMipsI32x4GtS: case kMipsI32x4GtU: case kMipsI32x4MaxS: case kMipsI32x4MaxU: case kMipsI32x4MinS: case kMipsI32x4MinU: case kMipsI32x4Mul: case kMipsI32x4Ne: case kMipsI32x4Neg: case kMipsI32x4ReplaceLane: case kMipsI32x4SConvertF32x4: case kMipsI32x4SConvertI16x8High: case kMipsI32x4SConvertI16x8Low: case kMipsI32x4Shl: case kMipsI32x4ShrS: case kMipsI32x4ShrU: case kMipsI32x4Splat: case kMipsI32x4Sub: case kMipsI32x4UConvertF32x4: case kMipsI32x4UConvertI16x8High: case kMipsI32x4UConvertI16x8Low: case kMipsI32x4Abs: case kMipsI32x4BitMask: case kMipsI32x4DotI16x8S: case kMipsI32x4ExtMulLowI16x8S: case kMipsI32x4ExtMulHighI16x8S: case kMipsI32x4ExtMulLowI16x8U: case kMipsI32x4ExtMulHighI16x8U: case kMipsI32x4TruncSatF64x2SZero: case kMipsI32x4TruncSatF64x2UZero: case kMipsI8x16Add: case kMipsI8x16AddSatS: case kMipsI8x16AddSatU: case kMipsI8x16Eq: case kMipsI8x16ExtractLaneU: case kMipsI8x16ExtractLaneS: case kMipsI8x16GeS: case kMipsI8x16GeU: case kMipsI8x16RoundingAverageU: case kMipsI8x16GtS: case kMipsI8x16GtU: case kMipsI8x16MaxS: case kMipsI8x16MaxU: case kMipsI8x16MinS: case kMipsI8x16MinU: case kMipsI8x16Ne: case kMipsI8x16Neg: case kMipsI8x16ReplaceLane: case kMipsI8x16SConvertI16x8: case kMipsI8x16Shl: case kMipsI8x16ShrS: case kMipsI8x16ShrU: case kMipsI8x16Splat: case kMipsI8x16Sub: case kMipsI8x16SubSatS: case kMipsI8x16SubSatU: case kMipsI8x16UConvertI16x8: case kMipsI8x16Abs: case kMipsI8x16Popcnt: case kMipsI8x16BitMask: case kMipsIns: case kMipsLsa: case kMipsMaddD: case kMipsMaddS: case kMipsMaxD: case kMipsMaxS: case kMipsMinD: case kMipsMinS: case kMipsMod: case kMipsModU: case kMipsMov: case kMipsMsubD: case kMipsMsubS: case kMipsMul: case kMipsMulD: case kMipsMulHigh: case kMipsMulHighU: case kMipsMulOvf: case kMipsMulPair: case kMipsMulS: case kMipsNegD: case kMipsNegS: case kMipsNor: case kMipsOr: case kMipsPopcnt: case kMipsRor: case kMipsRoundWD: case kMipsRoundWS: case kMipsS128And: case kMipsS128Not: case kMipsS128Or: case kMipsS128Select: case kMipsS128Xor: case kMipsS128Zero: case kMipsS128AndNot: case kMipsS16x2Reverse: case kMipsS16x4Reverse: case kMipsS16x8InterleaveEven: case kMipsS16x8InterleaveLeft: case kMipsS16x8InterleaveOdd: case kMipsS16x8InterleaveRight: case kMipsS16x8PackEven: case kMipsS16x8PackOdd: case kMipsI64x2AllTrue: case kMipsI32x4AllTrue: case kMipsI16x8AllTrue: case kMipsI8x16AllTrue: case kMipsV128AnyTrue: case kMipsS32x4InterleaveEven: case kMipsS32x4InterleaveLeft: case kMipsS32x4InterleaveOdd: case kMipsS32x4InterleaveRight: case kMipsS32x4PackEven: case kMipsS32x4PackOdd: case kMipsS32x4Shuffle: case kMipsS8x16Concat: case kMipsS8x16InterleaveEven: case kMipsS8x16InterleaveLeft: case kMipsS8x16InterleaveOdd: case kMipsS8x16InterleaveRight: case kMipsS8x16PackEven: case kMipsS8x16PackOdd: case kMipsI8x16Shuffle: case kMipsI8x16Swizzle: case kMipsS8x2Reverse: case kMipsS8x4Reverse: case kMipsS8x8Reverse: case kMipsSar: case kMipsSarPair: case kMipsSeb: case kMipsSeh: case kMipsShl: case kMipsShlPair: case kMipsShr: case kMipsShrPair: case kMipsSqrtD: case kMipsSqrtS: case kMipsSub: case kMipsSubD: case kMipsSubOvf: case kMipsSubPair: case kMipsSubS: case kMipsTruncUwD: case kMipsTruncUwS: case kMipsTruncWD: case kMipsTruncWS: case kMipsTst: case kMipsXor: return kNoOpcodeFlags; case kMipsLb: case kMipsLbu: case kMipsLdc1: case kMipsLh: case kMipsLhu: case kMipsLw: case kMipsLwc1: case kMipsMsaLd: case kMipsPeek: case kMipsUldc1: case kMipsUlh: case kMipsUlhu: case kMipsUlw: case kMipsUlwc1: case kMipsS128Load8Splat: case kMipsS128Load16Splat: case kMipsS128Load32Splat: case kMipsS128Load64Splat: case kMipsS128Load8x8S: case kMipsS128Load8x8U: case kMipsS128Load16x4S: case kMipsS128Load16x4U: case kMipsS128Load32x2S: case kMipsS128Load32x2U: case kMipsWord32AtomicPairLoad: return kIsLoadOperation; case kMipsModD: case kMipsMsaSt: case kMipsPush: case kMipsSb: case kMipsSdc1: case kMipsSh: case kMipsStackClaim: case kMipsStoreToStackSlot: case kMipsSw: case kMipsSwc1: case kMipsUsdc1: case kMipsUsh: case kMipsUsw: case kMipsUswc1: case kMipsSync: case kMipsWord32AtomicPairStore: case kMipsWord32AtomicPairAdd: case kMipsWord32AtomicPairSub: case kMipsWord32AtomicPairAnd: case kMipsWord32AtomicPairOr: case kMipsWord32AtomicPairXor: case kMipsWord32AtomicPairExchange: case kMipsWord32AtomicPairCompareExchange: return kHasSideEffect; #define CASE(Name) case k##Name: COMMON_ARCH_OPCODE_LIST(CASE) #undef CASE // Already covered in architecture independent code. UNREACHABLE(); } UNREACHABLE(); } enum Latency { BRANCH = 4, // Estimated max. RINT_S = 4, // Estimated. RINT_D = 4, // Estimated. MULT = 4, MULTU = 4, MADD = 4, MADDU = 4, MSUB = 4, MSUBU = 4, MUL = 7, MULU = 7, MUH = 7, MUHU = 7, DIV = 50, // Min:11 Max:50 DIVU = 50, ABS_S = 4, ABS_D = 4, NEG_S = 4, NEG_D = 4, ADD_S = 4, ADD_D = 4, SUB_S = 4, SUB_D = 4, MAX_S = 4, // Estimated. MAX_D = 4, // Estimated. C_cond_S = 4, C_cond_D = 4, MUL_S = 4, MADD_S = 4, MSUB_S = 4, NMADD_S = 4, NMSUB_S = 4, CABS_cond_S = 4, CABS_cond_D = 4, CVT_D_S = 4, CVT_PS_PW = 4, CVT_S_W = 4, CVT_S_L = 4, CVT_D_W = 4, CVT_D_L = 4, CVT_S_D = 4, CVT_W_S = 4, CVT_W_D = 4, CVT_L_S = 4, CVT_L_D = 4, CEIL_W_S = 4, CEIL_W_D = 4, CEIL_L_S = 4, CEIL_L_D = 4, FLOOR_W_S = 4, FLOOR_W_D = 4, FLOOR_L_S = 4, FLOOR_L_D = 4, ROUND_W_S = 4, ROUND_W_D = 4, ROUND_L_S = 4, ROUND_L_D = 4, TRUNC_W_S = 4, TRUNC_W_D = 4, TRUNC_L_S = 4, TRUNC_L_D = 4, MOV_S = 4, MOV_D = 4, MOVF_S = 4, MOVF_D = 4, MOVN_S = 4, MOVN_D = 4, MOVT_S = 4, MOVT_D = 4, MOVZ_S = 4, MOVZ_D = 4, MUL_D = 5, MADD_D = 5, MSUB_D = 5, NMADD_D = 5, NMSUB_D = 5, RECIP_S = 13, RECIP_D = 26, RSQRT_S = 17, RSQRT_D = 36, DIV_S = 17, SQRT_S = 17, DIV_D = 32, SQRT_D = 32, MTC1 = 4, MTHC1 = 4, DMTC1 = 4, LWC1 = 4, LDC1 = 4, LDXC1 = 4, LUXC1 = 4, LWXC1 = 4, MFC1 = 1, MFHC1 = 1, MFHI = 1, MFLO = 1, DMFC1 = 1, SWC1 = 1, SDC1 = 1, SDXC1 = 1, SUXC1 = 1, SWXC1 = 1, }; int ClzLatency() { if (IsMipsArchVariant(kLoongson)) { return (6 + 2 * Latency::BRANCH); } else { return 1; } } int RorLatency(bool is_operand_register = true) { if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) { return 1; } else { if (is_operand_register) { return 4; } else { return 3; // Estimated max. } } } int AdduLatency(bool is_operand_register = true) { if (is_operand_register) { return 1; } else { return 2; // Estimated max. } } int XorLatency(bool is_operand_register = true) { return AdduLatency(is_operand_register); } int AndLatency(bool is_operand_register = true) { return AdduLatency(is_operand_register); } int OrLatency(bool is_operand_register = true) { return AdduLatency(is_operand_register); } int SubuLatency(bool is_operand_register = true) { return AdduLatency(is_operand_register); } int MulLatency(bool is_operand_register = true) { if (is_operand_register) { if (IsMipsArchVariant(kLoongson)) { return Latency::MULT + 1; } else { return Latency::MUL + 1; } } else { if (IsMipsArchVariant(kLoongson)) { return Latency::MULT + 2; } else { return Latency::MUL + 2; } } } int NorLatency(bool is_operand_register = true) { if (is_operand_register) { return 1; } else { return 2; } } int InsLatency() { if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) { return 1; } else { return SubuLatency(false) + 7; } } int ShlPairLatency(bool is_operand_register = true) { if (is_operand_register) { int latency = AndLatency(false) + NorLatency() + OrLatency() + AndLatency(false) + 4; if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) { return latency + Latency::BRANCH + 2; } else { return latency + 2; } } else { return 2; } } int ShrPairLatency(bool is_operand_register = true, uint32_t shift = 0) { if (is_operand_register) { int latency = AndLatency(false) + NorLatency() + OrLatency() + AndLatency(false) + 4; if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) { return latency + Latency::BRANCH + 2; } else { return latency + 2; } } else { // Estimated max. return (InsLatency() + 2 > OrLatency() + 3) ? InsLatency() + 2 : OrLatency() + 3; } } int SarPairLatency(bool is_operand_register = true, uint32_t shift = 0) { if (is_operand_register) { return AndLatency(false) + NorLatency() + OrLatency() + AndLatency(false) + Latency::BRANCH + 6; } else { shift = shift & 0x3F; if (shift == 0) { return 2; } else if (shift < 32) { if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) { return InsLatency() + 2; } else { return OrLatency() + 3; } } else if (shift == 32) { return 2; } else { return 2; } } } int ExtLatency() { if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) { return 1; } else { // Estimated max. return 2; } } int LsaLatency() { // Estimated max. return AdduLatency() + 1; } int SltLatency(bool is_operand_register = true) { if (is_operand_register) { return 1; } else { return 2; // Estimated max. } } int SltuLatency(bool is_operand_register = true) { return SltLatency(is_operand_register); } int AddPairLatency() { return 3 * AdduLatency() + SltLatency(); } int SubPairLatency() { return SltuLatency() + 3 * SubuLatency(); } int MuluLatency(bool is_operand_register = true) { int latency = 0; if (!is_operand_register) latency++; if (!IsMipsArchVariant(kMips32r6)) { return latency + Latency::MULTU + 2; } else { return latency + Latency::MULU + Latency::MUHU; } } int MulPairLatency() { return MuluLatency() + 2 * MulLatency() + 2 * AdduLatency(); } int MaddSLatency() { if (IsMipsArchVariant(kMips32r2)) { return Latency::MADD_D; } else { return Latency::MUL_D + Latency::ADD_D; } } int MaddDLatency() { if (IsMipsArchVariant(kMips32r2)) { return Latency::MADD_D; } else { return Latency::MUL_D + Latency::ADD_D; } } int MsubSLatency() { if (IsMipsArchVariant(kMips32r2)) { return Latency::MSUB_S; } else { return Latency::MUL_S + Latency::SUB_S; } } int MsubDLatency() { if (IsMipsArchVariant(kMips32r2)) { return Latency::MSUB_D; } else { return Latency::MUL_D + Latency::SUB_D; } } int Mfhc1Latency() { if (IsFp32Mode()) { return Latency::MFC1; } else { return 1; } } int Mthc1Latency() { if (IsFp32Mode()) { return Latency::MTC1; } else { return 1; } } int MoveLatency(bool is_double_register = true) { if (!is_double_register) { return Latency::MTC1 + 1; } else { return Mthc1Latency() + 1; // Estimated. } } int Float64RoundLatency() { if (IsMipsArchVariant(kMips32r6)) { return Latency::RINT_D + 4; } else { // For ceil_l_d, floor_l_d, round_l_d, trunc_l_d latency is 4. return Mfhc1Latency() + ExtLatency() + Latency::BRANCH + Latency::MOV_D + 4 + MoveLatency() + 1 + Latency::BRANCH + Latency::CVT_D_L; } } int Float32RoundLatency() { if (IsMipsArchVariant(kMips32r6)) { return Latency::RINT_S + 4; } else { // For ceil_w_s, floor_w_s, round_w_s, trunc_w_s latency is 4. return Latency::MFC1 + ExtLatency() + Latency::BRANCH + Latency::MOV_S + 4 + Latency::MFC1 + Latency::BRANCH + Latency::CVT_S_W; } } int CvtDUwLatency() { if (IsFp64Mode()) { return Latency::MTC1 + Mthc1Latency() + Latency::CVT_D_L; } else { return Latency::BRANCH + Latency::MTC1 + 1 + Latency::MTC1 + Mthc1Latency() + Latency::CVT_D_W + Latency::BRANCH + Latency::ADD_D + Latency::CVT_D_W; } } int CvtSUwLatency() { return CvtDUwLatency() + Latency::CVT_S_D; } int Floor_w_dLatency() { if (IsMipsArchVariant(kLoongson)) { return Mfhc1Latency() + Latency::FLOOR_W_D + Mthc1Latency(); } else { return Latency::FLOOR_W_D; } } int FloorWDLatency() { return Floor_w_dLatency() + Latency::MFC1; } int Ceil_w_dLatency() { if (IsMipsArchVariant(kLoongson)) { return Mfhc1Latency() + Latency::CEIL_W_D + Mthc1Latency(); } else { return Latency::CEIL_W_D; } } int CeilWDLatency() { return Ceil_w_dLatency() + Latency::MFC1; } int Round_w_dLatency() { if (IsMipsArchVariant(kLoongson)) { return Mfhc1Latency() + Latency::ROUND_W_D + Mthc1Latency(); } else { return Latency::ROUND_W_D; } } int RoundWDLatency() { return Round_w_dLatency() + Latency::MFC1; } int Trunc_w_dLatency() { if (IsMipsArchVariant(kLoongson)) { return Mfhc1Latency() + Latency::TRUNC_W_D + Mthc1Latency(); } else { return Latency::TRUNC_W_D; } } int MovnLatency() { if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) { return Latency::BRANCH + 1; } else { return 1; } } int Trunc_uw_dLatency() { return 1 + Latency::MTC1 + Mthc1Latency() + Latency::BRANCH + Latency::SUB_D + Latency::TRUNC_W_D + Latency::MFC1 + OrLatency(false) + Latency::BRANCH + Latency::TRUNC_W_D + Latency::MFC1; } int Trunc_uw_sLatency() { return 1 + Latency::MTC1 + Latency::BRANCH + Latency::SUB_S + Latency::TRUNC_W_S + Latency::MFC1 + OrLatency(false) + Latency::TRUNC_W_S + Latency::MFC1; } int MovzLatency() { if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) { return Latency::BRANCH + 1; } else { return 1; } } int FmoveLowLatency() { if (IsFp32Mode()) { return Latency::MTC1; } else { return Latency::MFHC1 + Latency::MTC1 + Latency::MTHC1; } } int SebLatency() { if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) { return 1; } else { return 2; } } int SehLatency() { if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) { return 1; } else { return 2; } } int UlhuLatency() { if (IsMipsArchVariant(kMips32r6)) { return 1; } else { return 4; } } int UlhLatency() { if (IsMipsArchVariant(kMips32r6)) { return 1; } else { return 4; } } int AdjustBaseAndOffsetLatency() { return 3; // Estimated max. } int UshLatency() { if (IsMipsArchVariant(kMips32r6)) { return 1; } else { return AdjustBaseAndOffsetLatency() + 4; // Estimated max. } } int UlwLatency() { if (IsMipsArchVariant(kMips32r6)) { return 1; } else { return AdjustBaseAndOffsetLatency() + 3; // Estimated max. } } int UswLatency() { if (IsMipsArchVariant(kMips32r6)) { return 1; } else { return AdjustBaseAndOffsetLatency() + 2; } } int Ulwc1Latency() { if (IsMipsArchVariant(kMips32r6)) { return Latency::LWC1; } else { return UlwLatency() + Latency::MTC1; } } int Uswc1Latency() { if (IsMipsArchVariant(kMips32r6)) { return Latency::SWC1; } else { return Latency::MFC1 + UswLatency(); } } int Ldc1Latency() { int latency = AdjustBaseAndOffsetLatency() + Latency::LWC1; if (IsFp32Mode()) { return latency + Latency::LWC1; } else { return latency + 1 + Mthc1Latency(); } } int Uldc1Latency() { if (IsMipsArchVariant(kMips32r6)) { return Ldc1Latency(); } else { return 2 * UlwLatency() + Latency::MTC1 + Mthc1Latency(); } } int Sdc1Latency() { int latency = AdjustBaseAndOffsetLatency() + Latency::SWC1; if (IsFp32Mode()) { return latency + Latency::SWC1; } else { return latency + Mfhc1Latency() + 1; } } int Usdc1Latency() { if (IsMipsArchVariant(kMips32r6)) { return Sdc1Latency(); } else { return Latency::MFC1 + 2 * UswLatency() + Mfhc1Latency(); } } int PushRegisterLatency() { return AdduLatency(false) + 1; } int ByteSwapSignedLatency() { // operand_size == 4 if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) { return 2; } else if (IsMipsArchVariant(kMips32r1) || IsMipsArchVariant(kLoongson)) { return 10; } } int LlLatency(int offset) { bool is_one_instruction = IsMipsArchVariant(kMips32r6) ? is_int9(offset) : is_int16(offset); if (is_one_instruction) { return 1; } else { return 3; } } int ExtractBitsLatency(int size, bool sign_extend) { int latency = 1 + ExtLatency(); if (size == 8) { if (sign_extend) { return latency + SebLatency(); } else { return 0; } } else if (size == 16) { if (sign_extend) { return latency + SehLatency(); } else { return 0; } } else { UNREACHABLE(); } } int NegLatency() { return 1; } int InsertBitsLatency() { return RorLatency() + InsLatency() + SubuLatency(false) + NegLatency() + RorLatency(); } int ScLatency(int offset) { bool is_one_instruction = IsMipsArchVariant(kMips32r6) ? is_int9(offset) : is_int16(offset); if (is_one_instruction) { return 1; } else { return 3; } } int BranchShortHelperR6Latency() { return 2; // Estimated max. } int BranchShortHelperLatency() { return SltLatency() + 2; // Estimated max. } int BranchShortLatency(BranchDelaySlot bdslot = PROTECT) { if (IsMipsArchVariant(kMips32r6) && bdslot == PROTECT) { return BranchShortHelperR6Latency(); } else { return BranchShortHelperLatency(); } } int Word32AtomicExchangeLatency(bool sign_extend, int size) { return AdduLatency() + 1 + SubuLatency() + 2 + LlLatency(0) + ExtractBitsLatency(size, sign_extend) + InsertBitsLatency() + ScLatency(0) + BranchShortLatency() + 1; } int Word32AtomicCompareExchangeLatency(bool sign_extend, int size) { return AdduLatency() + 1 + SubuLatency() + 2 + LlLatency(0) + ExtractBitsLatency(size, sign_extend) + BranchShortLatency() + 1; } int AddOverflowLatency() { return 6; // Estimated max. } int SubOverflowLatency() { return 6; // Estimated max. } int MulhLatency(bool is_operand_register = true) { if (is_operand_register) { if (!IsMipsArchVariant(kMips32r6)) { return Latency::MULT + Latency::MFHI; } else { return Latency::MUH; } } else { if (!IsMipsArchVariant(kMips32r6)) { return 1 + Latency::MULT + Latency::MFHI; } else { return 1 + Latency::MUH; } } } int MulhuLatency(bool is_operand_register = true) { if (is_operand_register) { if (!IsMipsArchVariant(kMips32r6)) { return Latency::MULTU + Latency::MFHI; } else { return Latency::MUHU; } } else { if (!IsMipsArchVariant(kMips32r6)) { return 1 + Latency::MULTU + Latency::MFHI; } else { return 1 + Latency::MUHU; } } } int MulOverflowLatency() { return MulLatency() + 4; // Estimated max. } int ModLatency(bool is_operand_register = true) { if (is_operand_register) { if (!IsMipsArchVariant(kMips32r6)) { return Latency::DIV + Latency::MFHI; } else { return 1; } } else { if (!IsMipsArchVariant(kMips32r6)) { return 1 + Latency::DIV + Latency::MFHI; } else { return 2; } } } int ModuLatency(bool is_operand_register = true) { return ModLatency(is_operand_register); } int DivLatency(bool is_operand_register = true) { if (is_operand_register) { if (!IsMipsArchVariant(kMips32r6)) { return Latency::DIV + Latency::MFLO; } else { return Latency::DIV; } } else { if (!IsMipsArchVariant(kMips32r6)) { return 1 + Latency::DIV + Latency::MFLO; } else { return 1 + Latency::DIV; } } } int DivuLatency(bool is_operand_register = true) { if (is_operand_register) { if (!IsMipsArchVariant(kMips32r6)) { return Latency::DIVU + Latency::MFLO; } else { return Latency::DIVU; } } else { if (!IsMipsArchVariant(kMips32r6)) { return 1 + Latency::DIVU + Latency::MFLO; } else { return 1 + Latency::DIVU; } } } int CtzLatency() { if (IsMipsArchVariant(kMips32r6)) { return RorLatency(false) + 2 + ClzLatency(); } else { return AdduLatency(false) + XorLatency() + AndLatency() + ClzLatency() + 1 + SubuLatency(); } } int PopcntLatency() { return 4 * AndLatency() + SubuLatency() + 2 * AdduLatency() + MulLatency() + 8; } int CompareFLatency() { return Latency::C_cond_S; } int CompareIsNanFLatency() { return CompareFLatency(); } int CompareIsNanF32Latency() { return CompareIsNanFLatency(); } int Neg_sLatency() { if (IsMipsArchVariant(kMips32r6)) { return Latency::NEG_S; } else { // Estimated. return CompareIsNanF32Latency() + 2 * Latency::BRANCH + Latency::NEG_S + Latency::MFC1 + 1 + XorLatency() + Latency::MTC1; } } int CompareIsNanF64Latency() { return CompareIsNanFLatency(); } int Neg_dLatency() { if (IsMipsArchVariant(kMips32r6)) { return Latency::NEG_D; } else { // Estimated. return CompareIsNanF64Latency() + 2 * Latency::BRANCH + Latency::NEG_D + Mfhc1Latency() + 1 + XorLatency() + Mthc1Latency(); } } int CompareF32Latency() { return CompareFLatency(); } int Move_sLatency() { return Latency::MOV_S; // Estimated max. } int Float32MaxLatency() { // Estimated max. int latency = CompareIsNanF32Latency() + Latency::BRANCH; if (IsMipsArchVariant(kMips32r6)) { return latency + Latency::MAX_S; } else { return latency + 5 * Latency::BRANCH + 2 * CompareF32Latency() + Latency::MFC1 + Move_sLatency(); } } int CompareF64Latency() { return CompareF32Latency(); } int Move_dLatency() { return Latency::MOV_D; // Estimated max. } int Float64MaxLatency() { // Estimated max. int latency = CompareIsNanF64Latency() + Latency::BRANCH; if (IsMipsArchVariant(kMips32r6)) { return latency + Latency::MAX_D; } else { return latency + 5 * Latency::BRANCH + 2 * CompareF64Latency() + Latency::MFHC1 + 2 * Move_dLatency(); } } int PrepareCallCFunctionLatency() { int frame_alignment = TurboAssembler::ActivationFrameAlignment(); if (frame_alignment > kSystemPointerSize) { return 1 + SubuLatency(false) + AndLatency(false) + 1; } else { return SubuLatency(false); } } int MovToFloatParametersLatency() { return 2 * MoveLatency(); } int CallLatency() { // Estimated. return AdduLatency(false) + Latency::BRANCH + 3; } int CallCFunctionHelperLatency() { // Estimated. int latency = AndLatency(false) + Latency::BRANCH + 2 + CallLatency(); if (base::OS::ActivationFrameAlignment() > kSystemPointerSize) { latency++; } else { latency += AdduLatency(false); } return latency; } int CallCFunctionLatency() { return 1 + CallCFunctionHelperLatency(); } int MovFromFloatResultLatency() { return MoveLatency(); } int Float32MinLatency() { // Estimated max. return CompareIsNanF32Latency() + Latency::BRANCH + 2 * (CompareF32Latency() + Latency::BRANCH) + Latency::MFC1 + 2 * Latency::BRANCH + Move_sLatency(); } int Float64MinLatency() { // Estimated max. return CompareIsNanF64Latency() + Latency::BRANCH + 2 * (CompareF64Latency() + Latency::BRANCH) + Mfhc1Latency() + 2 * Latency::BRANCH + Move_dLatency(); } int SmiUntagLatency() { return 1; } int PrepareForTailCallLatency() { // Estimated max. return 2 * (LsaLatency() + AdduLatency(false)) + 2 + Latency::BRANCH + Latency::BRANCH + 2 * SubuLatency(false) + 2 + Latency::BRANCH + 1; } int JumpLatency() { // Estimated max. return 1 + AdduLatency(false) + Latency::BRANCH + 2; } int AssertLatency() { return 1; } int MultiPushLatency() { int latency = SubuLatency(false); for (int16_t i = kNumRegisters - 1; i >= 0; i--) { latency++; } return latency; } int MultiPushFPULatency() { int latency = SubuLatency(false); for (int16_t i = kNumRegisters - 1; i >= 0; i--) { latency += Sdc1Latency(); } return latency; } int PushCallerSavedLatency(SaveFPRegsMode fp_mode) { int latency = MultiPushLatency(); if (fp_mode == SaveFPRegsMode::kSave) { latency += MultiPushFPULatency(); } return latency; } int MultiPopFPULatency() { int latency = 0; for (int16_t i = 0; i < kNumRegisters; i++) { latency += Ldc1Latency(); } return latency++; } int MultiPopLatency() { int latency = 0; for (int16_t i = 0; i < kNumRegisters; i++) { latency++; } return latency++; } int PopCallerSavedLatency(SaveFPRegsMode fp_mode) { int latency = 0; if (fp_mode == SaveFPRegsMode::kSave) { latency += MultiPopFPULatency(); } return latency + MultiPopLatency(); } int AssembleArchJumpLatency() { // Estimated max. return Latency::BRANCH; } int AssembleArchBinarySearchSwitchLatency(int cases) { if (cases < CodeGenerator::kBinarySearchSwitchMinimalCases) { return cases * (1 + Latency::BRANCH) + AssembleArchJumpLatency(); } return 1 + Latency::BRANCH + AssembleArchBinarySearchSwitchLatency(cases / 2); } int GenerateSwitchTableLatency() { int latency = 0; if (kArchVariant >= kMips32r6) { latency = LsaLatency() + 2; } else { latency = 6; } latency += 2; return latency; } int AssembleArchTableSwitchLatency() { return Latency::BRANCH + GenerateSwitchTableLatency(); } int AssembleReturnLatency() { // Estimated max. return AdduLatency(false) + MultiPopLatency() + MultiPopFPULatency() + Latency::BRANCH + 1 + AdduLatency() + 8; } int TryInlineTruncateDoubleToILatency() { return 2 + Latency::TRUNC_W_D + Latency::MFC1 + 2 + AndLatency(false) + Latency::BRANCH; } int CallStubDelayedLatency() { return 1 + CallLatency(); } int TruncateDoubleToIDelayedLatency() { // TODO(mips): This no longer reflects how TruncateDoubleToI is called. return TryInlineTruncateDoubleToILatency() + 1 + SubuLatency(false) + Sdc1Latency() + CallStubDelayedLatency() + AdduLatency(false) + 1; } int CheckPageFlagLatency() { return 2 * AndLatency(false) + 1 + Latency::BRANCH; } int InstructionScheduler::GetInstructionLatency(const Instruction* instr) { // Basic latency modeling for MIPS32 instructions. They have been determined // in an empirical way. switch (instr->arch_opcode()) { case kArchCallCodeObject: #if V8_ENABLE_WEBASSEMBLY case kArchCallWasmFunction: #endif // V8_ENABLE_WEBASSEMBLY return CallLatency(); case kArchTailCallCodeObject: #if V8_ENABLE_WEBASSEMBLY case kArchTailCallWasm: #endif // V8_ENABLE_WEBASSEMBLY case kArchTailCallAddress: return JumpLatency(); case kArchCallJSFunction: { int latency = 0; if (FLAG_debug_code) { latency = 1 + AssertLatency(); } return latency + 1 + AdduLatency(false) + CallLatency(); } case kArchPrepareCallCFunction: return PrepareCallCFunctionLatency(); case kArchSaveCallerRegisters: { auto fp_mode = static_cast(MiscField::decode(instr->opcode())); return PushCallerSavedLatency(fp_mode); } case kArchRestoreCallerRegisters: { auto fp_mode = static_cast(MiscField::decode(instr->opcode())); return PopCallerSavedLatency(fp_mode); } case kArchPrepareTailCall: return 2; // Estimated max. case kArchCallCFunction: return CallCFunctionLatency(); case kArchJmp: return AssembleArchJumpLatency(); case kArchBinarySearchSwitch: return AssembleArchBinarySearchSwitchLatency((instr->InputCount() - 2) / 2); case kArchTableSwitch: return AssembleArchTableSwitchLatency(); case kArchAbortCSADcheck: return CallLatency() + 1; case kArchComment: case kArchDeoptimize: return 0; case kArchRet: return AssembleReturnLatency(); case kArchTruncateDoubleToI: return TruncateDoubleToIDelayedLatency(); case kArchStoreWithWriteBarrier: return AdduLatency() + 1 + CheckPageFlagLatency(); case kArchStackSlot: { // Estimated max. return AdduLatency(false) + AndLatency(false) + AssertLatency() + AdduLatency(false) + AndLatency(false) + BranchShortLatency() + 1 + SubuLatency() + AdduLatency(); } case kIeee754Float64Acos: case kIeee754Float64Acosh: case kIeee754Float64Asin: case kIeee754Float64Asinh: case kIeee754Float64Atan: case kIeee754Float64Atanh: case kIeee754Float64Atan2: case kIeee754Float64Cos: case kIeee754Float64Cosh: case kIeee754Float64Cbrt: case kIeee754Float64Exp: case kIeee754Float64Expm1: case kIeee754Float64Log: case kIeee754Float64Log1p: case kIeee754Float64Log10: case kIeee754Float64Log2: case kIeee754Float64Pow: case kIeee754Float64Sin: case kIeee754Float64Sinh: case kIeee754Float64Tan: case kIeee754Float64Tanh: return PrepareCallCFunctionLatency() + MovToFloatParametersLatency() + CallCFunctionLatency() + MovFromFloatResultLatency(); case kMipsAdd: return AdduLatency(instr->InputAt(1)->IsRegister()); case kMipsAnd: return AndLatency(instr->InputAt(1)->IsRegister()); case kMipsOr: return OrLatency(instr->InputAt(1)->IsRegister()); case kMipsXor: return XorLatency(instr->InputAt(1)->IsRegister()); case kMipsSub: return SubuLatency(instr->InputAt(1)->IsRegister()); case kMipsNor: return NorLatency(instr->InputAt(1)->IsRegister()); case kMipsAddOvf: return AddOverflowLatency(); case kMipsSubOvf: return SubOverflowLatency(); case kMipsMul: return MulLatency(false); case kMipsMulHigh: return MulhLatency(instr->InputAt(1)->IsRegister()); case kMipsMulHighU: return MulhuLatency(instr->InputAt(1)->IsRegister()); case kMipsMulOvf: return MulOverflowLatency(); case kMipsMod: return ModLatency(instr->InputAt(1)->IsRegister()); case kMipsModU: return ModuLatency(instr->InputAt(1)->IsRegister()); case kMipsDiv: { int latency = DivLatency(instr->InputAt(1)->IsRegister()); if (IsMipsArchVariant(kMips32r6)) { return latency++; } else { return latency + MovzLatency(); } } case kMipsDivU: { int latency = DivuLatency(instr->InputAt(1)->IsRegister()); if (IsMipsArchVariant(kMips32r6)) { return latency++; } else { return latency + MovzLatency(); } } case kMipsClz: return ClzLatency(); case kMipsCtz: return CtzLatency(); case kMipsPopcnt: return PopcntLatency(); case kMipsShlPair: { if (instr->InputAt(2)->IsRegister()) { return ShlPairLatency(); } else { return ShlPairLatency(false); } } case kMipsShrPair: { if (instr->InputAt(2)->IsRegister()) { return ShrPairLatency(); } else { // auto immediate_operand = ImmediateOperand::cast(instr->InputAt(2)); // return ShrPairLatency(false, immediate_operand->inline_32_value()); return 1; } } case kMipsSarPair: { if (instr->InputAt(2)->IsRegister()) { return SarPairLatency(); } else { return SarPairLatency(false); } } case kMipsExt: return ExtLatency(); case kMipsIns: return InsLatency(); case kMipsRor: return RorLatency(instr->InputAt(1)->IsRegister()); case kMipsLsa: return LsaLatency(); case kMipsModD: return PrepareCallCFunctionLatency() + MovToFloatParametersLatency() + CallCFunctionLatency() + MovFromFloatResultLatency(); case kMipsAddPair: return AddPairLatency(); case kMipsSubPair: return SubPairLatency(); case kMipsMulPair: return MulPairLatency(); case kMipsMaddS: return MaddSLatency(); case kMipsMaddD: return MaddDLatency(); case kMipsMsubS: return MsubSLatency(); case kMipsMsubD: return MsubDLatency(); case kMipsNegS: return Neg_sLatency(); case kMipsNegD: return Neg_dLatency(); case kMipsFloat64RoundDown: case kMipsFloat64RoundTruncate: case kMipsFloat64RoundUp: case kMipsFloat64RoundTiesEven: return Float64RoundLatency(); case kMipsFloat32RoundDown: case kMipsFloat32RoundTruncate: case kMipsFloat32RoundUp: case kMipsFloat32RoundTiesEven: return Float32RoundLatency(); case kMipsFloat32Max: return Float32MaxLatency(); case kMipsFloat64Max: return Float64MaxLatency(); case kMipsFloat32Min: return Float32MinLatency(); case kMipsFloat64Min: return Float64MinLatency(); case kMipsCvtSUw: return CvtSUwLatency(); case kMipsCvtDUw: return CvtDUwLatency(); case kMipsFloorWD: return FloorWDLatency(); case kMipsCeilWD: return CeilWDLatency(); case kMipsRoundWD: return RoundWDLatency(); case kMipsTruncWD: return Trunc_w_dLatency() + Latency::MFC1; case kMipsTruncWS: return Latency::TRUNC_W_S + Latency::MFC1 + AdduLatency(false) + SltLatency() + MovnLatency(); case kMipsTruncUwD: return Trunc_uw_dLatency(); case kMipsTruncUwS: return Trunc_uw_sLatency() + AdduLatency(false) + MovzLatency(); case kMipsFloat64ExtractLowWord32: return Latency::MFC1; case kMipsFloat64ExtractHighWord32: return Mfhc1Latency(); case kMipsFloat64InsertLowWord32: { if (IsFp32Mode()) { return Latency::MTC1; } else { return Latency::MFHC1 + Latency::MTC1 + Latency::MTHC1; } } case kMipsFloat64InsertHighWord32: return Mthc1Latency(); case kMipsFloat64SilenceNaN: return Latency::SUB_D; case kMipsSeb: return SebLatency(); case kMipsSeh: return SehLatency(); case kMipsUlhu: return UlhuLatency(); case kMipsUlh: return UlhLatency(); case kMipsUsh: return UshLatency(); case kMipsUlw: return UlwLatency(); case kMipsUsw: return UswLatency(); case kMipsUlwc1: return Ulwc1Latency(); case kMipsSwc1: return MoveLatency(false) + Latency::SWC1; // Estimated max. case kMipsUswc1: return MoveLatency(false) + Uswc1Latency(); // Estimated max. case kMipsLdc1: return Ldc1Latency(); case kMipsUldc1: return Uldc1Latency(); case kMipsSdc1: return MoveLatency(false) + Sdc1Latency(); // Estimated max. case kMipsUsdc1: return MoveLatency(false) + Usdc1Latency(); // Estimated max. case kMipsPush: { if (instr->InputAt(0)->IsFPRegister()) { auto op = LocationOperand::cast(instr->InputAt(0)); switch (op->representation()) { case MachineRepresentation::kFloat32: return Latency::SWC1 + SubuLatency(false); case MachineRepresentation::kFloat64: return Sdc1Latency() + SubuLatency(false); default: { UNREACHABLE(); } } } else { return PushRegisterLatency(); } } case kMipsPeek: { if (instr->OutputAt(0)->IsFPRegister()) { auto op = LocationOperand::cast(instr->OutputAt(0)); if (op->representation() == MachineRepresentation::kFloat64) { return Ldc1Latency(); } else { return Latency::LWC1; } } else { return 1; } } case kMipsStackClaim: return SubuLatency(false); case kMipsStoreToStackSlot: { if (instr->InputAt(0)->IsFPRegister()) { auto op = LocationOperand::cast(instr->InputAt(0)); if (op->representation() == MachineRepresentation::kFloat64) { return Sdc1Latency(); } else if (op->representation() == MachineRepresentation::kFloat32) { return Latency::SWC1; } else { return 1; // Estimated value. } } else { return 1; } } case kMipsByteSwap32: return ByteSwapSignedLatency(); case kAtomicLoadInt8: case kAtomicLoadUint8: case kAtomicLoadInt16: case kAtomicLoadUint16: case kAtomicLoadWord32: return 2; case kAtomicStoreWord8: case kAtomicStoreWord16: case kAtomicStoreWord32: return 3; case kAtomicExchangeInt8: return Word32AtomicExchangeLatency(true, 8); case kAtomicExchangeUint8: return Word32AtomicExchangeLatency(false, 8); case kAtomicExchangeInt16: return Word32AtomicExchangeLatency(true, 16); case kAtomicExchangeUint16: return Word32AtomicExchangeLatency(false, 16); case kAtomicExchangeWord32: { return 1 + AdduLatency() + Ldc1Latency() + 1 + ScLatency(0) + BranchShortLatency() + 1; } case kAtomicCompareExchangeInt8: return Word32AtomicCompareExchangeLatency(true, 8); case kAtomicCompareExchangeUint8: return Word32AtomicCompareExchangeLatency(false, 8); case kAtomicCompareExchangeInt16: return Word32AtomicCompareExchangeLatency(true, 16); case kAtomicCompareExchangeUint16: return Word32AtomicCompareExchangeLatency(false, 16); case kAtomicCompareExchangeWord32: return AdduLatency() + 1 + LlLatency(0) + BranchShortLatency() + 1; case kMipsTst: return AndLatency(instr->InputAt(1)->IsRegister()); case kMipsCmpS: return MoveLatency() + CompareF32Latency(); case kMipsCmpD: return MoveLatency() + CompareF64Latency(); case kArchNop: case kArchThrowTerminator: case kMipsCmp: return 0; case kArchDebugBreak: case kArchFramePointer: case kArchParentFramePointer: case kMipsShl: case kMipsShr: case kMipsSar: case kMipsMov: case kMipsMaxS: case kMipsMinS: case kMipsMaxD: case kMipsMinD: case kMipsLbu: case kMipsLb: case kMipsSb: case kMipsLhu: case kMipsLh: case kMipsSh: case kMipsLw: case kMipsSw: case kMipsLwc1: return 1; case kMipsAddS: return Latency::ADD_S; case kMipsSubS: return Latency::SUB_S; case kMipsMulS: return Latency::MUL_S; case kMipsAbsS: return Latency::ABS_S; case kMipsAddD: return Latency::ADD_D; case kMipsSubD: return Latency::SUB_D; case kMipsAbsD: return Latency::ABS_D; case kMipsCvtSD: return Latency::CVT_S_D; case kMipsCvtDS: return Latency::CVT_D_S; case kMipsMulD: return Latency::MUL_D; case kMipsFloorWS: return Latency::FLOOR_W_S; case kMipsCeilWS: return Latency::CEIL_W_S; case kMipsRoundWS: return Latency::ROUND_W_S; case kMipsCvtDW: return Latency::CVT_D_W; case kMipsCvtSW: return Latency::CVT_S_W; case kMipsDivS: return Latency::DIV_S; case kMipsSqrtS: return Latency::SQRT_S; case kMipsDivD: return Latency::DIV_D; case kMipsSqrtD: return Latency::SQRT_D; default: return 1; } } } // namespace compiler } // namespace internal } // namespace v8 ",16184,True,2717.422601183389,median "== CMMN 1.1 === What is CMMN? The Case Management Model and Notation (CMMN) is a standard notation and formal specification by the link:$$http://www.omg.org/spec/CMMN/$$[Object Management Group] for representing case models. Flowable contains: * A CMMN 1.1 modeler to create CMMN 1.1 case models * A Java engine that can import and execute CMMN 1.1 case models * A demonstration UI that executes the case models, allowing users to see and complete human tasks (and their forms) === Basic concepts and terminology The following figure shows a simple CMMN 1.1 diagram: image::images/cmmn-basic-concepts.png[align=""center""] A *case model* is always visualized as some sort of _folder_ that contains all the case elements. Every case model contains a *plan model* onto which items will be _planned_. The elements of a plan model are called *plan items*. Each _plan item_ has a *plan item definition* that gives its type and possible configuration options at runtime. For example, in the figure above, there are three *human task* plan items and one *milestone*. Other examples of plan items are _process tasks, case tasks and stages_. After having deployed a case model to the Flowable CMMN engine, it's possible to start *case instances* based on this case model. The plan items defined in the case model similarly have *plan item instance* runtime representations that are exposed by, and can be queried using, the Flowable API. Plan item instances have a state lifecycle that is defined in the CMMN 1.1 specification and is core to how the engine works. Please check out section 8.4.2 of the CMMN 1.1 specification for all the details. Plan items can have _sentries_: a plan item is said to have _entry criteria_ when a sentry ""guards"" its activation. These criteria specify conditions that must be satisfied to _trigger the sentry_. For example, in the figure above, the ""Milestone One"" plan item is _available_ after a case instance is started, but it is _activated_ (in CMMN 1.1 specification terminology: it moves from the _available_ state to the _active_ state) when both human task A and B are completed. Note that sentries can have complex expression in their _if part_, which are not visualized, allowing for much more complex functionality. Also note that there can be multiple sentries, although only one needs to be satisfied to trigger a state transition. Plan items and the plan model can also have sentries with _exit criteria_, which specify conditions that trigger an _exit_ from that particular plan item. In the figure above, the whole plan model is exited (as are all the child elements that are active at that moment), when human task C completes. CMMN 1.1 defines a standard XML format in an XSD that is part of the specification. For information, the example in the figure above is represented in XML as shown below. Some observations: * The four plan items above are in the XML and they reference their definition with a _definitionRef_. The actual definitions are at the bottom of the _casePlanModel_ element * The plan items have criteria (entry or exit) that reference a _sentry_ (not the other way around) * The XML also contains information on how the diagram is visualized (x and y coordinates, widths and heights, and so on), which are omitted below. These elements are important when exchanging case models with other CMMN 1.1 modeling tools to preserve the correct visual representation [source,xml,linenums] ---- complete complete complete ... ---- === Programmatic example In this section we're going to build a simple case model and execute it programmatically through the Java APIs of the Flowable CMMN engine in a simple command line example. The case model we'll build is a simplified _employee onboarding_ case with two stages: a phase before and phase after the potential employee has started. In the first stage, someone from the HR department will complete the tasks, while in the second stage it is the employee completing them. Also, at any point in time, the potential employee can reject the job and stop the whole case instance. Note that only stages and human tasks are used. In a real case model, there will most likely other plan item types too, such as milestones, nested stages, automated tasks, and so on. image::images/cmmn.programmatic.example.png[align=""center""] The XML for this case model is the following: [source,xml,linenums] ---- complete complete complete complete complete ---- First of all, create a new project and add the _flowable-cmmn-engine_ dependency (here shown for Maven). The H2 dependency is also added, as H2 will be used as embedded database later on. [source,xml,linenums] ---- org.flowable flowable-cmmn-engine ${flowable.version} com.h2database h2 ${h2.version} ---- The Flowable CMMN API is designed to be consistent with the other Flowable APIs and concepts. As such, people that know the BPMN or DMN APIs will have no problem finding their way around. As with the other engines, the first line of code is creating a CmmnEngine. Here, the default in-memory configuration is used, which uses H2 as the database: [source,java,linenums] ---- public class Main { public static void main(String[] args) { CmmnEngine cmmnEngine = new StandaloneInMemCmmnEngineConfiguration().buildCmmnEngine(); } } ---- Note that the _CmmnEngineConfiguration_ exposes many configuration options for tweaking various settings of the CMMN engine. Put the XML from above in a file, for example _my-case.cmmn_ (or .cmmn.xml). For Maven, it should be placed in the _src/main/resources_ folder. To make the engine aware of the case model, it first needs to be _deployed_. This is done through the _CmmnRepositoryService_: [source,java,linenums] ---- CmmnRepositoryService cmmnRepositoryService = cmmnEngine.getCmmnRepositoryService(); CmmnDeployment cmmnDeployment = cmmnRepositoryService.createDeployment() .addClasspathResource(""my-case.cmmn"") .deploy(); ---- Deploying the XML will return a *CmmnDeployment*. A deployment can contain many case models and artifacts. The specific case model definition above is stored as a *CaseDefinition*. This can be verified by doing a _CaseDefinitionQuery_: [source,java,linenums] ---- List caseDefinitions = cmmnRepositoryService.createCaseDefinitionQuery().list(); System.out.println(""Found "" + caseDefinitions.size() + "" case definitions""); ---- Having a *CaseDefinition* in the engine, it's now possible to start a *CaseInstance* for this case model definition. Either the result from the query is used and passed into the following snippet of code, or the _key_ of the case definition is used directly (as done below). Note that we're also passing data, an identifier to the _potentialEmployee_ as a variable when starting the *CaseInstance*. This variable will later be used in the human tasks to assign the task to the correct person (see the _assignee=""${potentialEmployee}""_ attribute on _human tasks_). [source,java,linenums] ---- CmmnRuntimeService cmmnRuntimeService = cmmnEngine.getCmmnRuntimeService(); CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder() .caseDefinitionKey(""employeeOnboarding"") .variable(""potentialEmployee"", ""johnDoe"") .start(); ---- After the *CaseInstance* is started, the engine will determine which of the plan items of the model should be activated: * The first stage has no entry criteria, so it's activated * The child human tasks of the first stage have no entry criteria, so three of them are expected to be active The plan items are represented at runtime by *PlanItemInstances* and can be queried through the _CmmnRuntimeService_: [source,java,linenums] ---- List planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery() .caseInstanceId(caseInstance.getId()) .orderByName().asc() .list(); for (PlanItemInstance planItemInstance : planItemInstances) { System.out.println(planItemInstance.getName()); } ---- which prints out ---- After starting Agree start date Allocate office Create email address Prior to starting Reject job Send joining letter to candidate ---- Some things might be unexpected here: * The stages are _also_ plan items and thus have a representation as *PlanItemInstance*. Note that that child plan item instances will have the stage as parent when calling _.getStageInstanceId()_. * The _Send joining letter to candidate_ is returned in the result. The reason is that, in accordance with the CMMN 1.1 specification, this plan item instance is in the _available_ state, but not yet in the _active_ state. Indeed, when the code above is changed to [source,java,linenums] ---- for (PlanItemInstance planItemInstance : planItemInstances) { System.out.println(planItemInstance.getName() + "", state="" + planItemInstance.getState() + "", parent stage="" + planItemInstance.getStageInstanceId()); } ---- The output now becomes: ---- After starting, state=available, parent stage=null Agree start date, state=active, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 Allocate office, state=active, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 Create email address, state=active, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 Prior to starting, state=active, parent stage=null Reject job, state=active, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 Send joining letter to candidate, state=available, parent stage=fe37ac97-b016-11e7-b3ad-acde48001122 ---- To only show the active plan item instances, the query can be adapted by adding _planItemInstanceStateActive()_: [source,java,linenums] ---- List planItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery() .caseInstanceId(caseInstance.getId()) .planItemInstanceStateActive() .orderByName().asc() .list(); ---- The output is now ---- Agree start date Allocate office Create email address Prior to starting Reject job ---- Of course, the *PlanItemInstance* is the low level representation, but each plan item also has a _plan item definition_ that defines what type it is. In this case, we only have _human tasks_. It is possible to interact with the _CaseInstance_ via its _plan item instances_, for example by triggering them programmatically (for example, _CmmnRuntimeService.triggerPlanItemInstance(String planItemInstanceId)_). However, most likely the interaction will happen through the results of the actual plan item definition: here, the human tasks. Querying for tasks is done in the exact same way as for the BPMN engine (in fact, the task service is a shared component and tasks created in BPMN or CMMN can be queried through both engines): [source,java,linenums] ---- CmmnTaskService cmmnTaskService = cmmnEngine.getCmmnTaskService(); List hrTasks = cmmnTaskService.createTaskQuery() .taskCandidateGroup(""hr"") .caseInstanceId(caseInstance.getId()) .orderByTaskName().asc() .list(); for (Task task : hrTasks) { System.out.println(""Task for HR : "" + task.getName()); } List employeeTasks = cmmnTaskService.createTaskQuery() .taskAssignee(""johndoe"") .orderByTaskName().asc() .list(); for (Task task : employeeTasks) { System.out.println(""Task for employee: "" + task); } ---- Which outputs: ---- Task for HR : Agree start date Task for HR : Allocate office Task for HR : Create email address Task for employee: Reject job ---- When the three tasks of HR are completed, the 'Send joining letter to candidate' task should be available: [source,java,linenums] ---- for (Task task : hrTasks) { cmmnTaskService.complete(task.getId()); } hrTasks = cmmnTaskService.createTaskQuery() .taskCandidateGroup(""hr"") .caseInstanceId(caseInstance.getId()) .orderByTaskName().asc() .list(); for (Task task : hrTasks) { System.out.println(""Task for HR : "" + task.getName()); } ---- And indeed, the expected task is now created: ---- Task for HR : Send joining letter to candidate ---- Completing this task will now move the case instance into the second stage, as the sentry for the first stage is satisfied. The 'Reject job' tasks is automatically completed by the system and the two tasks for the employee are created: [source,java,linenums] ---- Task for employee: Fill in paperwork Task for employee: New starter training Task for employee: Reject job ---- Completing all the tasks will end the case instance: ---- List tasks = cmmnTaskService.createTaskQuery().caseInstanceId(caseInstance.getId()).listPage(0, 1); while (!tasks.isEmpty()) { cmmnTaskService.complete(tasks.get(0).getId()); tasks = cmmnTaskService.createTaskQuery() .caseInstanceId(caseInstance.getId()) .listPage(0, 1); } ---- While executing case instances, the engine also stores historic information, which can be queried via a query API: [source,java,linenums] ---- CmmnHistoryService cmmnHistoryService = cmmnEngine.getCmmnHistoryService(); HistoricCaseInstance historicCaseInstance = cmmnHistoryService.createHistoricCaseInstanceQuery() .caseInstanceId(caseInstance.getId()) .singleResult(); System.out.println(""Case instance execution took "" + (historicCaseInstance.getEndTime().getTime() - historicCaseInstance.getStartTime().getTime()) + "" ms""); List historicTaskInstances = cmmnHistoryService.createHistoricTaskInstanceQuery() .caseInstanceId(caseInstance.getId()) .orderByTaskCreateTime().asc() .list(); for (HistoricTaskInstance historicTaskInstance : historicTaskInstances) { System.out.println(""Task completed: "" + historicTaskInstance.getName()); } ---- Which outputs: ---- Case instance execution took 149 ms Task completed: Reject job Task completed: Agree start date Task completed: Allocate office Task completed: Create email address Task completed: Send joining letter to candidate Task completed: New starter training Task completed: Fill in paperwork ---- Historic data related to the case execution is collected for special constructs, such as Tasks (as seen above), milestones, cases, variables and plan items in general. This data is persisted at the same time as the runtime data, but it is not deleted when case instances end. Access to the historic data is provided as query APIs by the _CmmnHistoryService_ Of course, this is but a small part of the available APIs and constructs available in the Flowable CMMN Engine. Please check the other sections for more detailed information === CMMN 1.1 Constructs This chapter covers the CMMN 1.1 constructs supported by Flowable, as well as extensions to the CMMN 1.1 standard. The following constructs, with the exception of sentries and item control, as for the CMMN specification are considered plan items. Historic data of their instances execution can be queried through the _CmmnHistoryService_ using _org.flowable.cmmn.api.history.HistoricPlanItemInstanceQuery_. ==== Stage A stage is used to group plan items together. It is typically used to define ""phases"" in a case instance. A stage is a plan item itself, and thus can have entry and exit criteria. Plan items contained within a stage are only available when the parent stage moves to the _active_ state. Stages can be nested in other stages. A stage is visualized as a rectangle with angled corners: image::images/cmmn.stage.png[align=""center""] ==== Task A ""manual"" task, meaning the task will happen external to the engine. Properties: * *name*: expression that will be resolved at runtime as the name of the manual task * *blocking*: a boolean value determining whether the task blocks * *blockingExpression*: an expression that evaluates to a boolean indicating whether the tasks blocks If a task is non-blocking, the engine will simply complete it automatically when executing it. If a task is blocking, a _PlanItemInstance_ for this task will remain in the _active_ state until it is programmatically triggered by the _CmmnRuntimeService.triggerPlanItemInstance(String planItemInstanceId)_ method. A task is visualized as a rounded rectangle: image::images/cmmn.task.png[align=""center""] ==== Human task A human task is used to model work that needs to be done by a human, typically through a form. When the engine arrives at a human task, a new entry is created in the task list of any users or groups assigned to that task. A human task is a plan item, which means that beyond a human task entry also a _PlanItemInstance_ is created and it can be queried via the _PlanItemInstanceQuery_. Human tasks can be queried through the _org.flowable.task.api.TaskQuery_ API. Historic task data can be queried through the _org.flowable.task.api.history.HistoricTaskInstanceQuery_. Properties: * *name*: expression that will be resolved at runtime as the name of the human task * *blocking*: a boolean value determining whether the task blocks * *blockingExpression*: an expression that evaluates to a boolean indicating whether the tasks blocks * *assignee* : an expression (can be a static text value) that is used to determine to whom the human task is assigned * *owner* : an expression (can be a static text value) that is used to determine who is the owner of the human task * *candidateUsers* : an expression (can be a static text value) that resolves to a comma-separated list of Strings that is used to determine which users are candidate for this human task * *candidateGroups* : an expression (can be a static text value) that resolves to a comma-separated list of Strings that is used to determine to which groups the task is assigned * *form key*: an expression that determines a key when using forms. Can be retrieved via the API afterwards * *Due date* an expression that resolves to java.util.Date or a ISO-8601 date string * *Priority*: an expression that resolves to an integer. Can be used in the TaskQuery API to filter tasks A human task is visualized as a rounded rectangle with a user icon in the top left corner: image::images/cmmn.humantask.png[align=""center""] ==== Java Service task A service task is used to execute custom logic. Custom logic is placed in a class that implements the _org.flowable.cmmn.api.delegate.PlanItemJavaDelegate_ interface. [source,java,linenums] ---- public class MyJavaDelegate implements PlanItemJavaDelegate { public void execute(DelegatePlanItemInstance planItemInstance) { String value = (String) planItemInstance.getVariable(""someVariable""); ... } } ---- For lower-level implementations that cannot be covered by using the _PlanItemJavaDelegate_ approach, the _CmmnActivityBehavior_ can be used (similar to _JavaDelegate_ vs _ActivityBehavior_ in the BPMN engine). Properties: * *name*: name of the service task * *class*: the Java class implementing the custom logic * *class fields*: parameters to pass when calling the custom logic * *Delegate expression*: an expression that resolves to a class implementing the _PlanItemJavaDelegate_ interface A service task is visualized as a rounded rectangle with a cog icon in the top left corner: image::images/cmmn.servicetask.png[align=""center""] ==== Decision task A _Decision task_ calls out to a DMN decision table and stores the resulting variable in the case instance. Properties: * *Decision table reference*: the referenced DMN decision table that needs to be invoked. It is also possible to throw an error when no rule is hit during the evaluation of the DMN decision table by setting the '_Throw error if no rules were hit_' property. A decision task is visualized as a _task_ with a table icon in the top left corner: image::images/cmmn.decisiontask.png[align=""center""] ==== Http Task The Http task is an out-of-the-box implementation of a _service task_. It is used when a REST service needs to be called over HTTP. The Http task has various options to customize the request and response. See the BPMN http task documentation for details on all the configuration options. A http task is visualized as a _task_ with a rocket icon in the top left corner: image::images/cmmn.httptask.png[align=""center""] ==== Script Task A task of type ""script"", similar to its equivalent in BPMN, the Script Task executes a script when the plan item instance becomes active. Properties: * *name*: task attribute to indicate the name of the task * *type*: task attribute whose value must be ""script"" to indicate the type of task * *scriptFormat*: extended attribute that indicate the language of the script (for example, javascript, groovy) * *script*: the script to execute, defined as a string in a extension field element named ""script"" * *autoStoreVariables*: optional task attribute flag (default: false) that indicates whether or not variables defined in the script will be stored in the Plan Item Instance context (see note below) * *resultVariableName*: optional task attribute that when present will store a variable with the specified name in the Plan Item instance context with the script evaluation result (see note below) A script task is visualized as a _task_ with a script icon in the top left corner: image::images/cmmn.scripttask.png[align=""center""] [source,xml,linenums] ---- Optional documentation sum = 0; for ( i in inputArray ) { sum += i; } ---- *Note*: The value of the *scriptFormat* attribute must be a name that is compatible with the link:$$http://jcp.org/en/jsr/detail?id=223$$[JSR-223] (scripting for the Java platform). By default, JavaScript is included in every JDK and as such doesn't need any additional JAR files. If you want to use another (JSR-223 compatible) scripting engine, it is sufficient to add the corresponding JAR to the classpath and use the appropriate name. For example, the Flowable unit tests often use Groovy because the syntax is similar to that of Java. Do note that the Groovy scripting engine is bundled with the groovy-jsr223 JAR. As such, one must add the following dependency: [source,xml,linenums] ---- org.codehaus.groovy groovy-jsr223 2.x.x ---- All case variables that are accessible through the PlanItem instance that arrives in the script task can be used within the script. In the example below, the script variable _'inputArray'_ is in fact a case variable (an array of integers). [source,xml,linenums] ---- sum = 0 for ( i in inputArray ) { sum += i } ---- *Note*: It's also possible to set process variables in a script, simply by calling _planItemInstance.setVariable(""variableName"", variableValue)_. By default, no variables are stored automatically. It's possible to automatically store any variable defined in the script (for example, __sum__ in the example above) by setting the property ++autoStoreVariables++ on the ++scriptTask++ to ++true++. However, *the best practice is not to do this and use an explicit execution.setVariable() call*, as with some recent versions of the JDK, auto storing of variables does not work for some scripting languages. See link:$$http://www.jorambarrez.be/blog/2013/03/25/bug-on-jdk-1-7-0_17-when-using-scripttask-in-activiti/$$[this link] for more details. [source,xml,linenums] ---- ---- The default for this parameter is +false+, meaning that if the parameter is omitted from the script task definition, all the declared variables will only exist during the duration of the script. Here's an example of how to set a variable in a script: [source,xml,linenums] ---- def scriptVar = ""test123"" planItemInstance.setVariable(""myVar"", scriptVar) ---- The following names are reserved and *cannot be used* as variable names: *out, out:print, lang:import, context, elcontext*. *Note* The return value of a script task can be assigned to an already existing or new process variable by specifying its name as a literal value for the _'flowable:resultVariable'_ attribute of a script task definition. Any existing value for a specific process variable will be overwritten by the result value of the script execution. When a result variable name is not specified, the script result value gets ignored. [source,xml,linenums] ---- #{echo} ---- In the above example, the result of the script execution (the value of the resolved expression __'#{echo}'__) is set to the process variable named __'myVar'__ after the script completes. ==== Milestone A milestone is used to mark arriving at a certain point in the case instance. At runtime, they are represented as *MilestoneInstances* and they can be queried through the *MilestoneInstanceQuery* via the _CmmnRuntimeService_. There is also a historical counterpart via the _CmmnHistoryService_. A milestone is a plan item, which means that as well as a milestone entry, a _PlanItemInstance_ is created also, which can be queried via the _PlanItemInstanceQuery_. Properties: * *name*: an expression or static text that determines the name of the milestone A milestone is visualized as a rounded rectangle (more rounded than a task): image::images/cmmn.milestone.png[align=""center""] ==== Case task A case task is used to start a child case within the context of another case. The _CaseInstanceQuery_ has _parent_ options to find these cases. When the case task is blocking, the _PlanItemInstance_ will be _active_ until the child case has completely finished. If the case task is non-blocking, the child case is started and the plan item instance automatically completes. When the child case instance ends there is no impact on the parent case. Properties: * *name*: an expression or static text that determines the name * *blocking*: a boolean value determining whether the task blocks * *blockingExpression*: an expression that evaluates to a boolean indicating whether the tasks blocks * *Case reference*: the key of the case definition that is used to start the child case instance. Can be an expression A case task is visualized as a rounded rectangle with a case icon in the top left corner: image::images/cmmn.casetask.png[align=""center""] ==== Process task A process task is used to start a process instance within the context of a case. When the process task is blocking, the _PlanItemInstance_ will be _active_ until the process instance has completely finished. If the process task is non-blocking, the process instance is started and the plan item instance automatically completes. When the process instance ends there is no impact on the parent case. Properties: * *name*: an expression or static text that determines the name * *blocking*: a boolean value determining whether the task blocks * *blockingExpression*: an expression that evaluates to a boolean indicating whether the tasks blocks * *Process reference*: the key of the process definition that is used to start the process instance. Can be an expression A process task is visualized as a rounded rectangle with an arrow icon in the top left corner: image::images/cmmn.processtask.png[align=""center""] ==== Criteria ===== Entry criterion Entry criteria form a sentry for a given plan item instance. They consist of two parts: * One or more parts that depend on other plan items: these define dependencies on state transitions of other plan items. For example, one human task can depend on the state transition 'complete' of three other human tasks to become active itself * One optional _if part_ or _condition_: this is an expression that allows the definition of a complex condition A sentry is satisfied when all its criteria are resolved to _true_. When a criterion evaluates to true, this is stored and remembered for future evaluations. Note that entry criteria of all plan item instances in the _available_ state are evaluated whenever something changes in the case instance. Multiple sentries are possible on a plan item. However, when one is satisfied, the plan item moves from state _available_ to _active_. An entry criterion is visualized as a diamond shape (white color inside) on the border of a plan item: image::images/cmmn.entrycriteria.png[align=""center""] ===== Exit criterion Exit criteria form a sentry for a given plan item instance. They consist of two parts: * One or more parts that depend on other plan items: these define dependencies on state transitions of other plan items. For example, one human task can depend on reaching a certain milestone to be automatically terminated * One optional _if part_ or _condition_: this is an expression that allows a complex condition to be defined A sentry is satisfied when all its criteria are resolved to _true_. When a criterion evaluates to true, this is stored and remembered for future evaluations. Note that exit criteria of all plan item instances in the _active_ state are evaluated whenever something changes in the case instance. Multiple sentries are possible on a plan item. However, when one is satisfied, the plan item moves from state _active_ to _exit_. An exit criterion is visualized as a diamond shape (white color inside) on the border of a plan item: image::images/cmmn.exitcriteria.png[align=""center""] ==== Event Listeners ===== Timer Event Listener A timer event listener is used when the passing of time needs to be captured in a case model. A timer event listener is not a task and has a simpler plan item lifecycle compared to a _task_: the timer will simply move from _available_ to _completed_ when the event (in this case, the time passing) occurs. Properties: * *Timer expression*: an expression that defines when the timer should occur. The following options are possible: ** An expression resolving to a java.util.Date or org.joda.time.DateTime instance (for example, _${someBean.calculateNextDate(someCaseInstanceVariable)}) ** An ISO8601 date ** An ISO8601 duration String (for example, _PT5H_, indicating the timer should fire in 5 hours from instantiation) ** AN ISO8601 repetition String (for example, R5/PT2H, indicating the timer should fire 5 times, each time waiting 2 hours) ** A String containing a cron expression * *Start trigger plan item/event*: reference to a plan item in the case model that triggers the start of the timer event listener Note that setting a _start trigger_ for the timer event listener does not have a visual indicator in the case model, unlike entry/exit criteria on sentries. A timer event listener is visualized as circle with a clock icon inside: image::images/cmmn.timereventlistener.png[align=""center""] ===== User Event Listener A user event listener can be used when needing to capture a user interaction that directly influences a case state, instead of indirectly via impacting variables or information in the case. When the event is captured an Occur transition is triggered on the event listener. Like timer event listeners, it has a much simpler lifecycle that a _task_. image::images/cmmn.usereventlistener.png[align=""center""] User event listeners can be queried using the _org.flowable.cmmn.api.runtime.UserEventListenerInstanceQuery_. Such a query can be created by calling the _cmmnRuntimeService.createUserEventListenerInstanceQuery()_ method. Note that a user event listener is also a plan item instance, which means it can also be queried through the _org.flowable.cmmn.api.runtime.PlanItemInstanceQuery_ API. A user event listener can be completed by calling the _cmmnRuntimeService.completeUserEventListenerInstance(id)_ method. ==== Item control: Repetition Rule Plan items on the case model can have a _repetition rule_: an expression that can be used to indicate a certain plan item needs to be repeated. When no expression is set, but the repetition is enabled (for example, the checkbox is checked in the Flowable Modeler) or the expression is empty, a _true_ value is assumed by default. An optional _repetition counter variable_ can be set, which holds the index (one-based) of the instance. If not set, the default variable name is _repeitionCounter_. If the plan item does not have any entry criteria, the repetition rule expression is evaluated when the plan item is completed or terminated. If the expression resolved to _true_, a new instance is created. For example, a human task with a repetition rule expression _${repetitionCounter < 3}_, will create three sequential human tasks. If the plan item has entry criteria, the behavior is different. The repetition rule is not evaluated on completion or termination, but when a sentry of the plan item is satisfied. If both the sentry is satisfied and the repetition rule evaluates to true, a new instance is created. Take, for example, the following timer event listener followed by a human task. The sentry has one entry criterion for the _occur_ event of the timer event listener. Note that enabling and setting the repetition rule on the task has a visual indicator at the bottom of the rectangle. image::images/cmmn.repeatingtimereventlistener.png[align=""center""] If the timer event listener is repeating (for example, _R/PT1H_), the _occur_ event will be fired every hour. When the repetition rule expression of the human task evaluates to true, a new human task instance will be created each hour. ==== Item control: Manual Activation Rule Plan items on the case model can have a _manual activation rule_: an expression that can be used to indicate a certain plan item needs to be _manually activated by an end-user_. When no expression is set, but the manual activation is enabled (for example, the checkbox is checked in the Flowable Modeler) or the expression is empty, a _true_ value is assumed by default. Stages and all task types can be marked for manual activation. Visually, the task or stage will get a 'play' icon (small triangle pointing to the right) to indicate an end-user will have to manually activate it: image::images/cmmn.manual-activation.png[align=""center""] Normally, when a sentry for a plan item is satisfied (or the plan item doesn't have any sentries) the plan item instance is automatically moved to the _ACTIVE_ state. When a manual activation is set though, and it evaluates to true, the plan item instance now becomes _ENABLED_ instead of _ACTIVE_. As the name implies, the idea behind this is that end-users manually have to activate the plan item instance. A typical use case is showing a list of buttons of potential plan item instances that can currently be started by the end user. To start an enabled plan item instance, the _startPlanItemInstance_ method of the _CmmnRuntimeService_ can be used: [source,java,linenums] ---- List enabledPlanItemInstances = cmmnRuntimeService.createPlanItemInstanceQuery() .caseInstanceId(caseInstance.getId()) .planItemInstanceStateEnabled() .list(); // ... cmmnRuntimeService.startPlanItemInstance(planItemInstance.getId()); ---- Note that the behavior of a task is only executed when the plan item instance moves into the _ACTIVE_ state. For example, for a human task, the user task will only be created after calling the _startPlanItemInstance_ method. Plan item instances that are enabled can be moved into the _DISABLED_ state: [source,java,linenums] ---- cmmnRuntimeService.disablePlanItemInstance(planItemInstance.getId()); ---- Disabled plan item instances can be enabled again: [source,java,linenums] ---- cmmnRuntimeService.enablePlanItemInstance(planItemInstance.getId()); ---- Note that with regards to determining stage or case instance termination, the _DISABLED_ state is seen as a 'terminal' state. This means that the case instance will terminate when only disabled plan item instances would remain. ==== Item control: Required Rule Plan items on the case model can have a _required rule_: an expression that can be used to indicate a certain plan item is _required by the enclosing stage (or plan model)_. This can be used to indicate which plan items of the case model are required to be executed and which are optional. When no expression is set, but the required rule is enabled (for example, the checkbox is checked in the Flowable Modeler) or the expression is empty, a _true_ value is assumed by default. The _required rule_ works in conjunction with the _autoComplete_ attribute on the parent stage: * If _autoComplete_ resolves to _false_ for the stage, which is also the default when nothing is set, *all* child plan item instances must be in an end state (completed, terminated, and so on) for the stage plan item instance to be completed by the engine * If _autoComplete_ resolves to _true_ for the stage, all child plan item instances for *which the required rule evaluates to true* need to be in an end state. If there are also no other active child plan item instances, the stage completes automatically A _stage plan item instance_ has a *completeable* property that can be used to see whether or not the conditions for completion are satisfied. Take, for example, the following simple stage and assume that the sentry for the _required task_ evaluates to true and the other one to false. This means that the left plan item instance will be active while the right one will be in the _available_ state. image::images/cmmn.completeable-stage.png[align=""center""] Calling _cmmnRuntimeService.completeStagePlanItemInstance(String stagePlanItemInstanceId)_ will not be possible for the stage (an exception will be thrown) as it has one active child plan item instance. When this user task on the left is completed, the _completeStagePlanItemInstance_ can now be called, as no child plan item instances are currently active. However, by itself, the stage will not automatically complete as the right user task is in the available state. If the previous stage is changed to be *autoCompleteable* (this is visualised by a black rectangle at the bottom of the stage) and the plan item on the left is changed to be required (this is visualised using an exclamation mark), the behavior will be different: image::images/cmmn.completeable-stage02.png[align=""center""] * If the left plan item instance is active (sentry is true) and the right is not (sentry is false). In this case, when the left user task is completed, the stage instance will auto complete as it has no active child plan item instances and all required plan item instances are in an end state * If both the left and right user tasks are active (sentries are true) ** When the left user task is completed, the stage will not autocomplete as there is still a child plan item instance active ** When the right user task is completed, the stage will not autocomplete as the required left child plan item instance is not in an end state * If the left plan item instance is not active and the right is active. In this case, when the right user task is completed the stage will not autocomplete, as the required left user task is not in an end state. It will need to become active and be completed to complete the stage. Note that the manual activation rule works independently of the required rule. For example, given the following stage: image::images/cmmn.completeable-stage03.png[align=""center""] Here, user task D is required and user task B is manually activated. * If D is completed, the stage will automatically complete, as B is not required and it is not active * If B would be required too, it would need to be manually started (using _cmmnRuntimeService.startPlanItemInstance(String planItemInstanceId)_) before the stage would automatically complete, even if D would be completed before the manual start of B ==== Item control: Completion Neutral Rule Plan items on the case model can have a _completion neutral rule_: an expression that can be used to indicate a certain plan item is _neutral with regards to the completion of its parent stage (or plan model)_. This can be used to indicate which plan items of the case model are required to be executed and which are optional, as a more flexible alternative in some use cases to using the _required rule_ and _autoComplete_ . Note that the _Completion Neutral Rule_ is not a CMMN 1.1 Standard, but a Flowable-specific addition. Following the specification, a stage with a plan item in state *AVAILABLE* does not complete unless its _autoComplete_ attribute is set _true_ and the plan item is not required. For example, a plan item that has an unsatisfied sentry remains in *AVAILABLE* until the sentry is satisfied. This means that the parent stage would not complete, unless the plan item is marked as _not required_ and the stage is set to _autoComplete_. The downside is that once a stage is marked as to autoComplete, all child plan items need to have a configuration for the _required_ rule, which is in some use cases tedious and lots of work. The _Completion Neutral Rule_, contrary to the autoComplete-required mechanism, works from ""bottom-up"": a plan item can be marked individually to be _neutral wrt the completion of its parent_ without having to mark any other plan item. The _Required Rule_ takes precedence when plan items with both rules both evaluate to _true_. To summarize: * a plan item configured to be _""completion neutral""_ will allow a stage to complete automatically if it's in *AVAILABLE* state (e.g. waiting for an entry criterion sentry),meaning that such a plan item is neutral with respect to its parent stage completion evaluation. * a stage will remain *ACTIVE* on any of these conditions: 1. It has at least one plan item in *ACTIVE* state 2. It has at least one plan item with _requiredRule_ in *AVAILABLE* or *ENABLE* state 3. It is not marked as _autoComplete_ and has at least one plan item in *ENABLED* state (irrespective of its _requiredRule_) 4. It is not marked as _autoComplete_ and has at least one plan item in *AVAILABLE* state that is *not* _completionNeutral_ * a stage will *COMPLETE* if: 1. It contains no plan items or all child plan items are in a _Terminal_ or _Semi-terminal_ state (CLOSED, COMPLETED, DISABLED, FAILED) 2. It is not marked as _autoComplete_ and all remaining child plan items are in *AVAILABLE* state and are _completionNeutral_ and not _required_ 3. It is _autoComplete_ and all remaining plan items are _not required_ in *ENABLED* or *AVAILABLE* state (regardless of its completion neutrality, as required rule gets precedence) ",12484,False,1882.3808372921485,median "= AddressBook Level 4 - Developer Guide :site-section: DeveloperGuide :toc: :toc-title: :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: :experimental: endif::[] :repoURL: https://github.com/se-edu/addressbook-level4/tree/master By: `Team SE-EDU`      Since: `Jun 2016`      Licence: `MIT` == Setting up === Prerequisites . *JDK `9`* or later + [WARNING] JDK `10` on Windows will fail to run tests in <> due to a https://github.com/javafxports/openjdk-jfx/issues/66[JavaFX bug]. Windows developers are highly recommended to use JDK `9`. . *IntelliJ* IDE + [NOTE] IntelliJ by default has Gradle and JavaFx plugins installed. + Do not disable them. If you have disabled them, go to `File` > `Settings` > `Plugins` to re-enable them. === Setting up the project in your computer . Fork this repo, and clone the fork to your computer . Open IntelliJ (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project dialog first) . Set up the correct JDK version for Gradle .. Click `Configure` > `Project Defaults` > `Project Structure` .. Click `New...` and find the directory of the JDK . Click `Import Project` . Locate the `build.gradle` file and select it. Click `OK` . Click `Open as Project` . Click `OK` to accept the default settings . Open a console and run the command `gradlew processResources` (Mac/Linux: `./gradlew processResources`). It should finish with the `BUILD SUCCESSFUL` message. + This will generate all resources required by the application and tests. . Open link:{repoURL}/src/main/java/seedu/address/ui/MainWindow.java[`MainWindow.java`] and check for any code errors .. Due to an ongoing https://youtrack.jetbrains.com/issue/IDEA-189060[issue] with some of the newer versions of IntelliJ, code errors may be detected even if the project can be built and run successfully .. To resolve this, place your cursor over any of the code section highlighted in red. Press kbd:[ALT + ENTER], and select `Add '--add-modules=...' to module compiler options` for each error . Repeat this for the test folder as well (e.g. check link:{repoURL}/src/test/java/seedu/address/ui/HelpWindowTest.java[`HelpWindowTest.java`] for code errors, and if so, resolve it the same way) === Verifying the setup . Run the `seedu.address.MainApp` and try a few commands . <> to ensure they all pass. === Configurations to do before writing code ==== Configuring the coding style This project follows https://github.com/oss-generic/process/blob/master/docs/CodingStandards.adoc[oss-generic coding standards]. IntelliJ's default style is mostly compliant with ours but it uses a different import order from ours. To rectify, . Go to `File` > `Settings...` (Windows/Linux), or `IntelliJ IDEA` > `Preferences...` (macOS) . Select `Editor` > `Code Style` > `Java` . Click on the `Imports` tab to set the order * For `Class count to use import with '\\*'` and `Names count to use static import with '*'`: Set to `999` to prevent IntelliJ from contracting the import statements * For `Import Layout`: The order is `import static all other imports`, `import java.\\*`, `import javax.*`, `import org.\\*`, `import com.*`, `import all other imports`. Add a `` between each `import` Optionally, you can follow the <> document to configure Intellij to check style-compliance as you write code. ==== Updating documentation to match your fork After forking the repo, the documentation will still have the SE-EDU branding and refer to the `se-edu/addressbook-level4` repo. If you plan to develop this fork as a separate product (i.e. instead of contributing to `se-edu/addressbook-level4`), you should do the following: . Configure the <> in link:{repoURL}/build.gradle[`build.gradle`], such as the `site-name`, to suit your own project. . Replace the URL in the attribute `repoURL` in link:{repoURL}/docs/DeveloperGuide.adoc[`DeveloperGuide.adoc`] and link:{repoURL}/docs/UserGuide.adoc[`UserGuide.adoc`] with the URL of your fork. ==== Setting up CI Set up Travis to perform Continuous Integration (CI) for your fork. See <> to learn how to set it up. After setting up Travis, you can optionally set up coverage reporting for your team fork (see <>). [NOTE] Coverage reporting could be useful for a team repository that hosts the final version but it is not that useful for your personal fork. Optionally, you can set up AppVeyor as a second CI (see <>). [NOTE] Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based) ==== Getting started with coding When you are ready to start coding, 1. Get some sense of the overall design by reading <>. 2. Take a look at <>. == Design [[Design-Architecture]] === Architecture .Architecture Diagram image::Architecture.png[width=""600""] The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component. [TIP] The `.pptx` files used to create diagrams in this document can be found in the link:{repoURL}/docs/diagrams/[diagrams] folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose `Save as picture`. `Main` has only one class called link:{repoURL}/src/main/java/seedu/address/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. Two of those classes play important roles at the architecture level. * `EventsCenter` : This class (written using https://github.com/google/guava/wiki/EventBusExplained[Google's Event Bus library]) is used by components to communicate with other components using events (i.e. a form of _Event Driven_ design) * `LogsCenter` : Used by many classes to write log messages to the App's log file. The rest of the App consists of four components. * <>: The UI of the App. * <>: The command executor. * <>: Holds the data of the App in-memory. * <>: 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 it's API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class. .Class Diagram of the Logic Component image::LogicClassDiagram.png[width=""800""] [discrete] ==== Events-Driven nature of the design The _Sequence Diagram_ below shows how the components interact for the scenario where the user issues the command `delete 1`. .Component interactions for `delete 1` command (part 1) image::SDforDeletePerson.png[width=""800""] [NOTE] Note how the `Model` simply raises a `AddressBookChangedEvent` when the Address Book data are changed, instead of asking the `Storage` to save the updates to the hard disk. The diagram below shows how the `EventsCenter` reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time. .Component interactions for `delete 1` command (part 2) image::SDforDeletePersonEventHandling.png[width=""800""] [NOTE] Note how the event is propagated through the `EventsCenter` to the `Storage` and `UI` without `Model` having to be coupled to either of them. This is an example of how this Event Driven approach helps us reduce direct coupling between components. The sections below give more details of each component. [[Design-Ui]] === UI component .Structure of the UI Component image::UiClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/ui/Ui.java[`Ui.java`] The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `PersonListPanel`, `StatusBarFooter`, `BrowserPanel` 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/address/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. * Binds itself to some data in the `Model` so that the UI can auto-update when data in the `Model` change. * Responds to events raised from various parts of the App and updates the UI accordingly. [[Design-Logic]] === Logic component [[fig-LogicClassDiagram]] .Structure of the Logic Component image::LogicClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/logic/Logic.java[`Logic.java`] . `Logic` uses the `AddressBookParser` class to parse the user command. . This results in a `Command` object which is executed by the `LogicManager`. . The command execution can affect the `Model` (e.g. adding a person) and/or raise events. . The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`. Given below is the Sequence Diagram for interactions within the `Logic` component for the `execute(""delete 1"")` API call. .Interactions Inside the Logic Component for the `delete 1` Command image::DeletePersonSdForLogic.png[width=""800""] [[Design-Model]] === Model component .Structure of the Model Component image::ModelClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model.java`] The `Model`, * stores a `UserPref` object that represents the user's preferences. * stores the Address Book 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. [NOTE] As a more OOP model, we can store a `Tag` list in `Address Book`, which `Person` can reference. This would allow `Address Book` to only require one `Tag` object per unique `Tag`, instead of each `Person` needing their own `Tag` object. An example of how such a model may look like is given below. + + image:ModelClassBetterOopDiagram.png[width=""800""] [[Design-Storage]] === Storage component .Structure of the Storage Component image::StorageClassDiagram.png[width=""800""] *API* : link:{repoURL}/src/main/java/seedu/address/storage/Storage.java[`Storage.java`] The `Storage` component, * can save `UserPref` objects in json format and read it back. * can save the Address Book data in json format and read it back. [[Design-Commons]] === Common classes Classes used by multiple components are in the `seedu.addressbook.commons` package. == Implementation This section describes some noteworthy details on how certain features are implemented. // tag::undoredo[] === Undo/Redo feature ==== Current Implementation The undo/redo mechanism is facilitated by `VersionedAddressBook`. It extends `AddressBook` with an undo/redo history, stored internally as an `addressBookStateList` and `currentStatePointer`. Additionally, it implements the following operations: * `VersionedAddressBook#commit()` -- Saves the current address book state in its history. * `VersionedAddressBook#undo()` -- Restores the previous address book state from its history. * `VersionedAddressBook#redo()` -- Restores a previously undone address book state from its history. These operations are exposed in the `Model` interface as `Model#commitAddressBook()`, `Model#undoAddressBook()` and `Model#redoAddressBook()` respectively. Given below is an example usage scenario and how the undo/redo mechanism behaves at each step. Step 1. The user launches the application for the first time. The `VersionedAddressBook` will be initialized with the initial address book state, and the `currentStatePointer` pointing to that single address book state. image::UndoRedoStartingStateListDiagram.png[width=""800""] Step 2. The user executes `delete 5` command to delete the 5th person in the address book. The `delete` command calls `Model#commitAddressBook()`, causing the modified state of the address book after the `delete 5` command executes to be saved in the `addressBookStateList`, and the `currentStatePointer` is shifted to the newly inserted address book state. image::UndoRedoNewCommand1StateListDiagram.png[width=""800""] Step 3. The user executes `add n/David ...` to add a new person. The `add` command also calls `Model#commitAddressBook()`, causing another modified address book state to be saved into the `addressBookStateList`. image::UndoRedoNewCommand2StateListDiagram.png[width=""800""] [NOTE] If a command fails its execution, it will not call `Model#commitAddressBook()`, so the address book state will not be saved into the `addressBookStateList`. Step 4. The user now decides that adding the person was a mistake, and decides to undo that action by executing the `undo` command. The `undo` command will call `Model#undoAddressBook()`, which will shift the `currentStatePointer` once to the left, pointing it to the previous address book state, and restores the address book to that state. image::UndoRedoExecuteUndoStateListDiagram.png[width=""800""] [NOTE] If the `currentStatePointer` is at index 0, pointing to the initial address book state, then there are no previous address book states to restore. The `undo` command uses `Model#canUndoAddressBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the undo. The following sequence diagram shows how the undo operation works: image::UndoRedoSequenceDiagram.png[width=""800""] The `redo` command does the opposite -- it calls `Model#redoAddressBook()`, which shifts the `currentStatePointer` once to the right, pointing to the previously undone state, and restores the address book to that state. [NOTE] If the `currentStatePointer` is at index `addressBookStateList.size() - 1`, pointing to the latest address book state, then there are no undone address book states to restore. The `redo` command uses `Model#canRedoAddressBook()` to check if this is the case. If so, it will return an error to the user rather than attempting to perform the redo. Step 5. The user then decides to execute the command `list`. Commands that do not modify the address book, such as `list`, will usually not call `Model#commitAddressBook()`, `Model#undoAddressBook()` or `Model#redoAddressBook()`. Thus, the `addressBookStateList` remains unchanged. image::UndoRedoNewCommand3StateListDiagram.png[width=""800""] Step 6. The user executes `clear`, which calls `Model#commitAddressBook()`. Since the `currentStatePointer` is not pointing at the end of the `addressBookStateList`, all address book states after the `currentStatePointer` will be purged. We designed it this way because it no longer makes sense to redo the `add n/David ...` command. This is the behavior that most modern desktop applications follow. image::UndoRedoNewCommand4StateListDiagram.png[width=""800""] The following activity diagram summarizes what happens when a user executes a new command: image::UndoRedoActivityDiagram.png[width=""650""] ==== Design Considerations ===== Aspect: How undo & redo executes * **Alternative 1 (current choice):** Saves the entire address book. ** Pros: Easy to implement. ** Cons: May have performance issues in terms of memory usage. * **Alternative 2:** Individual command knows how to undo/redo by itself. ** Pros: Will use less memory (e.g. for `delete`, just save the person being deleted). ** Cons: We must ensure that the implementation of each individual command are correct. ===== Aspect: Data structure to support the undo/redo commands * **Alternative 1 (current choice):** Use a list to store the history of address book states. ** Pros: Easy for new Computer Science student undergraduates to understand, who are likely to be the new incoming developers of our project. ** Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update both `HistoryManager` and `VersionedAddressBook`. * **Alternative 2:** Use `HistoryManager` for undo/redo ** Pros: We do not need to maintain a separate list, and just reuse what is already in the codebase. ** Cons: Requires dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as `HistoryManager` now needs to do two different things. // end::undoredo[] // tag::dataencryption[] === [Proposed] Data Encryption _{Explain here how the data encryption feature will be implemented}_ // end::dataencryption[] === 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 We use asciidoc for writing documentation. [NOTE] We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting. === Editing Documentation See <> to learn how to render `.adoc` files locally to preview the end result of your edits. Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your `.adoc` files in real-time. === Publishing Documentation See <> to learn how to deploy GitHub Pages using Travis. === Converting Documentation to PDF format We use https://www.google.com/chrome/browser/desktop/[Google Chrome] for converting documentation to PDF format, as Chrome's PDF engine preserves hyperlinks used in webpages. Here are the steps to convert the project documentation files to PDF format. . Follow the instructions in <> to convert the AsciiDoc files in the `docs/` directory to HTML format. . Go to your generated HTML files in the `build/docs` folder, right click on them and select `Open with` -> `Google Chrome`. . Within Chrome, click on the `Print` option in Chrome's menu. . Set the destination to `Save as PDF`, then click `Save` to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below. .Saving documentation as PDF files in Chrome image::chrome_save_as_pdf.png[width=""300""] [[Docs-SiteWideDocSettings]] === Site-wide Documentation Settings The link:{repoURL}/build.gradle[`build.gradle`] file specifies some project-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how all documentation files within this project are rendered. [TIP] Attributes left unset in the `build.gradle` file will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of site-wide attributes |=== |Attribute name |Description |Default value |`site-name` |The name of the website. If set, the name will be displayed near the top of the page. |_not set_ |`site-githuburl` |URL to the site's repository on https://github.com[GitHub]. Setting this will add a ""View on GitHub"" link in the navigation bar. |_not set_ |`site-seedu` |Define this attribute if the project is an official SE-EDU project. This will render the SE-EDU navigation bar at the top of the page, and add some SE-EDU-specific navigation items. |_not set_ |=== [[Docs-PerFileDocSettings]] === Per-file Documentation Settings Each `.adoc` file may also specify some file-specific https://asciidoctor.org/docs/user-manual/#attributes[asciidoc attributes] which affects how the file is rendered. Asciidoctor's https://asciidoctor.org/docs/user-manual/#builtin-attributes[built-in attributes] may be specified and used as well. [TIP] Attributes left unset in `.adoc` files will use their *default value*, if any. [cols=""1,2a,1"", options=""header""] .List of per-file attributes, excluding Asciidoctor's built-in attributes |=== |Attribute name |Description |Default value |`site-section` |Site section that the document belongs to. This will cause the associated item in the navigation bar to be highlighted. One of: `UserGuide`, `DeveloperGuide`, ``LearningOutcomes``{asterisk}, `AboutUs`, `ContactUs` _{asterisk} Official SE-EDU projects only_ |_not set_ |`no-site-header` |Set this attribute to remove the site navigation bar. |_not set_ |=== === Site Template The files in link:{repoURL}/docs/stylesheets[`docs/stylesheets`] are the https://developer.mozilla.org/en-US/docs/Web/CSS[CSS stylesheets] of the site. You can modify them to change some properties of the site's design. The files in link:{repoURL}/docs/templates[`docs/templates`] controls the rendering of `.adoc` files into HTML5. These template files are written in a mixture of https://www.ruby-lang.org[Ruby] and http://slim-lang.com[Slim]. [WARNING] ==== Modifying the template files in link:{repoURL}/docs/templates[`docs/templates`] requires some knowledge and experience with Ruby and Asciidoctor's API. You should only modify them if you need greater control over the site's layout than what stylesheets can provide. The SE-EDU team does not provide support for modified template files. ==== [[Testing]] == Testing === Running Tests There are three ways to run tests. [TIP] The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies. *Method 1: Using IntelliJ JUnit test runner* * To run all tests, right-click on the `src/test/java` folder and choose `Run 'All Tests'` * To run a subset of tests, you can right-click on a test package, test class, or a test and choose `Run 'ABC'` *Method 2: Using Gradle* * Open a console and run the command `gradlew clean allTests` (Mac/Linux: `./gradlew clean allTests`) [NOTE] See <> for more info on how to run tests using Gradle. *Method 3: Using Gradle (headless)* Thanks to the https://github.com/TestFX/TestFX[TestFX] library we use, our GUI tests can be run in the _headless_ mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running. To run tests in headless mode, open a console and run the command `gradlew clean headless allTests` (Mac/Linux: `./gradlew clean headless allTests`) === Types of tests We have two types of tests: . *GUI Tests* - These are tests involving the GUI. They include, .. _System Tests_ that test the entire App by simulating user actions on the GUI. These are in the `systemtests` package. .. _Unit tests_ that test the individual components. These are in `seedu.address.ui` package. . *Non-GUI Tests* - These are tests not involving the GUI. They include, .. _Unit tests_ targeting the lowest level methods/classes. + e.g. `seedu.address.commons.StringUtilTest` .. _Integration tests_ that are checking the integration of multiple code units (those code units are assumed to be working). + e.g. `seedu.address.storage.StorageManagerTest` .. Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together. + e.g. `seedu.address.logic.LogicManagerTest` === Troubleshooting Testing **Problem: `HelpWindowTest` fails with a `NullPointerException`.** * Reason: One of its dependencies, `HelpWindow.html` in `src/main/resources/docs` is missing. * Solution: Execute Gradle task `processResources`. == Dev Ops === Build Automation See <> to learn how to use Gradle for build automation. === Continuous Integration We use https://travis-ci.org/[Travis CI] and https://www.appveyor.com/[AppVeyor] to perform _Continuous Integration_ on our projects. See <> and <> for more details. === Coverage Reporting We use https://coveralls.io/[Coveralls] to track the code coverage of our projects. See <> for more details. === Documentation Previews When a pull request has changes to asciidoc files, you can use https://www.netlify.com/[Netlify] to see a preview of how the HTML version of those asciidoc files will look like when the pull request is merged. See <> for more details. === Making a Release Here are the steps to create a new release. . Update the version number in link:{repoURL}/src/main/java/seedu/address/MainApp.java[`MainApp.java`]. . Generate a JAR file <>. . Tag the repo with the version number. e.g. `v0.1` . https://help.github.com/articles/creating-releases/[Create a new release using GitHub] and upload the JAR file you created. === Managing Dependencies A project often depends on third-party libraries. For example, Address Book depends on the https://github.com/FasterXML/jackson[Jackson library] for JSON parsing. Managing these _dependencies_ can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives: [loweralpha] . Include those libraries in the repo (this bloats the repo size) . Require developers to download those libraries manually (this creates extra work for developers) [[GetStartedProgramming]] [appendix] == Suggested Programming Tasks to Get Started Suggested path for new programmers: 1. First, add small local-impact (i.e. the impact of the change does not go beyond the component) enhancements to one component at a time. Some suggestions are given in <>. 2. Next, add a feature that touches multiple components to learn how to implement an end-to-end feature across all components. <> explains how to go about adding such a feature. [[GetStartedProgramming-EachComponent]] === Improving each component Each individual exercise in this section is component-based (i.e. you would not need to modify the other components to get it to work). [discrete] ==== `Logic` component *Scenario:* You are in charge of `logic`. During dog-fooding, your team realize that it is troublesome for the user to type the whole command in order to execute a command. Your team devise some strategies to help cut down the amount of typing necessary, and one of the suggestions was to implement aliases for the command words. Your job is to implement such aliases. [TIP] Do take a look at <> before attempting to modify the `Logic` component. . Add a shorthand equivalent alias for each of the individual commands. For example, besides typing `clear`, the user can also type `c` to remove all persons in the list. + **** * Hints ** Just like we store each individual command word constant `COMMAND_WORD` inside `*Command.java` (e.g. link:{repoURL}/src/main/java/seedu/address/logic/commands/FindCommand.java[`FindCommand#COMMAND_WORD`], link:{repoURL}/src/main/java/seedu/address/logic/commands/DeleteCommand.java[`DeleteCommand#COMMAND_WORD`]), you need a new constant for aliases as well (e.g. `FindCommand#COMMAND_ALIAS`). ** link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] is responsible for analyzing command words. * Solution ** Modify the switch statement in link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser#parseCommand(String)`] such that both the proper command word and alias can be used to execute the same intended command. ** Add new tests for each of the aliases that you have added. ** Update the user guide to document the new aliases. ** See this https://github.com/se-edu/addressbook-level4/pull/785[PR] for the full solution. **** [discrete] ==== `Model` component *Scenario:* You are in charge of `model`. One day, the `logic`-in-charge approaches you for help. He wants to implement a command such that the user is able to remove a particular tag from everyone in the address book, but the model API does not support such a functionality at the moment. Your job is to implement an API method, so that your teammate can use your API to implement his command. [TIP] Do take a look at <> before attempting to modify the `Model` component. . Add a `removeTag(Tag)` method. The specified tag will be removed from everyone in the address book. + **** * Hints ** The link:{repoURL}/src/main/java/seedu/address/model/Model.java[`Model`] and the link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] API need to be updated. ** Think about how you can use SLAP to design the method. Where should we place the main logic of deleting tags? ** Find out which of the existing API methods in link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] and link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] classes can be used to implement the tag removal logic. link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`] allows you to update a person, and link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] allows you to update the tags. * Solution ** Implement a `removeTag(Tag)` method in link:{repoURL}/src/main/java/seedu/address/model/AddressBook.java[`AddressBook`]. Loop through each person, and remove the `tag` from each person. ** Add a new API method `deleteTag(Tag)` in link:{repoURL}/src/main/java/seedu/address/model/ModelManager.java[`ModelManager`]. Your link:{repoURL}/src/main/java/seedu/address/model/ModelManager.java[`ModelManager`] should call `AddressBook#removeTag(Tag)`. ** Add new tests for each of the new public methods that you have added. ** See this https://github.com/se-edu/addressbook-level4/pull/790[PR] for the full solution. **** [discrete] ==== `Ui` component *Scenario:* You are in charge of `ui`. During a beta testing session, your team is observing how the users use your address book application. You realize that one of the users occasionally tries to delete non-existent tags from a contact, because the tags all look the same visually, and the user got confused. Another user made a typing mistake in his command, but did not realize he had done so because the error message wasn't prominent enough. A third user keeps scrolling down the list, because he keeps forgetting the index of the last person in the list. Your job is to implement improvements to the UI to solve all these problems. [TIP] Do take a look at <> before attempting to modify the `UI` component. . Use different colors for different tags inside person cards. For example, `friends` tags can be all in brown, and `colleagues` tags can be all in yellow. + **Before** + image::getting-started-ui-tag-before.png[width=""300""] + **After** + image::getting-started-ui-tag-after.png[width=""300""] + **** * Hints ** The tag labels are created inside link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[the `PersonCard` constructor] (`new Label(tag.tagName)`). https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Label.html[JavaFX's `Label` class] allows you to modify the style of each Label, such as changing its color. ** Use the .css attribute `-fx-background-color` to add a color. ** You may wish to modify link:{repoURL}/src/main/resources/view/DarkTheme.css[`DarkTheme.css`] to include some pre-defined colors using css, especially if you have experience with web-based css. * Solution ** You can modify the existing test methods for `PersonCard` 's to include testing the tag's color as well. ** See this https://github.com/se-edu/addressbook-level4/pull/798[PR] for the full solution. *** The PR uses the hash code of the tag names to generate a color. This is deliberately designed to ensure consistent colors each time the application runs. You may wish to expand on this design to include additional features, such as allowing users to set their own tag colors, and directly saving the colors to storage, so that tags retain their colors even if the hash code algorithm changes. **** . Modify link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] such that link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay`] can show a different style on error (currently it shows the same regardless of errors). + **Before** + image::getting-started-ui-result-before.png[width=""200""] + **After** + image::getting-started-ui-result-after.png[width=""200""] + **** * Hints ** link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] is raised by link:{repoURL}/src/main/java/seedu/address/ui/CommandBox.java[`CommandBox`] which also knows whether the result is a success or failure, and is caught by link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay`] which is where we want to change the style to. ** Refer to link:{repoURL}/src/main/java/seedu/address/ui/CommandBox.java[`CommandBox`] for an example on how to display an error. * Solution ** Modify link:{repoURL}/src/main/java/seedu/address/commons/events/ui/NewResultAvailableEvent.java[`NewResultAvailableEvent`] 's constructor so that users of the event can indicate whether an error has occurred. ** Modify link:{repoURL}/src/main/java/seedu/address/ui/ResultDisplay.java[`ResultDisplay#handleNewResultAvailableEvent(NewResultAvailableEvent)`] to react to this event appropriately. ** You can write two different kinds of tests to ensure that the functionality works: *** The unit tests for `ResultDisplay` can be modified to include verification of the color. *** The system tests link:{repoURL}/src/test/java/systemtests/AddressBookSystemTest.java[`AddressBookSystemTest#assertCommandBoxShowsDefaultStyle() and AddressBookSystemTest#assertCommandBoxShowsErrorStyle()`] to include verification for `ResultDisplay` as well. ** See this https://github.com/se-edu/addressbook-level4/pull/799[PR] for the full solution. *** Do read the commits one at a time if you feel overwhelmed. **** . Modify the link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] to show the total number of people in the address book. + **Before** + image::getting-started-ui-status-before.png[width=""500""] + **After** + image::getting-started-ui-status-after.png[width=""500""] + **** * Hints ** link:{repoURL}/src/main/resources/view/StatusBarFooter.fxml[`StatusBarFooter.fxml`] will need a new `StatusBar`. Be sure to set the `GridPane.columnIndex` properly for each `StatusBar` to avoid misalignment! ** link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] needs to initialize the status bar on application start, and to update it accordingly whenever the address book is updated. * Solution ** Modify the constructor of link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter`] to take in the number of persons when the application just started. ** Use link:{repoURL}/src/main/java/seedu/address/ui/StatusBarFooter.java[`StatusBarFooter#handleAddressBookChangedEvent(AddressBookChangedEvent)`] to update the number of persons whenever there are new changes to the addressbook. ** For tests, modify link:{repoURL}/src/test/java/guitests/guihandles/StatusBarFooterHandle.java[`StatusBarFooterHandle`] by adding a state-saving functionality for the total number of people status, just like what we did for save location and sync status. ** For system tests, modify link:{repoURL}/src/test/java/systemtests/AddressBookSystemTest.java[`AddressBookSystemTest`] to also verify the new total number of persons status bar. ** See this https://github.com/se-edu/addressbook-level4/pull/803[PR] for the full solution. **** [discrete] ==== `Storage` component *Scenario:* You are in charge of `storage`. For your next project milestone, your team plans to implement a new feature of saving the address book to the cloud. However, the current implementation of the application constantly saves the address book after the execution of each command, which is not ideal if the user is working on limited internet connection. Your team decided that the application should instead save the changes to a temporary local backup file first, and only upload to the cloud after the user closes the application. Your job is to implement a backup API for the address book storage. [TIP] Do take a look at <> before attempting to modify the `Storage` component. . Add a new method `backupAddressBook(ReadOnlyAddressBook)`, so that the address book can be saved in a fixed temporary location. + **** * Hint ** Add the API method in link:{repoURL}/src/main/java/seedu/address/storage/AddressBookStorage.java[`AddressBookStorage`] interface. ** Implement the logic in link:{repoURL}/src/main/java/seedu/address/storage/StorageManager.java[`StorageManager`] and link:{repoURL}/src/main/java/seedu/address/storage/JsonAddressBookStorage.java[`JsonAddressBookStorage`] class. * Solution ** See this https://github.com/se-edu/addressbook-level4/pull/594[PR] for the full solution. **** [[GetStartedProgramming-RemarkCommand]] === Creating a new command: `remark` By creating this command, you will get a chance to learn how to implement a feature end-to-end, touching all major components of the app. *Scenario:* You are a software maintainer for `addressbook`, as the former developer team has moved on to new projects. The current users of your application have a list of new feature requests that they hope the software will eventually have. The most popular request is to allow adding additional comments/notes about a particular contact, by providing a flexible `remark` field for each contact, rather than relying on tags alone. After designing the specification for the `remark` command, you are convinced that this feature is worth implementing. Your job is to implement the `remark` command. ==== Description Edits the remark for a person specified in the `INDEX`. + Format: `remark INDEX r/[REMARK]` Examples: * `remark 1 r/Likes to drink coffee.` + Edits the remark for the first person to `Likes to drink coffee.` * `remark 1 r/` + Removes the remark for the first person. ==== Step-by-step Instructions ===== [Step 1] Logic: Teach the app to accept 'remark' which does nothing Let's start by teaching the application how to parse a `remark` command. We will add the logic of `remark` later. **Main:** . Add a `RemarkCommand` that extends link:{repoURL}/src/main/java/seedu/address/logic/commands/Command.java[`Command`]. Upon execution, it should just throw an `Exception`. . Modify link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] to accept a `RemarkCommand`. **Tests:** . Add `RemarkCommandTest` that tests that `execute()` throws an Exception. . Add new test method to link:{repoURL}/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java[`AddressBookParserTest`], which tests that typing ""remark"" returns an instance of `RemarkCommand`. ===== [Step 2] Logic: Teach the app to accept 'remark' arguments Let's teach the application to parse arguments that our `remark` command will accept. E.g. `1 r/Likes to drink coffee.` **Main:** . Modify `RemarkCommand` to take in an `Index` and `String` and print those two parameters as the error message. . Add `RemarkCommandParser` that knows how to parse two arguments, one index and one with prefix 'r/'. . Modify link:{repoURL}/src/main/java/seedu/address/logic/parser/AddressBookParser.java[`AddressBookParser`] to use the newly implemented `RemarkCommandParser`. **Tests:** . Modify `RemarkCommandTest` to test the `RemarkCommand#equals()` method. . Add `RemarkCommandParserTest` that tests different boundary values for `RemarkCommandParser`. . Modify link:{repoURL}/src/test/java/seedu/address/logic/parser/AddressBookParserTest.java[`AddressBookParserTest`] to test that the correct command is generated according to the user input. ===== [Step 3] Ui: Add a placeholder for remark in `PersonCard` Let's add a placeholder on all our link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] s to display a remark for each person later. **Main:** . Add a `Label` with any random text inside link:{repoURL}/src/main/resources/view/PersonListCard.fxml[`PersonListCard.fxml`]. . Add FXML annotation in link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] to tie the variable to the actual label. **Tests:** . Modify link:{repoURL}/src/test/java/guitests/guihandles/PersonCardHandle.java[`PersonCardHandle`] so that future tests can read the contents of the remark label. ===== [Step 4] Model: Add `Remark` class We have to properly encapsulate the remark in our link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`] class. Instead of just using a `String`, let's follow the conventional class structure that the codebase already uses by adding a `Remark` class. **Main:** . Add `Remark` to model component (you can copy from link:{repoURL}/src/main/java/seedu/address/model/person/Address.java[`Address`], remove the regex and change the names accordingly). . Modify `RemarkCommand` to now take in a `Remark` instead of a `String`. **Tests:** . Add test for `Remark`, to test the `Remark#equals()` method. ===== [Step 5] Model: Modify `Person` to support a `Remark` field Now we have the `Remark` class, we need to actually use it inside link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. **Main:** . Add `getRemark()` in link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. . You may assume that the user will not be able to use the `add` and `edit` commands to modify the remarks field (i.e. the person will be created without a remark). . Modify link:{repoURL}/src/main/java/seedu/address/model/util/SampleDataUtil.java/[`SampleDataUtil`] to add remarks for the sample data (delete your `data/addressbook.json` so that the application will load the sample data when you launch it.) ===== [Step 6] Storage: Add `Remark` field to `JsonAdaptedPerson` class We now have `Remark` s for `Person` s, but they will be gone when we exit the application. Let's modify link:{repoURL}/src/main/java/seedu/address/storage/JsonAdaptedPerson.java[`JsonAdaptedPerson`] to include a `Remark` field so that it will be saved. **Main:** . Add a new JSON field for `Remark`. **Tests:** . Fix `invalidAndValidPersonAddressBook.json`, `typicalPersonsAddressBook.json`, `validAddressBook.json` etc., such that the JSON tests will not fail due to a missing `remark` field. ===== [Step 6b] Test: Add withRemark() for `PersonBuilder` Since `Person` can now have a `Remark`, we should add a helper method to link:{repoURL}/src/test/java/seedu/address/testutil/PersonBuilder.java[`PersonBuilder`], so that users are able to create remarks when building a link:{repoURL}/src/main/java/seedu/address/model/person/Person.java[`Person`]. **Tests:** . Add a new method `withRemark()` for link:{repoURL}/src/test/java/seedu/address/testutil/PersonBuilder.java[`PersonBuilder`]. This method will create a new `Remark` for the person that it is currently building. . Try and use the method on any sample `Person` in link:{repoURL}/src/test/java/seedu/address/testutil/TypicalPersons.java[`TypicalPersons`]. ===== [Step 7] Ui: Connect `Remark` field to `PersonCard` Our remark label in link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`] is still a placeholder. Let's bring it to life by binding it with the actual `remark` field. **Main:** . Modify link:{repoURL}/src/main/java/seedu/address/ui/PersonCard.java[`PersonCard`]'s constructor to bind the `Remark` field to the `Person` 's remark. **Tests:** . Modify link:{repoURL}/src/test/java/seedu/address/ui/testutil/GuiTestAssert.java[`GuiTestAssert#assertCardDisplaysPerson(...)`] so that it will compare the now-functioning remark label. ===== [Step 8] Logic: Implement `RemarkCommand#execute()` logic We now have everything set up... but we still can't modify the remarks. Let's finish it up by adding in actual logic for our `remark` command. **Main:** . Replace the logic in `RemarkCommand#execute()` (that currently just throws an `Exception`), with the actual logic to modify the remarks of a person. **Tests:** . Update `RemarkCommandTest` to test that the `execute()` logic works. ==== Full Solution See this https://github.com/se-edu/addressbook-level4/pull/599[PR] for the step-by-step solution. [appendix] == Product Scope *Target user profile*: * has a need to manage a significant number of contacts * prefer desktop apps over other types * can type fast * prefers typing over mouse input * is reasonably comfortable using CLI apps *Value proposition*: manage contacts faster than a typical mouse/GUI driven app [appendix] == User Stories Priorities: High (must have) - `* * \\*`, Medium (nice to have) - `* \\*`, Low (unlikely to have) - `*` [width=""59%"",cols=""22%,<23%,<25%,<30%"",options=""header"",] |======================================================================= |Priority |As a ... |I want to ... |So that I can... |`* * *` |new user |see usage instructions |refer to instructions when I forget how to use the App |`* * *` |user |add a new person | |`* * *` |user |delete a person |remove entries that I no longer need |`* * *` |user |find a person by name |locate details of persons without having to go through the entire list |`* *` |user |hide <> by default |minimize chance of someone else seeing them by accident |`*` |user with many persons in the address book |sort persons by name |locate a person easily |======================================================================= _{More to be added}_ [appendix] == Use Cases (For all use cases below, the *System* is the `AddressBook` and the *Actor* is the `user`, unless specified otherwise) [discrete] === Use case: Delete person *MSS* 1. User requests to list persons 2. AddressBook shows a list of persons 3. User requests to delete a specific person in the list 4. AddressBook deletes the person + Use case ends. *Extensions* [none] * 2a. The list is empty. + Use case ends. * 3a. The given index is invalid. + [none] ** 3a1. AddressBook shows an error message. + Use case resumes at step 2. _{More to be added}_ [appendix] == Non Functional Requirements . Should work on any <> as long as it has Java `9` or higher installed. . Should be able to hold up to 1000 persons without a noticeable sluggishness in performance for typical usage. . A user with above average typing speed 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. _{More to be added}_ [appendix] == Glossary [[mainstream-os]] Mainstream OS:: Windows, Linux, Unix, OS-X [[private-contact-detail]] Private contact detail:: A contact detail that is not meant to be shared with others [appendix] == Product Survey *Product Name* Author: ... Pros: * ... * ... Cons: * ... * ... [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. _{ more test cases ... }_ === Deleting a person . Deleting a person while all persons are listed .. Prerequisites: List all persons using the `list` command. Multiple persons in the list. .. Test case: `delete 1` + Expected: First contact is deleted from the list. Details of the deleted contact shown in the status message. Timestamp in the status bar is updated. .. Test case: `delete 0` + Expected: No person 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) _{give more}_ + Expected: Similar to previous. _{ more test cases ... }_ === Saving data . Dealing with missing/corrupted data files .. _{explain how to simulate a missing/corrupted file and the expected behavior}_ _{ more test cases ... }_ ",12090,False,2072.7020131507775,median "// MultiSpec // // Copyright 1988-2020 Purdue Research 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: https://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. // // MultiSpec is curated by the Laboratory for Applications of Remote Sensing at // Purdue University in West Lafayette, IN and licensed by Larry Biehl. // // File: xDialog.cpp : class implementation file // Class Definition: xDialog.h // // Authors: Abdur Rahman Maud, Larry L. Biehl // // Revision date: 11/21/2019 // // Language: C++ // // System: Linux and MacOS Operating Systems // // Brief description: This file contains functions that relate to the // CMDialog class. /* Template for debugging int numberChars = sprintf ( (char*)&gTextString3, "" xDialog: (): %s"", gEndOfLine); ListString ((char*)&gTextString3, numberChars, gOutputTextH); */ //------------------------------------------------------------------------------------ #include ""SMultiSpec.h"" #include ""xChannelsDialog.h"" #include ""xDialog.h"" #include ""xClassesDialog.h"" #include ""xDialog_images.cpp"" #include ""xStatusDialog.h"" #include ""wx/wx.h"" #include ""wx/textctrl.h"" #include ""wx/msgdlg.h"" #include ""wx/radiobut.h"" #include ""wx/checkbox.h"" BEGIN_EVENT_TABLE (CMDialog, wxDialog) EVT_CHAR_HOOK (CMDialog::OnCharHook) END_EVENT_TABLE () CMDialog::CMDialog () { }; CMDialog::CMDialog ( wxWindowID IDD, wxWindow* pParent, const wxString& title) : wxDialog (pParent, IDD, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxSTAY_ON_TOP) { m_ColumnEnd = 1; m_ColumnInterval = 1; m_ColumnStart = 1; m_LineEnd = 1; m_LineInterval = 1; m_LineStart = 1; m_channelSelection = 0; m_channelListType = 1; m_classSelection = 0; m_featureTransformationFlag = FALSE; m_symbolSelection = 0; m_valuePtr = NULL; m_availableFeaturePtr = NULL; m_localActiveFeaturesPtr = NULL; m_localFeaturesPtr = NULL; m_localTransformFeaturesPtr = NULL; m_classListPtr = NULL; m_localSymbolsPtr = NULL; m_dialogPanel = NULL; // Get the default image window info pointer. It may // be changed later by super classes of this. m_dialogSelectArea.imageWindowInfoPtr = gImageWindowInfoPtr; m_dialogSelectArea.windowPtr = NULL; m_localActiveNumberFeatures = 0; m_localNumberFeatures = 0; m_localNumberTransformFeatures = 0; m_localNumberClasses = 0; m_outputStorageType = 0; // m_settingSelectedEntireButton is used to indicate when the selected/ // entire button is being set so that no checks are made of the line // and column values being used. m_settingSelectedEntireButton = FALSE; m_initializedFlag = FALSE; // Set limit values if (m_dialogSelectArea.imageWindowInfoPtr != NULL) { m_maxNumberLines = m_dialogSelectArea.imageWindowInfoPtr->maxNumberLines; m_maxNumberColumns = m_dialogSelectArea.imageWindowInfoPtr->maxNumberColumns; } // end ""m_dialogSelectArea.imageWindowInfoPtr != NULL"" else // m_dialogSelectArea.imageWindowInfoPtr == NULL { m_maxNumberLines = 1; m_maxNumberColumns = 1; } // end ""else m_dialogSelectArea.imageWindowInfoPtr == NULL"" m_initializedFlag = TRUE; } // end ""CMDialog"" CMDialog::~CMDialog () { m_value.Clear (); if (m_dialogPanel != NULL) delete m_dialogPanel; m_dialogPanel = NULL; } // end ""~CMDialog"" void CMDialog::CheckColumnEnd ( wxCommandEvent& event) { if (!m_settingSelectedEntireButton) { SInt32 returnValue; returnValue = CheckValue (IDC_ColumnEnd, 1, m_maxNumberColumns); if (returnValue > 0) { m_ColumnEnd = returnValue; SetEntireImageButtons (NULL, m_LineStart, m_LineEnd, m_ColumnStart, m_ColumnEnd); } // end ""if (returnValue > 0)"" } // end ""if (!m_settingSelectedEntireButton)"" } // end ""CheckColumnEnd"" void CMDialog::CheckColumnInterval ( wxCommandEvent& event) { SInt32 returnValue; returnValue = CheckValue (IDC_ColumnInterval, 1, m_maxNumberColumns); if (returnValue > 0) m_ColumnInterval = returnValue; } // end ""CheckColumnInterval"" void CMDialog::CheckColumnStart ( wxCommandEvent& event) { if (!m_settingSelectedEntireButton) { SInt32 returnValue; returnValue = CheckValue (IDC_ColumnStart, 1, m_maxNumberColumns); if (returnValue > 0) { m_ColumnStart = returnValue; SetEntireImageButtons (NULL, m_LineStart, m_LineEnd, m_ColumnStart, m_ColumnEnd); } // end ""if (returnValue > 0)"" } // end ""if (!m_settingSelectedEntireButton)"" } // end ""CheckColumnStart"" void CMDialog::CheckLineEnd ( wxCommandEvent& event) { if (!m_settingSelectedEntireButton) { SInt32 returnValue; returnValue = CheckValue (IDC_LineEnd, 1, m_maxNumberLines); if (returnValue > 0) { m_LineEnd = returnValue; SetEntireImageButtons (NULL, m_LineStart, m_LineEnd, m_ColumnStart, m_ColumnEnd); } // end ""if (returnValue > 0)"" } // end ""if (!m_settingSelectedEntireButton)"" } // end ""CheckLineEnd"" void CMDialog::CheckLineInterval ( wxCommandEvent& event) { SInt32 returnValue; returnValue = CheckValue (IDC_LineInterval, 1, m_maxNumberLines); if (returnValue > 0) m_LineInterval = returnValue; } // end ""CheckLineInterval"" void CMDialog::CheckLineStart ( wxCommandEvent& event) { if (!m_settingSelectedEntireButton) { SInt32 returnValue; returnValue = CheckValue (IDC_LineStart, 1, m_maxNumberLines); if (returnValue > 0) { m_LineStart = returnValue; SetEntireImageButtons (NULL, m_LineStart, m_LineEnd, m_ColumnStart, m_ColumnEnd); } // end ""if (returnValue > 0)"" } // end ""if (!m_settingSelectedEntireButton)"" } // end ""CheckLineStart"" SInt32 CMDialog::CheckValue ( int controlID, SInt32 minValue, SInt32 maxValue) { wxTextCtrl* textControlPtr; SInt32 outputValue = 0; textControlPtr = wxDynamicCast (FindWindow (controlID), wxTextCtrl); if (textControlPtr != NULL) { m_value = textControlPtr->GetValue (); if (m_value.Length () > 0) { outputValue = wxAtoi (m_value); if (outputValue < minValue || outputValue > maxValue) { if (outputValue < minValue) outputValue = minValue; else outputValue = maxValue; textControlPtr->ChangeValue (wxString::Format (wxT(""%i""), outputValue)); } // end ""if (outputValue < minValue || outputValue > maxValue)"" } // end ""if (m_value.Length () > 0)"" } // end ""if (textControlPtr != NULL)"" return (outputValue); } // end ""CheckValue"" void CMDialog::CreateLineColumnControls ( wxStaticBoxSizer* sbSizer) { wxStaticText *staticLineText, *staticColumnText, *staticEmptyText, *staticStartText, *staticEndText, *staticIntervalText; wxBitmap entireimi = wxBITMAP_PNG_FROM_DATA (entireim); wxBitmap toentirei = wxBITMAP_PNG_FROM_DATA (toentire); wxBitmap selectedi = wxBITMAP_PNG_FROM_DATA (selected); wxBitmap bmp4i = wxBITMAP_PNG_FROM_DATA (bmp4); wxBoxSizer* bSizer791; bSizer791 = new wxBoxSizer (wxHORIZONTAL); m_bpButton4 = new wxBitmapButton (sbSizer->GetStaticBox (), IDEntireImage, entireimi, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW); SetUpToolTip (m_bpButton4, IDS_ToolTip40); m_bpButton4->SetBitmapDisabled (toentirei); bSizer791->Add (m_bpButton4, wxSizerFlags(0).Align(wxALIGN_CENTER_VERTICAL).Border(wxALL, 5)); m_bpButton5 = new wxBitmapButton (sbSizer->GetStaticBox (), IDSelectedImage, selectedi, wxDefaultPosition, wxDefaultSize, wxBU_AUTODRAW); m_bpButton5->Hide (); m_bpButton5->SetBitmapDisabled (bmp4i); bSizer791->Add (m_bpButton5, wxSizerFlags(0).Align(wxALIGN_CENTER_VERTICAL).Border(wxALL, 5)); sbSizer->Add (bSizer791, wxSizerFlags(0).Expand()); wxGridSizer* gSizer1; gSizer1 = new wxGridSizer (3, 4, 0, 0); staticEmptyText = new wxStaticText (sbSizer->GetStaticBox (), wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); staticEmptyText->Wrap (-1); gSizer1->Add (staticEmptyText, wxSizerFlags(0).Border(wxALL, 5)); staticStartText = new wxStaticText (sbSizer->GetStaticBox (), wxID_ANY, wxT(""Start""), wxDefaultPosition, wxDefaultSize, 0); staticStartText->Wrap (-1); gSizer1->Add (staticStartText, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); staticEndText = new wxStaticText (sbSizer->GetStaticBox (), wxID_ANY, wxT(""End""), wxDefaultPosition, wxDefaultSize, 0); staticEndText->Wrap (-1); gSizer1->Add (staticEndText, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); staticIntervalText = new wxStaticText (sbSizer->GetStaticBox (), wxID_ANY, wxT(""Interval""), wxDefaultPosition, wxDefaultSize, 0); staticIntervalText->Wrap (-1); gSizer1->Add (staticIntervalText, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); staticLineText = new wxStaticText (sbSizer->GetStaticBox (), wxID_ANY, wxT(""Line""), wxDefaultPosition, wxDefaultSize, 0); staticLineText->Wrap (-1); gSizer1->Add (staticLineText, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); m_linestartctrl = new wxTextCtrl (sbSizer->GetStaticBox (), IDC_LineStart, wxEmptyString, wxDefaultPosition, wxSize(75, -1), 0); m_linestartctrl->SetValidator ( wxTextValidator (wxFILTER_DIGITS, &m_LineStartString)); gSizer1->Add (m_linestartctrl, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); m_lineendctrl = new wxTextCtrl (sbSizer->GetStaticBox (), IDC_LineEnd, wxEmptyString, wxDefaultPosition, wxSize(75, -1), 0); m_lineendctrl->SetValidator (wxTextValidator (wxFILTER_DIGITS, &m_LineEndString)); gSizer1->Add (m_lineendctrl, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); m_lineintctrl = new wxTextCtrl (sbSizer->GetStaticBox (), IDC_LineInterval, wxEmptyString, wxDefaultPosition, wxSize(75, -1), 0); m_lineintctrl->SetValidator ( wxTextValidator (wxFILTER_DIGITS, &m_LineIntervalString)); gSizer1->Add (m_lineintctrl, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); staticColumnText = new wxStaticText (sbSizer->GetStaticBox (), wxID_ANY, wxT(""Column""), wxDefaultPosition, wxSize(75, -1), 0); staticColumnText->Wrap (-1); gSizer1->Add (staticColumnText, wxSizerFlags(0).Align(wxALIGN_CENTER)); m_colstartctrl = new wxTextCtrl (sbSizer->GetStaticBox (), IDC_ColumnStart, wxEmptyString, wxDefaultPosition, wxSize(75, -1), 0); m_colstartctrl->SetValidator ( wxTextValidator (wxFILTER_DIGITS, &m_ColumnStartString)); gSizer1->Add (m_colstartctrl, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); m_colendctrl = new wxTextCtrl (sbSizer->GetStaticBox (), IDC_ColumnEnd, wxEmptyString, wxDefaultPosition, wxSize(75, -1), 0); m_colendctrl->SetValidator ( wxTextValidator (wxFILTER_DIGITS, &m_ColumnEndString)); gSizer1->Add (m_colendctrl, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); m_colintctrl = new wxTextCtrl (sbSizer->GetStaticBox (), IDC_ColumnInterval, wxEmptyString, wxDefaultPosition, wxSize(75, -1), 0); m_colintctrl->SetValidator ( wxTextValidator (wxFILTER_DIGITS, &m_ColumnIntervalString)); gSizer1->Add (m_colintctrl, wxSizerFlags(0).Align(wxALIGN_CENTER).Border(wxALL, 5)); SetUpToolTip (m_linestartctrl, IDS_ToolTip19); SetUpToolTip (m_lineendctrl, IDS_ToolTip20); SetUpToolTip (m_lineintctrl, IDS_ToolTip21); SetUpToolTip (m_colstartctrl, IDS_ToolTip22); SetUpToolTip (m_colendctrl, IDS_ToolTip23); SetUpToolTip (m_colintctrl, IDS_ToolTip24); sbSizer->Add (gSizer1, wxSizerFlags(1).Expand()); } // end ""CreateLineColumnControls"" void CMDialog::CreateStandardButtons ( wxBoxSizer* bVMainSizer) { wxSizer* standardButtonSizer = CreateButtonSizer (wxOK | wxCANCEL); #if defined multispec_wxmac bVMainSizer->Add (standardButtonSizer, wxSizerFlags(0).Right()); #else bVMainSizer->Add (standardButtonSizer, wxSizerFlags(0).Right().Border(wxTOP|wxBOTTOM, 12)); #endif } // end ""CreateStandardButtons"" void CMDialog::GetAllSubsetMenuControl ( int controlCode, wxWindow* parentWindow, UInt16 controlItemNumber, int horizontalSize, int toolTipStringNumber) { #if defined multispec_wxlin wxComboBox* control = new wxComboBox (parentWindow, controlItemNumber, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); #endif // multispec_wxlin #if defined multispec_wxmac wxChoice* control = new wxChoice (parentWindow, controlItemNumber, wxDefaultPosition, wxSize (horizontalSize, -1)); #endif // multispec_wxmac if (controlCode == kChannelsMenu || controlCode == kChannelsAvailableMenu) m_channelsCtrl = control; else if (controlCode == kClassesMenu) m_classesCtrl = control; else if (controlCode == kChannelsPossibleMenu) m_channelsPossibleCtrl = control; else if (controlCode == kClassAreasMenu) m_classAreasCtrl = control; if (controlCode == kChannelsPossibleMenu) control->Append (wxT(""All possible"")); else if (controlCode == kChannelsAvailableMenu) control->Append (wxT(""All available"")); else // controlCode != kChannelsPossibleMenu control->Append (wxT(""All"")); control->Append (wxT(""Subset..."")); if (toolTipStringNumber > 0) SetUpToolTip (control, toolTipStringNumber); } // end ""GetAllSubsetMenuControl"" SInt16 CMDialog::GetComboListSelection ( UInt16 dialogItemNumber, SInt32 selectedListItemData) { return (::GetComboListSelection (this, dialogItemNumber, selectedListItemData)); } // end ""GetComboListSelection"" SInt16 CMDialog::GetComboListSelection2 ( wxWindow* cWindowPtr, UInt16 dialogItemNumber, SInt32 selectedListItemData) { wxComboBox* comboBoxPtr; wxWindow* wptr; wxChoice* choiceptr; UInt32 index, numberComboItems; SInt16 comboListSelection; comboListSelection = -1; wptr = cWindowPtr->FindWindow (dialogItemNumber); if (wxDynamicCast (wptr, wxComboBox) != NULL) { // If it's wxComboBox comboBoxPtr = (wxComboBox*)wptr; if (comboBoxPtr != NULL) { numberComboItems = (UInt32)comboBoxPtr->GetCount (); for (index=0; indexGetClientData (index)) { SInt64 selectindex64 = (SInt64)((int*)comboBoxPtr->GetClientData (index)); SInt32 selectindex = (SInt32)selectindex64; if (selectindex == selectedListItemData) comboListSelection = (SInt16)index; } // end ""if (comboBoxPtr->GetClientData (index))"" } // end ""for (index=0; indexGetCount (); for (index = 0; index < numberComboItems; index++) { if (choiceptr->GetClientData (index)) { SInt64 selectindex64 = (SInt64)((int*)choiceptr->GetClientData (index)); SInt32 selectindex = (SInt32)selectindex64; if (selectindex == selectedListItemData) comboListSelection = (SInt16)index; } // end ""if (choiceptr->GetClientData (index))"" } // end ""for (index=0; indexAppend (wxT(""Equal"")); control->Append (wxT(""Unequal..."")); if (toolTipStringNumber > 0) SetUpToolTip (control, toolTipStringNumber); } // end ""GetEqualUnequalMenuControl"" void CMDialog::GetPaletteMenuControl ( int controlCode, wxWindow* parentWindow, UInt16 controlItemNumber, int horizontalSize, int toolTipStringNumber) { #if defined multispec_wxlin wxComboBox* control = new wxComboBox (parentWindow, controlItemNumber, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY); #endif // multispec_wxlin #if defined multispec_wxmac wxChoice* control = new wxChoice (parentWindow, controlItemNumber, wxDefaultPosition, wxSize (horizontalSize, -1)); #endif // multispec_wxmac m_paletteCtrl = control; m_paletteCtrl->Append (wxT(""Default Colors"")); m_paletteCtrl->Append (wxT(""Default Gray Levels"")); m_paletteCtrl->Append (wxT(""Blue-Green-Red"")); m_paletteCtrl->Append (wxT(""AVHRR NDVI"")); m_paletteCtrl->Append (wxT(""MODIS NDVI"")); m_paletteCtrl->Append (wxT(""False Color..."")); m_paletteCtrl->Append (wxT(""ERDAS .trl file"")); m_paletteCtrl->Append (wxT(""User Defined"")); m_paletteCtrl->SetClientData (0, (void*)kDefaultColors); m_paletteCtrl->SetClientData (1, (void*)kDefaultGrays); m_paletteCtrl->SetClientData (2, (void*)kCorrelationMatrixColors); m_paletteCtrl->SetClientData (3, (void*)kAVHRR_NDVI_Colors); m_paletteCtrl->SetClientData (4, (void*)kMODIS_NDVI_Colors); m_paletteCtrl->SetClientData (5, (void*)kFalseColors); m_paletteCtrl->SetClientData (6, (void*)kImageDefaultColorTable); m_paletteCtrl->SetClientData (7, (void*)kUserDefinedColors); if (toolTipStringNumber > 0) SetUpToolTip (control, toolTipStringNumber); } // end ""GetPaletteMenuControl"" void CMDialog::HandleChannelsMenu ( UInt16 channelsMenuItemNumber, Boolean transformationFlag, SInt16 totalNumberChannels, SInt16 channelMenuType, Boolean okFlagSetting) { int channelSelection; Boolean wxChoiceFlag = FALSE; const wxChar* classNamePtr = (FindWindow (channelsMenuItemNumber))-> GetClassInfo()->GetClassName (); if (wxStrcmp (classNamePtr, wxT(""wxChoice"")) == 0) wxChoiceFlag = TRUE; if (wxChoiceFlag) channelSelection = (wxDynamicCast (FindWindow (channelsMenuItemNumber), wxChoice))->GetCurrentSelection (); else // classNamePtr must be ""wxComboBox"" channelSelection = (wxDynamicCast (FindWindow (channelsMenuItemNumber), wxComboBox))->GetCurrentSelection (); if (channelSelection == kSubsetMenuItem || (channelSelection == kAllMenuItem && m_channelListType == kSelectedItemsListOnly)) { // Following line commented out were included to try to fix issue where // one has to click mouse button or use key twice to get action after // the channels dialog box is display for OSX. //CheckSomeEvents (updateMask+activMask); //wxCommandEvent *evt = new wxCommandEvent (wxEVT_BUTTON, IDC_ChannelsSubset); //wxQueueEvent (m_hiddenChannelSubset, evt); // Subset of channels to be used. SetDLogControlHilite (NULL, wxID_OK, 255); CMChannelsDlg* channelsDialogPtr = NULL; channelsDialogPtr = new CMChannelsDlg (this); channelsDialogPtr->DoDialog ((SInt16*)&m_localActiveNumberFeatures, (SInt16*)m_localActiveFeaturesPtr, gImageLayerInfoPtr, gImageFileInfoPtr, m_channelListType, transformationFlag, (SInt16*)m_availableFeaturePtr, totalNumberChannels, m_channelSelection); if (channelsDialogPtr != NULL) delete channelsDialogPtr; if (channelMenuType == kImageChannelType) { if (m_localActiveNumberFeatures == (UInt16)totalNumberChannels) channelSelection = kAllMenuItem; } // end ""if (channelMenuType == kImageChannelType)"" if (okFlagSetting) SetDLogControlHilite (NULL, wxID_OK, 0); } // end ""if (m_channelSelection == kSubsetMenuItem)"" else // channelSelection == kAllMenuItem { if (channelMenuType == kImageChannelType) m_localActiveNumberFeatures = totalNumberChannels; } // end ""else channelSelection == kAllMenuItem"" if (channelMenuType == kProjectChannelType) { channelSelection = UpdateDialogNumberFeatureParameters ( transformationFlag, &m_localActiveNumberFeatures, &m_localNumberFeatures, totalNumberChannels, &m_localNumberTransformFeatures, gTransformationMatrix.numberFeatures, channelSelection); } // end ""if (channelMenuType == kProjectChannelType)"" m_channelSelection = channelSelection; if (wxChoiceFlag) (wxDynamicCast (FindWindow (channelsMenuItemNumber), wxChoice))-> SetSelection (m_channelSelection); else // Must be wxComboBox (wxDynamicCast (FindWindow (channelsMenuItemNumber), wxComboBox))-> SetSelection (m_channelSelection); } // end ""HandleChannelsMenu"" /* void CMDialog::OnChannelsSubset ( wxCommandEvent& event) { int channelSelection; Boolean transformationFlag = kNoTransformation; SInt16 totalNumberChannels = 7; SInt16 channelMenuType = kImageChannelType; Boolean okFlagSetting = true; // Subset of channels to be used. SetDLogControlHilite (NULL, wxID_OK, 255); CMChannelsDlg* channelsDialogPtr = NULL; channelsDialogPtr = new CMChannelsDlg (this); channelsDialogPtr->DoDialog ((SInt16*)&m_localActiveNumberFeatures, (SInt16*)m_localActiveFeaturesPtr, gImageLayerInfoPtr, gImageFileInfoPtr, m_channelListType, transformationFlag, (SInt16*)m_availableFeaturePtr, totalNumberChannels, m_channelSelection); if (channelsDialogPtr != NULL) delete channelsDialogPtr; if (channelMenuType == kImageChannelType) { if (m_localActiveNumberFeatures == (UInt16)totalNumberChannels) channelSelection = kAllMenuItem; } // end ""if (channelMenuType == kImageChannelType)"" if (okFlagSetting) SetDLogControlHilite (NULL, wxID_OK, 0); } // end ""OnChannelsSubset"" */ void CMDialog::HandleClassesMenu ( UInt32* numberOutputClassesPtr, SInt16* classListPtr, SInt16 minimumNumberClasses, SInt16 numberInputClasses, UInt16 classesMenuItemNumber, int* classMenuSelectionPtr) { wxChoice* classChoicePtr; wxComboBox* classComboBoxPtr; int classMenuSelection; Boolean returnFlag, wxChoiceFlag = FALSE; const wxChar* classNamePtr = (FindWindow (classesMenuItemNumber))-> GetClassInfo()->GetClassName (); if (wxStrcmp (classNamePtr, wxT(""wxChoice"")) == 0) wxChoiceFlag = TRUE; if (wxChoiceFlag) { classChoicePtr = wxDynamicCast (FindWindow (classesMenuItemNumber), wxChoice); classMenuSelection = classChoicePtr->GetCurrentSelection (); } // end ""if (wxChoiceFlag)"" else // classNamePtr must be ""wxComboBox"" { classComboBoxPtr = wxDynamicCast (FindWindow (classesMenuItemNumber), wxComboBox); classMenuSelection = classComboBoxPtr->GetCurrentSelection (); } // end ""else classNamePtr must be ""wxComboBox"" if (classMenuSelection == kSubsetMenuItem) { // Subset of classes to be used. SetDLogControlHilite (NULL, wxID_OK, 255); // If all classes is the current setting, then assume that // the subset is the single active project class. if (*classMenuSelectionPtr == kAllMenuItem && gProjectInfoPtr->currentClass >= 0) { *numberOutputClassesPtr = 1; classListPtr[0] = gProjectInfoPtr->currentClass + 1; } // end ""if (currentSelection = kAllMenuItem && ..."" CMClassesDlg* classesDialogPtr = NULL; try { classesDialogPtr = new CMClassesDlg (); returnFlag = classesDialogPtr->DoDialog (numberOutputClassesPtr, classListPtr, minimumNumberClasses, (UInt16) numberInputClasses); if (classesDialogPtr != NULL) delete classesDialogPtr; } // end ""try"" catch (int e) { MemoryMessage (0, kObjectMessage); } // catch if (!returnFlag && *classMenuSelectionPtr == kAllMenuItem) *numberOutputClassesPtr = gProjectInfoPtr->numberStatisticsClasses; if (*numberOutputClassesPtr == gProjectInfoPtr->numberStatisticsClasses) { classMenuSelection = kAllMenuItem; if (wxChoiceFlag) classChoicePtr->SetSelection (classMenuSelection); else // must be wxComboBox classComboBoxPtr->SetSelection (classMenuSelection); } // end ""if (*numberOutputClassesPtr == ..."" SetDLogControlHilite (NULL, wxID_OK, 0); } // end ""if (classMenuSelection == kSubsetMenuItem)"" else // classMenuSelection == kAllMenuItem { *numberOutputClassesPtr = gProjectInfoPtr->numberStatisticsClasses; } // end ""else classMenuSelection == kAllMenuItem"" *classMenuSelectionPtr = classMenuSelection; } // end ""HandleClassesMenu"" void CMDialog::HandleClassPairWeightsMenu ( SInt16** weightsListPtrPtr, UInt16 pairWeightsMenuItemNumber, int* pairWeightsMenuSelectionPtr, SInt16* defaultClassPairWeightPtr) { wxChoice* pairWeightsChoicePtr; wxComboBox* pairWeightsComboBoxPtr; int pairWeightsMenuSelection; Boolean wxChoiceFlag = FALSE; const wxChar* classNamePtr = (FindWindow (pairWeightsMenuItemNumber))-> GetClassInfo()->GetClassName (); if (wxStrcmp (classNamePtr, wxT(""wxChoice"")) == 0) wxChoiceFlag = TRUE; if (wxChoiceFlag) { pairWeightsChoicePtr = wxDynamicCast ( FindWindow (pairWeightsMenuItemNumber), wxChoice); pairWeightsMenuSelection = pairWeightsChoicePtr->GetCurrentSelection (); } // end ""if (wxChoiceFlag)"" else // classNamePtr must be ""wxComboBox"" { pairWeightsComboBoxPtr = wxDynamicCast ( FindWindow (pairWeightsMenuItemNumber), wxComboBox); pairWeightsMenuSelection = pairWeightsComboBoxPtr->GetCurrentSelection (); } // end ""else classNamePtr must be ""wxComboBox"" if (pairWeightsMenuSelection == kUnequalWeightMenuItem) { // Subset of classes to be used. SetDLogControlHilite (NULL, wxID_OK, 255); pairWeightsMenuSelection = ClassPairWeightsDialog ( gProjectInfoPtr->numberStatisticsClasses, weightsListPtrPtr, *pairWeightsMenuSelectionPtr, defaultClassPairWeightPtr); SetDLogControlHilite (NULL, wxID_OK, 0); if (pairWeightsMenuSelection == kEqualWeightMenuItem) { if (wxChoiceFlag) pairWeightsChoicePtr->SetSelection (pairWeightsMenuSelection); else // must be wxComboBox pairWeightsComboBoxPtr->SetSelection (pairWeightsMenuSelection); } // end ""if (classPairWeightsMenuSelection == kEqualWeightMenuItem)"" } // end ""if (classPairWeightsMenuSelection == kUnequalWeightMenuItem)"" *pairWeightsMenuSelectionPtr = pairWeightsMenuSelection; } // end ""HandleClassPairWeightsMenu"" void CMDialog::HandleClassWeightsMenu ( UInt16 numberOutputClassesToUse, SInt16* classListPtr, float* weightsListPtr, Boolean useEnhancedStatFlag, UInt16 weightsMenuItemNumber, int* weightsMenuSelectionPtr) { wxChoice* weightsChoicePtr; wxComboBox* weightsComboBoxPtr; int weightsMenuSelection; Boolean wxChoiceFlag = FALSE; const wxChar* classNamePtr = (FindWindow (weightsMenuItemNumber))-> GetClassInfo()->GetClassName (); if (wxStrcmp (classNamePtr, wxT(""wxChoice"")) == 0) wxChoiceFlag = TRUE; if (wxChoiceFlag) { weightsChoicePtr = wxDynamicCast (FindWindow (weightsMenuItemNumber), wxChoice); weightsMenuSelection = weightsChoicePtr->GetCurrentSelection (); } // end ""if (wxChoiceFlag)"" else // classNamePtr must be ""wxComboBox"" { weightsComboBoxPtr = wxDynamicCast ( FindWindow (weightsMenuItemNumber), wxComboBox); weightsMenuSelection = weightsComboBoxPtr->GetCurrentSelection (); } // end ""else classNamePtr must be ""wxComboBox"" if (weightsMenuSelection == kUnequalWeightMenuItem) { // Subset of classes to be used. SetDLogControlHilite (NULL, wxID_OK, 255); weightsMenuSelection = ClassWeightsDialog (numberOutputClassesToUse, classListPtr, weightsListPtr, *weightsMenuSelectionPtr, useEnhancedStatFlag); SetDLogControlHilite (NULL, wxID_OK, 0); if (weightsMenuSelection == kEqualWeightMenuItem) { if (wxChoiceFlag) weightsChoicePtr->SetSelection (weightsMenuSelection); else // must be wxComboBox weightsComboBoxPtr->SetSelection (weightsMenuSelection); } // end ""if (weightsMenuSelection == kEqualWeightMenuItem)"" } // end ""if (weightsMenuSelection == kUnequalWeightMenuItem)"" *weightsMenuSelectionPtr = weightsMenuSelection; } // end ""HandleClassWeightsMenu"" void CMDialog::HideShowAreaItems ( Boolean imageAreaFlag) { if (imageAreaFlag) { MShowDialogItem (this, IDC_LineColFrame); MShowDialogItem (this, IDC_StartEndInterval); MShowDialogItem (this, IDC_LinePrompt); MShowDialogItem (this, IDC_ColumnPrompt); MShowDialogItem (this, IDC_LineStart); MShowDialogItem (this, IDC_LineEnd); MShowDialogItem (this, IDC_LineInterval); MShowDialogItem (this, IDC_ColumnStart); MShowDialogItem (this, IDC_ColumnEnd); MShowDialogItem (this, IDC_ColumnInterval); MShowDialogItem (this, IDC_StartPrompt); MShowDialogItem (this, IDC_EndPrompt); MShowDialogItem (this, IDC_IntervalPrompt); } // end ""if (imageAreaFlag)"" else // !imageAreaFlag { MHideDialogItem (this, IDC_LineColFrame); MHideDialogItem (this, IDEntireImage); MHideDialogItem (this, IDSelectedImage); MHideDialogItem (this, IDC_StartEndInterval); MHideDialogItem (this, IDC_LinePrompt); MHideDialogItem (this, IDC_ColumnPrompt); MHideDialogItem (this, IDC_LineStart); MHideDialogItem (this, IDC_LineEnd); MHideDialogItem (this, IDC_LineInterval); MHideDialogItem (this, IDC_ColumnStart); MHideDialogItem (this, IDC_ColumnEnd); MHideDialogItem (this, IDC_ColumnInterval); MHideDialogItem (this, IDC_StartPrompt); MHideDialogItem (this, IDC_EndPrompt); MHideDialogItem (this, IDC_IntervalPrompt); } // end ""else !imageAreaFlag"" } // end ""HideShowAreaItems"" void CMDialog::HideSomeAreaSelectionItems () { MHideDialogItem (this, IDEntireImage); MHideDialogItem (this, IDSelectedImage); MHideDialogItem (this, IDC_LineStart); MHideDialogItem (this, IDC_LineEnd); MHideDialogItem (this, IDC_ColumnStart); MHideDialogItem (this, IDC_ColumnEnd); MHideDialogItem (this, IDC_StartPrompt); MHideDialogItem (this, IDC_EndPrompt); MHideDialogItem (this, IDC_StartEnd); } // end ""HideSomeAreaSelectionItems"" void CMDialog::LoadDItemString ( UInt16 itemNumber, Str255* theStringPtr) { CharPtr stringPtr = (CharPtr)theStringPtr; stringPtr = (CharPtr)&stringPtr[1]; LoadDItemString (itemNumber, stringPtr); } // end ""LoadDItemString"" void CMDialog::LoadDItemString ( UInt16 itemNumber, CharPtr theStringPtr) { const wxString string = wxString::FromAscii (theStringPtr); wxWindow* lcontrol = this->FindWindow ((long)itemNumber); wxTextCtrl* tctrl = wxDynamicCast (lcontrol, wxTextCtrl); if (tctrl != NULL) tctrl->ChangeValue (string); else // tctrl == NULL { wxStaticText* tctrl = wxDynamicCast (lcontrol, wxStaticText); if (tctrl != NULL) tctrl->SetLabel (string); } // end ""else tctrl == NULL"" } // end ""LoadDItemString"" void CMDialog::LoadDItemValue ( UInt16 itemNumber, SInt32 value) { wxString strval = wxString::Format (wxT(""%i""), value); wxTextCtrl* ctrl = wxDynamicCast (FindWindow (itemNumber), wxTextCtrl); if (ctrl != NULL) ctrl->ChangeValue (strval); else // ctrl == NULL { wxStaticText* tctrl = wxDynamicCast (FindWindow (itemNumber), wxStaticText); if (tctrl != NULL) tctrl->SetLabel (strval); else // tctrl == NULL { wxComboBox* cctrl = wxDynamicCast (FindWindow (itemNumber), wxComboBox); if (cctrl != NULL) cctrl->SetValue (strval); } // end ""else tctrl == NULL"" } // end ""else ctrl == NULL"" } // end ""LoadDItemString"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void MHideDialogItem // // Software purpose: The purpose of this routine is to hide the specifed dialog // item. // // Parameters in: Status Dialog item set // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Abdur Rahman Maud Date: 06/01/2011 // Revised By: Larry L. Biehl Date: 05/04/2018 void CMDialog::MHideDialogItem ( DialogPtr dialogPtr, SInt16 itemNumber) { wxWindow* dialogItemWindowPtr = FindWindow (itemNumber); if (dialogItemWindowPtr != NULL) dialogItemWindowPtr->Show (false); } // end ""MHideDialogItem"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void MShowDialogItem // // Software purpose: The purpose of this routine is to show the specifed dialog // item. // // Parameters in: Status Dialog item set // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Abdur Rahman Maud Date: 06/01/2011 // Revised By: Larry L. Biehl Date: 05/04/2018 void CMDialog::MEnableDialogItem ( DialogPtr dialogPtr, SInt16 itemNumber) { wxWindow* dialogItemWindowPtr = FindWindow (itemNumber); if (dialogItemWindowPtr != NULL) dialogItemWindowPtr->Enable (true); } // end ""MEnableDialogItem"" void CMDialog::MDisableDialogItem ( DialogPtr dialogPtr, SInt16 itemNumber) { wxWindow* dialogItemWindowPtr = FindWindow (itemNumber); if (dialogItemWindowPtr != NULL) dialogItemWindowPtr->Enable (false); } // end ""MDisableDialogItem"" void CMDialog::MShowDialogItem ( DialogPtr dialogPtr, SInt16 itemNumber) { wxWindow* dialogItemWindowPtr = FindWindow (itemNumber); if (dialogItemWindowPtr != NULL) dialogItemWindowPtr->Show (true); } // end ""MShowDialogItem"" void CMDialog::OnCharHook ( wxKeyEvent& event) { if (event.GetKeyCode () == WXK_RETURN || event.GetKeyCode () == WXK_NUMPAD_ENTER) { if (Validate () && TransferDataFromWindow ()) EndModal (wxID_OK); } // end ""if (event.GetKeyCode () == WXK_RETURN || ..."" #if defined multispec_wxlin else if (gProcessorCode == kClusterProcessor) { if (event.GetKeyCode () == WXK_ESCAPE && gStatusDialogPtr != NULL) ((CShortStatusDlg*)gStatusDialogPtr)-> m_canceledCommandInitiatedFlag = TRUE; event.Skip (); } // end ""else if (gProcessorCode == kClusterProcessor)"" #endif else event.Skip (); } // end ""OnCharHook"" void CMDialog::OnChannelComboCloseUp ( wxCommandEvent& event) { wxComboBox* channelComboPtr = (wxComboBox*)FindWindow (IDC_ChannelCombo); int channelSelection = channelComboPtr->GetSelection (); if (channelSelection == -1) channelComboPtr->SetSelection (m_channelSelection); event.Skip (false); // default is true } // end ""OnChannelComboCloseUp"" void CMDialog::OnChannelComboDropDown ( wxCommandEvent& event) { wxComboBox* channelComboPtr = (wxComboBox*)event.GetEventObject (); if (channelComboPtr != NULL) channelComboPtr->SetSelection (-1); } // end ""OnChannelComboDropDown"" void CMDialog::OnClassComboCloseUp ( wxCommandEvent& event) { wxComboBox* classComboPtr = (wxComboBox*)FindWindow (IDC_ClassCombo); int classSelection = classComboPtr->GetSelection (); if (classSelection == -1) classComboPtr->SetSelection (m_classSelection); event.Skip (); } // end ""OnClassComboCloseUp"" void CMDialog::OnClassComboDropDown ( wxCommandEvent& event) { wxComboBox* classComboPtr = (wxComboBox*)event.GetEventObject (); if (classComboPtr != NULL) classComboPtr->SetSelection (-1); } // end ""OnClassComboDropDown"" void CMDialog::OnClassComboSelendok ( wxCommandEvent& event) { HandleClassesMenu (&m_localNumberClasses, (SInt16*)m_classListPtr, 1, (SInt16)gProjectInfoPtr->numberStatisticsClasses, IDC_ClassCombo, &m_classSelection); } // end ""OnSelendokClassCombo"" void CMDialog::OnClassPairWeightsComboCloseUp ( wxCommandEvent& event) { wxComboBox* classPairWeightsComboPtr = (wxComboBox*)FindWindow (IDC_ClassPairWeightsCombo); int classPairWeightsSelection = classPairWeightsComboPtr->GetSelection (); if (classPairWeightsSelection == -1) classPairWeightsComboPtr->SetSelection (m_classPairWeightsSelection); event.Skip (); } // end ""OnClassPairWeightsComboCloseUp"" void CMDialog::OnClassPairWeightsComboDropDown ( wxCommandEvent& event) { wxComboBox* classPairWeightsComboPtr = (wxComboBox*)event.GetEventObject (); if (classPairWeightsComboPtr != NULL) classPairWeightsComboPtr->SetSelection (-1); } // end ""OnClassPairWeightsComboDropDown"" void CMDialog::OnClassWeightComboDropDown ( wxCommandEvent& event) { wxComboBox* weightsComboPtr = (wxComboBox*)event.GetEventObject (); if (weightsComboPtr != NULL) weightsComboPtr->SetSelection (-1); } // end ""OnClassWeightComboDropDown"" /* void CMDialog::OnCloseUpComboBox ( int controlID, int currentSelection) { wxComboBox* comboPtr = wxDynamicCast (FindWindow (controlID), wxComboBox); int selection = comboPtr->GetSelection (); if (selection == -1) comboPtr->SetSelection (currentSelection); } // end ""OnCloseUpComboBox"" void CMDialog::OnFeatureTransformation () { wxCheckBox* checkptr = (wxDynamicCast (FindWindow (IDC_FeatureTransformation), wxCheckBox)); wxRadioButton* radioptr = (wxDynamicCast (FindWindow (IDC_FeatureTransformation), wxRadioButton)); if (checkptr != NULL) m_featureTransformationFlag = checkptr->GetValue (); else if (radioptr != NULL) m_featureTransformationFlag = radioptr->GetValue (); CheckFeatureTransformationDialog (this, m_featureTransformAllowedFlag, IDC_FeatureTransformation, IDC_ChannelPrompt, (SInt16*)&m_featureTransformationFlag); } // end ""OnFeatureTransformation"" */ void CMDialog::OnClassWeightComboCloseUp ( wxCommandEvent& event) { wxComboBox* weightsComboPtr = (wxComboBox*)event.GetEventObject (); int weightsSelection = weightsComboPtr->GetSelection (); if (weightsSelection == -1) weightsComboPtr->SetSelection (m_classWeightsSelection); event.Skip (); } // end ""OnClassWeightComboCloseUp"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void PositionDialogWindow // // Software purpose: The purpose of this routine is to set the hilite // of the control in the dialog window. // // Parameters in: None // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Larry L. Biehl Date: 06/29/2011 // Revised By: Larry L. Biehl Date: 06/01/2015 void CMDialog::PositionDialogWindow (void) { CenterOnParent (); } // end ""PositionDialogWindow"" void CMDialog::SetChoiceItemText ( UInt16 dialogItemNumber, SInt16 comboItem, CharPtr stringPtr) { const wxString str = wxString::FromAscii (stringPtr); wxChoice* choicePtr; UInt32 numberComboItems; choicePtr = (wxChoice*)FindWindow (dialogItemNumber); if (choicePtr != NULL) { numberComboItems = choicePtr->GetCount (); if (numberComboItems > (UInt32)comboItem) choicePtr->SetString (comboItem, str); else // numberComboItems <= comboItem choicePtr->Append (str); } // end ""if (comboBoxPtr != NULL)"" } // end ""SetChoiceItemText"" void CMDialog::SetComboItemText ( UInt16 dialogItemNumber, SInt16 comboItem, CharPtr stringPtr) { const wxString str = wxString::FromAscii (stringPtr); wxComboBox* comboBoxPtr; UInt32 numberComboItems; comboBoxPtr = (wxComboBox*)FindWindow (dialogItemNumber); if (comboBoxPtr != NULL) { numberComboItems = comboBoxPtr->GetCount (); if (numberComboItems > (UInt32)comboItem) comboBoxPtr->SetString (comboItem, str); else // numberComboItems <= comboItem comboBoxPtr->Append (str); } // end ""if (comboBoxPtr != NULL)"" } // end ""SetComboItemText"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void SetDLogControl // // Software purpose: The purpose of this routine is to set the control // value of the control in the dialog window. // // Parameters in: None // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Abdur Rahman Maud Date: ??/??/2011 // Revised By: Larry L. Biehl Date: 07/20/2018 void CMDialog::SetDLogControl ( DialogPtr dialogPtr, SInt16 itemNumber, SInt16 setting) { ::SetDLogControl (dialogPtr, itemNumber, setting); } // end ""SetDLogControl"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void SetDLogControlHilite // // Software purpose: The purpose of this routine is to set the hilite // of the control in the dialog window. // // Parameters in: None // // Parameters out: None // // Value Returned: None // // Called By: Many dialogs // // Coded By: Larry L. Biehl Date: 01/30/2011 // Revised By: Larry L. Biehl Date: 06/02/2016 void CMDialog::SetDLogControlHilite ( DialogPtr dialogPtr, SInt16 itemNumber, SInt16 setting) { wxWindow* dialogItemWindowPtr = FindWindow (itemNumber); if (dialogItemWindowPtr != NULL) { if (setting == 0) dialogItemWindowPtr->Enable (true); else if (setting == 255) dialogItemWindowPtr->Enable (false); } // end ""if (dialogItemWindowPtr != NULL)"" } // end ""SetDLogControlHilite"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void SetEntireImageButtons // // Software purpose: The purpose of this routine is to set the 'to entire image/ // to selected image' buttons. // // Parameters in: None // // Parameters out: None // // Value Returned: None. // // Called By: // // Coded By: Larry L. Biehl Date: 10/16/2011 // Revised By: Larry L. Biehl Date: 03/08/2016 void CMDialog::SetEntireImageButtons ( DialogPtr dialogPtr, SInt32 lineStart, SInt32 lineEnd, SInt32 columnStart, SInt32 columnEnd) { // Determine if this is the entire area. m_entireImageFlag = CheckIfEntireImage (m_dialogSelectArea.imageWindowInfoPtr, lineStart, lineEnd, columnStart, columnEnd); if (!m_entireImageFlag || !gSelectionRectangleFlag) { MHideDialogItem (dialogPtr, IDSelectedImage); MShowDialogItem (dialogPtr, IDEntireImage); if (m_entireImageFlag) // Unhilite the button until the option is needed. SetDLogControlHilite (dialogPtr, IDEntireImage, 255); else SetDLogControlHilite (dialogPtr, IDEntireImage, 0); } // end ""if (!m_entireImageFlag || !gSelectionRectangleFlag)"" else // m_entireImageFlag && gSelectionRectangleFlag { wxBitmapButton* bitmapbutton = (wxBitmapButton*)FindWindow (IDEntireImage); // Save the original image position wxPoint pos = bitmapbutton->GetPosition (); MHideDialogItem (dialogPtr, IDEntireImage); MShowDialogItem (dialogPtr, IDSelectedImage); bitmapbutton = (wxBitmapButton*)FindWindow (IDSelectedImage); // Set to the original image position bitmapbutton->SetPosition (pos); } // end ""else m_entireImageFlag && gSelectionRectangleFlag"" } // end ""SetEntireImageButtons"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void SetMaxNumberLinesAndColumns // // Software purpose: The purpose of this routine is to set the maximum number // of lines and columns allowed. // // Parameters in: // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Larry L. Biehl Date: 03/18/2011 // Revised By: Larry L. Biehl Date: 03/18/2016 void CMDialog::SetMaxNumberLinesAndColumns ( UInt32 maxNumberLines, UInt32 maxNumberColumns) { m_maxNumberLines = maxNumberLines; m_maxNumberColumns = maxNumberColumns; } // end ""SetMaxNumberLinesAndColumns"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void SetStaticTextOrDropDownList // // Software purpose: The purpose of this routine is to show // or hide the specifed dialog item dependant upon // the input flag. // // Parameters in: Status Dialog item set // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Larry L. Biehl Date: 03/26/2012 // Revised By: Larry L. Biehl Date: 11/11/2019 void CMDialog::SetStaticTextOrDropDownList ( SInt16 dropDownListSelection, SInt16 dropDownListID, SInt16 staticTextID, Boolean deactivatedFlag) { char listString[64]; wxChoice* choiceCtrl; if (deactivatedFlag) { HideDialogItem (this, dropDownListID); ShowDialogItem (this, staticTextID); choiceCtrl = (wxChoice*)FindWindow (dropDownListID); wxString wxlistString = choiceCtrl->GetString (dropDownListSelection); strcpy (listString, (const char*)wxlistString.mb_str (wxConvUTF8)); LoadDItemString (staticTextID, listString); } // end ""if (projectionDeactivatedFlag)"" else // ""!deactivatedFlag"" { ShowDialogItem (this, dropDownListID); HideDialogItem (this, staticTextID); } // end ""if (deactivatedFlag)"" } // end ""SetStaticTextOrDropDownList"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: void ShowHideDialogItem // // Software purpose: The purpose of this routine is to show // or hide the specifed dialog item dependant upon // the input flag. // // Parameters in: Status Dialog item set // // Parameters out: None // // Value Returned: None // // Called By: // // Coded By: Larry L. Biehl Date: 09/24/2011 // Revised By: Larry L. Biehl Date: 06/01/2016 void CMDialog::ShowHideDialogItem ( DialogPtr dialogPtr, SInt16 itemNumber, Boolean showFlag) { if (showFlag) MShowDialogItem (dialogPtr, itemNumber); else // !showFlag MHideDialogItem (dialogPtr, itemNumber); dialogPtr->Fit (); } // end ""ShowHideDialogItem"" void CMDialog::ShowSomeAreaSelectionItems () { MShowDialogItem (this, IDEntireImage); MShowDialogItem (this, IDSelectedImage); // Determine if this is the entire area and set the to entire image icon. SetEntireImageButtons (NULL, m_LineStart, m_LineEnd, m_ColumnStart, m_ColumnEnd); MShowDialogItem (this, IDC_LineStart); MShowDialogItem (this, IDC_LineEnd); MShowDialogItem (this, IDC_ColumnStart); MShowDialogItem (this, IDC_ColumnEnd); MShowDialogItem (this, IDC_StartPrompt); MShowDialogItem (this, IDC_EndPrompt); MShowDialogItem (this, IDC_StartEnd); } // end ""ShowSomeAreaSelectionItems"" void CMDialog::ToEntireImage ( wxCommandEvent& event) { // Change to entire image m_LineStart = 1; m_LineEnd = m_maxNumberLines; m_ColumnStart = 1; m_ColumnEnd = m_maxNumberColumns; m_settingSelectedEntireButton = TRUE; LoadDItemValue (IDC_LineStart, m_LineStart); LoadDItemValue (IDC_LineEnd, m_LineEnd); LoadDItemValue (IDC_ColumnStart, m_ColumnStart); LoadDItemValue (IDC_ColumnEnd, m_ColumnEnd); m_settingSelectedEntireButton = FALSE; // Update m_dialogSelectArea since it will not get updated with the // LoadDItemValue calls above. m_dialogSelectArea.lineStart = m_LineStart; m_dialogSelectArea.lineEnd = m_LineEnd; m_dialogSelectArea.columnStart = m_ColumnStart; m_dialogSelectArea.columnEnd = m_ColumnEnd; FindWindow (IDC_LineStart)->SetFocus (); SetEntireImageButtons (NULL, m_LineStart, m_LineEnd, m_ColumnStart, m_ColumnEnd); SelectDialogItemText (this, IDC_LineStart, 0, SInt16_MAX); } // end ""ToEntireImage"" void CMDialog::ToSelectedImage ( wxCommandEvent& event) { LongRect selectionRect; // Change to selected area if (GetSelectionRectangle (m_dialogSelectArea.windowPtr, &selectionRect, kDontClearSelectionArea, kUseThreshold, kDontAdjustToBaseImage)) { m_LineStart = selectionRect.top; m_LineEnd = selectionRect.bottom; m_ColumnStart = selectionRect.left; m_ColumnEnd = selectionRect.right; m_settingSelectedEntireButton = TRUE; LoadDItemValue (IDC_LineStart, m_LineStart); LoadDItemValue (IDC_LineEnd, m_LineEnd); LoadDItemValue (IDC_ColumnStart, m_ColumnStart); LoadDItemValue (IDC_ColumnEnd, m_ColumnEnd); m_settingSelectedEntireButton = FALSE; // Update m_dialogSelectArea since it will not get updated with the // LoadDItemValue calls above. m_dialogSelectArea.lineStart = m_LineStart; m_dialogSelectArea.lineEnd = m_LineEnd; m_dialogSelectArea.columnStart = m_ColumnStart; m_dialogSelectArea.columnEnd = m_ColumnEnd; FindWindow (IDC_LineStart)->SetFocus (); SetEntireImageButtons (NULL, m_LineStart, m_LineEnd, m_ColumnStart, m_ColumnEnd); SelectDialogItemText (this, IDC_LineStart, 0, SInt16_MAX); } // end ""if (GetLineColumnSelection (..."" } // end ""ToSelectedImage"" void CMDialog::TransferLinesColumnsFromWindow () { m_LineStartString = m_linestartctrl->GetValue (); m_LineStart = wxAtoi (m_LineStartString); m_LineEndString = m_lineendctrl->GetValue (); m_LineEnd = wxAtoi (m_LineEndString); m_LineIntervalString = m_lineintctrl->GetValue (); m_LineInterval = wxAtoi (m_LineIntervalString); m_ColumnStartString = m_colstartctrl->GetValue (); m_ColumnStart = wxAtoi (m_ColumnStartString); m_ColumnEndString = m_colendctrl->GetValue (); m_ColumnEnd = wxAtoi (m_ColumnEndString); m_ColumnIntervalString = m_colintctrl->GetValue (); m_ColumnInterval = wxAtoi (m_ColumnIntervalString); } // end ""TransferLinesColumnsToWindow"" void CMDialog::TransferLinesColumnsToWindow () { m_linestartctrl->ChangeValue (wxString::Format (wxT(""%i""), m_LineStart)); m_lineendctrl->ChangeValue (wxString::Format (wxT(""%i""), m_LineEnd)); m_lineintctrl->ChangeValue (wxString::Format (wxT(""%i""), m_LineInterval)); m_colstartctrl->ChangeValue (wxString::Format (wxT(""%i""), m_ColumnStart)); m_colendctrl->ChangeValue (wxString::Format (wxT(""%i""), m_ColumnEnd)); m_colintctrl->ChangeValue (wxString::Format (wxT(""%i""), m_ColumnInterval)); } // end ""TransferLinesColumnsToWindow"" //------------------------------------------------------------------------------------ // Copyright 1988-2020 Purdue Research Foundation // // Function name: short int UpdateOneColListSelections // // Software purpose: The purpose of this routine is to update the selections // in the one column list based on the start, end // and interval values. // From Windows code. // // Parameters in: dialog list handle // // // Parameters out: None // // Value Returned: the number of selections // // Called By: ClassDialog in SProjectUtilities.cpp // ClassGroupDialog in SDisplayThematic.cpp // OnEnterNewRange in xOneColumnDialog.cpp // // Coded By: Larry L. Biehl Date: 05/16/1991 // Revised By: Larry L. Biehl Date: 11/12/2019 UInt16 CMDialog::UpdateOneColListSelections ( UInt16 numberInputVecItems, UInt16 listStart, UInt16 listEnd, UInt16 listInterval) { wxListBox* wxListBoxPtr; UInt16 index, item, nextTrueSelection, numberSelections; bool selectionFlag; wxListBoxPtr = (wxListBox*)FindWindow (IDC_List1); if (wxListBoxPtr != NULL && wxListBoxPtr->GetCount () > 0) { index = 0; for (item=1; itemDeselect (index); index++; } // end ""for (item=1; item<..."" nextTrueSelection = listStart; for (item=listStart; item<=listEnd; item++) { selectionFlag = (item == nextTrueSelection); if (selectionFlag) { nextTrueSelection += listInterval; wxListBoxPtr->Select (index); } // end ""if (selectionFlag)"" else // !selectionFlag wxListBoxPtr->Deselect (index); index++; } // end ""for (item=listStart; item..."" index = listEnd; for (item=listEnd+1; item<=numberInputVecItems; item++) { wxListBoxPtr->Deselect (index); index++; } // end ""for (item=listEnd+1; item<..."" } // end ""if (wxListBoxPtr != NULL && wxListBoxPtr->GetCount () > 0)"" numberSelections = (listEnd - listStart + listInterval) / listInterval; return (numberSelections); } // end ""UpdateOneColListSelections"" void CMDialog::UpdateAllSubsetList ( UInt16 channelsMenuItemNumber) { if (m_channelListType == kSelectedItemsListOnly) { if (m_channelsCtrl->GetCount () == 2) { if (m_channelSelection == kAllMenuItem) m_channelsCtrl->Delete (1); else // m_channelSelection == kSubsetMenuItem m_channelsCtrl->Delete (0); } // end ""if (...->GetCount () == 2)"" } // end ""if (m_channelListType == kSelectedChannelsListOnly)"" else // m_channelListType != kSelectedChannelsListOnly { if (m_channelsCtrl->GetCount () == 1) { m_channelsCtrl->Delete (0); m_channelsCtrl->Append (wxT(""All"")); m_channelsCtrl->Append (wxT(""Subset..."")); } // end ""if (...->GetCount () == 1)"" #if defined multispec_wxlin m_channelsCtrl->SetSelection (-1); #endif } // end ""else m_channelListType != kSelectedChannelsListOnly"" } // end ""UpdateAllSubsetList"" SInt16 CMDialog::VerifyLineColumnStartEndValues () { // Verify that the line and column values make sense SInt16 returnCode = 0; if (m_LineStart > m_LineEnd) { DisplayAlert (kErrorAlertID, kStopAlert, kAlertStrID, IDS_Alert68, 0, NULL); returnCode = IDC_LineStart; } // end ""m_LineStart > m_LineEnd"" else if (m_ColumnStart > m_ColumnEnd) { DisplayAlert (kErrorAlertID, kStopAlert, kAlertStrID, IDS_Alert69, 0, NULL); returnCode = IDC_ColumnStart; } // end ""else if (m_ColumnStart > m_ColumnEnd)"" return returnCode; } // end ""VerifyLineColumnStartEndValues"" SInt16 CMDialog::VerifyLineColumnValues ( SInt16 startLineItem, SInt16 startColumnItem, Boolean checkIntervalFlag) { SInt32 maxValue; SInt16 returnCode = 0; // Verify that none of the entries are blank. if (m_LineStartString.empty ()) returnCode = IDC_LineStart; else if (m_LineEndString.empty ()) returnCode = IDC_LineEnd; else if (checkIntervalFlag && m_LineIntervalString.empty ()) returnCode = IDC_LineInterval; if (returnCode != 0) maxValue = m_maxNumberLines; if (returnCode == 0) { if (m_ColumnStartString.empty ()) returnCode = IDC_ColumnStart; else if (m_ColumnEndString.empty ()) returnCode = IDC_ColumnEnd; else if (checkIntervalFlag && m_ColumnIntervalString.empty ()) returnCode = IDC_ColumnInterval; if (returnCode != 0) maxValue = m_maxNumberColumns; } // end ""if (returnCode == 0)"" if (returnCode != 0) { if (LoadSpecifiedStringNumberLongP (kAlertStrID, IDS_Alert91, (char*)gTextString, (char*)gTextString2, TRUE, 1, maxValue)) DisplayAlert (kErrorAlertID, kStopAlert, 0, 0, 0, gTextString); } // end ""if (returnCode != 0)"" // Verify that the line and column values make sense if (returnCode == 0) returnCode = VerifyLineColumnStartEndValues (); if (returnCode != 0) SelectDialogItemText (this, returnCode, 0, SHRT_MAX); return (returnCode); } // end ""VerifyLineColumnValues"" ",16291,True,2835.968793425846,median "/* Copyright (c) 2014, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED ""AS IS"" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include ""test_config.h"" #include #include #include #include #include #include #include #include #include ""../../crypto/internal.h"" #include ""../internal.h"" #include ""test_state.h"" namespace { template struct Flag { const char *flag; T TestConfig::*member; }; // FindField looks for the flag in |flags| that matches |flag|. If one is found, // it returns a pointer to the corresponding field in |config|. Otherwise, it // returns NULL. template T *FindField(TestConfig *config, const Flag (&flags)[N], const char *flag) { for (size_t i = 0; i < N; i++) { if (strcmp(flag, flags[i].flag) == 0) { return &(config->*(flags[i].member)); } } return NULL; } const Flag kBoolFlags[] = { {""-server"", &TestConfig::is_server}, {""-dtls"", &TestConfig::is_dtls}, {""-quic"", &TestConfig::is_quic}, {""-fallback-scsv"", &TestConfig::fallback_scsv}, {""-enable-ech-grease"", &TestConfig::enable_ech_grease}, {""-require-any-client-certificate"", &TestConfig::require_any_client_certificate}, {""-false-start"", &TestConfig::false_start}, {""-async"", &TestConfig::async}, {""-write-different-record-sizes"", &TestConfig::write_different_record_sizes}, {""-cbc-record-splitting"", &TestConfig::cbc_record_splitting}, {""-partial-write"", &TestConfig::partial_write}, {""-no-tls13"", &TestConfig::no_tls13}, {""-no-tls12"", &TestConfig::no_tls12}, {""-no-tls11"", &TestConfig::no_tls11}, {""-no-tls1"", &TestConfig::no_tls1}, {""-no-ticket"", &TestConfig::no_ticket}, {""-enable-channel-id"", &TestConfig::enable_channel_id}, {""-shim-writes-first"", &TestConfig::shim_writes_first}, {""-expect-session-miss"", &TestConfig::expect_session_miss}, {""-decline-alpn"", &TestConfig::decline_alpn}, {""-reject-alpn"", &TestConfig::reject_alpn}, {""-select-empty-alpn"", &TestConfig::select_empty_alpn}, {""-defer-alps"", &TestConfig::defer_alps}, {""-expect-extended-master-secret"", &TestConfig::expect_extended_master_secret}, {""-enable-ocsp-stapling"", &TestConfig::enable_ocsp_stapling}, {""-enable-signed-cert-timestamps"", &TestConfig::enable_signed_cert_timestamps}, {""-implicit-handshake"", &TestConfig::implicit_handshake}, {""-use-early-callback"", &TestConfig::use_early_callback}, {""-fail-early-callback"", &TestConfig::fail_early_callback}, {""-install-ddos-callback"", &TestConfig::install_ddos_callback}, {""-fail-ddos-callback"", &TestConfig::fail_ddos_callback}, {""-fail-cert-callback"", &TestConfig::fail_cert_callback}, {""-handshake-never-done"", &TestConfig::handshake_never_done}, {""-use-export-context"", &TestConfig::use_export_context}, {""-tls-unique"", &TestConfig::tls_unique}, {""-expect-ticket-renewal"", &TestConfig::expect_ticket_renewal}, {""-expect-no-session"", &TestConfig::expect_no_session}, {""-expect-ticket-supports-early-data"", &TestConfig::expect_ticket_supports_early_data}, {""-use-ticket-callback"", &TestConfig::use_ticket_callback}, {""-renew-ticket"", &TestConfig::renew_ticket}, {""-enable-early-data"", &TestConfig::enable_early_data}, {""-check-close-notify"", &TestConfig::check_close_notify}, {""-shim-shuts-down"", &TestConfig::shim_shuts_down}, {""-verify-fail"", &TestConfig::verify_fail}, {""-verify-peer"", &TestConfig::verify_peer}, {""-verify-peer-if-no-obc"", &TestConfig::verify_peer_if_no_obc}, {""-expect-verify-result"", &TestConfig::expect_verify_result}, {""-renegotiate-once"", &TestConfig::renegotiate_once}, {""-renegotiate-freely"", &TestConfig::renegotiate_freely}, {""-renegotiate-ignore"", &TestConfig::renegotiate_ignore}, {""-renegotiate-explicit"", &TestConfig::renegotiate_explicit}, {""-forbid-renegotiation-after-handshake"", &TestConfig::forbid_renegotiation_after_handshake}, {""-use-old-client-cert-callback"", &TestConfig::use_old_client_cert_callback}, {""-send-alert"", &TestConfig::send_alert}, {""-peek-then-read"", &TestConfig::peek_then_read}, {""-enable-grease"", &TestConfig::enable_grease}, {""-use-exporter-between-reads"", &TestConfig::use_exporter_between_reads}, {""-retain-only-sha256-client-cert"", &TestConfig::retain_only_sha256_client_cert}, {""-expect-sha256-client-cert"", &TestConfig::expect_sha256_client_cert}, {""-read-with-unfinished-write"", &TestConfig::read_with_unfinished_write}, {""-expect-secure-renegotiation"", &TestConfig::expect_secure_renegotiation}, {""-expect-no-secure-renegotiation"", &TestConfig::expect_no_secure_renegotiation}, {""-expect-session-id"", &TestConfig::expect_session_id}, {""-expect-no-session-id"", &TestConfig::expect_no_session_id}, {""-expect-accept-early-data"", &TestConfig::expect_accept_early_data}, {""-expect-reject-early-data"", &TestConfig::expect_reject_early_data}, {""-expect-no-offer-early-data"", &TestConfig::expect_no_offer_early_data}, {""-no-op-extra-handshake"", &TestConfig::no_op_extra_handshake}, {""-handshake-twice"", &TestConfig::handshake_twice}, {""-allow-unknown-alpn-protos"", &TestConfig::allow_unknown_alpn_protos}, {""-use-custom-verify-callback"", &TestConfig::use_custom_verify_callback}, {""-allow-false-start-without-alpn"", &TestConfig::allow_false_start_without_alpn}, {""-handoff"", &TestConfig::handoff}, {""-use-ocsp-callback"", &TestConfig::use_ocsp_callback}, {""-set-ocsp-in-callback"", &TestConfig::set_ocsp_in_callback}, {""-decline-ocsp-callback"", &TestConfig::decline_ocsp_callback}, {""-fail-ocsp-callback"", &TestConfig::fail_ocsp_callback}, {""-install-cert-compression-algs"", &TestConfig::install_cert_compression_algs}, {""-is-handshaker-supported"", &TestConfig::is_handshaker_supported}, {""-handshaker-resume"", &TestConfig::handshaker_resume}, {""-reverify-on-resume"", &TestConfig::reverify_on_resume}, {""-enforce-rsa-key-usage"", &TestConfig::enforce_rsa_key_usage}, {""-jdk11-workaround"", &TestConfig::jdk11_workaround}, {""-server-preference"", &TestConfig::server_preference}, {""-export-traffic-secrets"", &TestConfig::export_traffic_secrets}, {""-key-update"", &TestConfig::key_update}, {""-expect-delegated-credential-used"", &TestConfig::expect_delegated_credential_used}, {""-expect-hrr"", &TestConfig::expect_hrr}, {""-expect-no-hrr"", &TestConfig::expect_no_hrr}, {""-wait-for-debugger"", &TestConfig::wait_for_debugger}, }; const Flag kStringFlags[] = { {""-write-settings"", &TestConfig::write_settings}, {""-key-file"", &TestConfig::key_file}, {""-cert-file"", &TestConfig::cert_file}, {""-expect-server-name"", &TestConfig::expect_server_name}, {""-advertise-npn"", &TestConfig::advertise_npn}, {""-expect-next-proto"", &TestConfig::expect_next_proto}, {""-select-next-proto"", &TestConfig::select_next_proto}, {""-send-channel-id"", &TestConfig::send_channel_id}, {""-host-name"", &TestConfig::host_name}, {""-advertise-alpn"", &TestConfig::advertise_alpn}, {""-expect-alpn"", &TestConfig::expect_alpn}, {""-expect-late-alpn"", &TestConfig::expect_late_alpn}, {""-expect-advertised-alpn"", &TestConfig::expect_advertised_alpn}, {""-select-alpn"", &TestConfig::select_alpn}, {""-psk"", &TestConfig::psk}, {""-psk-identity"", &TestConfig::psk_identity}, {""-srtp-profiles"", &TestConfig::srtp_profiles}, {""-cipher"", &TestConfig::cipher}, {""-export-label"", &TestConfig::export_label}, {""-export-context"", &TestConfig::export_context}, {""-expect-peer-cert-file"", &TestConfig::expect_peer_cert_file}, {""-use-client-ca-list"", &TestConfig::use_client_ca_list}, {""-expect-client-ca-list"", &TestConfig::expect_client_ca_list}, {""-expect-msg-callback"", &TestConfig::expect_msg_callback}, {""-handshaker-path"", &TestConfig::handshaker_path}, {""-delegated-credential"", &TestConfig::delegated_credential}, {""-expect-early-data-reason"", &TestConfig::expect_early_data_reason}, {""-quic-early-data-context"", &TestConfig::quic_early_data_context}, }; // TODO(davidben): When we can depend on C++17 or Abseil, switch this to // std::optional or absl::optional. const Flag> kOptionalStringFlags[] = { {""-expect-peer-application-settings"", &TestConfig::expect_peer_application_settings}, }; const Flag kBase64Flags[] = { {""-expect-certificate-types"", &TestConfig::expect_certificate_types}, {""-expect-channel-id"", &TestConfig::expect_channel_id}, {""-token-binding-params"", &TestConfig::send_token_binding_params}, {""-expect-ocsp-response"", &TestConfig::expect_ocsp_response}, {""-expect-signed-cert-timestamps"", &TestConfig::expect_signed_cert_timestamps}, {""-ocsp-response"", &TestConfig::ocsp_response}, {""-signed-cert-timestamps"", &TestConfig::signed_cert_timestamps}, {""-ticket-key"", &TestConfig::ticket_key}, {""-quic-transport-params"", &TestConfig::quic_transport_params}, {""-expect-quic-transport-params"", &TestConfig::expect_quic_transport_params}, }; const Flag kIntFlags[] = { {""-port"", &TestConfig::port}, {""-resume-count"", &TestConfig::resume_count}, {""-expect-token-binding-param"", &TestConfig::expect_token_binding_param}, {""-min-version"", &TestConfig::min_version}, {""-max-version"", &TestConfig::max_version}, {""-expect-version"", &TestConfig::expect_version}, {""-mtu"", &TestConfig::mtu}, {""-export-keying-material"", &TestConfig::export_keying_material}, {""-expect-total-renegotiations"", &TestConfig::expect_total_renegotiations}, {""-expect-peer-signature-algorithm"", &TestConfig::expect_peer_signature_algorithm}, {""-expect-curve-id"", &TestConfig::expect_curve_id}, {""-initial-timeout-duration-ms"", &TestConfig::initial_timeout_duration_ms}, {""-max-cert-list"", &TestConfig::max_cert_list}, {""-expect-cipher-aes"", &TestConfig::expect_cipher_aes}, {""-expect-cipher-no-aes"", &TestConfig::expect_cipher_no_aes}, {""-expect-cipher"", &TestConfig::expect_cipher}, {""-resumption-delay"", &TestConfig::resumption_delay}, {""-max-send-fragment"", &TestConfig::max_send_fragment}, {""-read-size"", &TestConfig::read_size}, {""-expect-ticket-age-skew"", &TestConfig::expect_ticket_age_skew}, {""-quic-use-legacy-codepoint"", &TestConfig::quic_use_legacy_codepoint}, }; const Flag> kIntVectorFlags[] = { {""-signing-prefs"", &TestConfig::signing_prefs}, {""-verify-prefs"", &TestConfig::verify_prefs}, {""-expect-peer-verify-pref"", &TestConfig::expect_peer_verify_prefs}, {""-curves"", &TestConfig::curves}, }; const Flag>> kStringPairVectorFlags[] = { {""-application-settings"", &TestConfig::application_settings}, }; bool ParseFlag(char *flag, int argc, char **argv, int *i, bool skip, TestConfig *out_config) { bool *bool_field = FindField(out_config, kBoolFlags, flag); if (bool_field != NULL) { if (!skip) { *bool_field = true; } return true; } std::string *string_field = FindField(out_config, kStringFlags, flag); if (string_field != NULL) { *i = *i + 1; if (*i >= argc) { fprintf(stderr, ""Missing parameter.\\n""); return false; } if (!skip) { string_field->assign(argv[*i]); } return true; } std::unique_ptr *optional_string_field = FindField(out_config, kOptionalStringFlags, flag); if (optional_string_field != NULL) { *i = *i + 1; if (*i >= argc) { fprintf(stderr, ""Missing parameter.\\n""); return false; } if (!skip) { optional_string_field->reset(new std::string(argv[*i])); } return true; } std::string *base64_field = FindField(out_config, kBase64Flags, flag); if (base64_field != NULL) { *i = *i + 1; if (*i >= argc) { fprintf(stderr, ""Missing parameter.\\n""); return false; } size_t len; if (!EVP_DecodedLength(&len, strlen(argv[*i]))) { fprintf(stderr, ""Invalid base64: %s.\\n"", argv[*i]); return false; } std::unique_ptr decoded(new uint8_t[len]); if (!EVP_DecodeBase64(decoded.get(), &len, len, reinterpret_cast(argv[*i]), strlen(argv[*i]))) { fprintf(stderr, ""Invalid base64: %s.\\n"", argv[*i]); return false; } if (!skip) { base64_field->assign(reinterpret_cast(decoded.get()), len); } return true; } int *int_field = FindField(out_config, kIntFlags, flag); if (int_field) { *i = *i + 1; if (*i >= argc) { fprintf(stderr, ""Missing parameter.\\n""); return false; } if (!skip) { *int_field = atoi(argv[*i]); } return true; } std::vector *int_vector_field = FindField(out_config, kIntVectorFlags, flag); if (int_vector_field) { *i = *i + 1; if (*i >= argc) { fprintf(stderr, ""Missing parameter.\\n""); return false; } // Each instance of the flag adds to the list. if (!skip) { int_vector_field->push_back(atoi(argv[*i])); } return true; } std::vector> *string_pair_vector_field = FindField(out_config, kStringPairVectorFlags, flag); if (string_pair_vector_field) { *i = *i + 1; if (*i >= argc) { fprintf(stderr, ""Missing parameter.\\n""); return false; } const char *comma = strchr(argv[*i], ','); if (!comma) { fprintf(stderr, ""Parameter should be a pair of comma-separated strings.\\n""); return false; } // Each instance of the flag adds to the list. if (!skip) { string_pair_vector_field->push_back(std::make_pair( std::string(argv[*i], comma - argv[*i]), std::string(comma + 1))); } return true; } fprintf(stderr, ""Unknown argument: %s.\\n"", flag); return false; } const char kInit[] = ""-on-initial""; const char kResume[] = ""-on-resume""; const char kRetry[] = ""-on-retry""; } // namespace bool ParseConfig(int argc, char **argv, TestConfig *out_initial, TestConfig *out_resume, TestConfig *out_retry) { out_initial->argc = out_resume->argc = out_retry->argc = argc; out_initial->argv = out_resume->argv = out_retry->argv = argv; for (int i = 0; i < argc; i++) { bool skip = false; char *flag = argv[i]; if (strncmp(flag, kInit, strlen(kInit)) == 0) { if (!ParseFlag(flag + strlen(kInit), argc, argv, &i, skip, out_initial)) { return false; } } else if (strncmp(flag, kResume, strlen(kResume)) == 0) { if (!ParseFlag(flag + strlen(kResume), argc, argv, &i, skip, out_resume)) { return false; } } else if (strncmp(flag, kRetry, strlen(kRetry)) == 0) { if (!ParseFlag(flag + strlen(kRetry), argc, argv, &i, skip, out_retry)) { return false; } } else { int i_init = i; int i_resume = i; if (!ParseFlag(flag, argc, argv, &i_init, skip, out_initial) || !ParseFlag(flag, argc, argv, &i_resume, skip, out_resume) || !ParseFlag(flag, argc, argv, &i, skip, out_retry)) { return false; } } } return true; } static CRYPTO_once_t once = CRYPTO_ONCE_INIT; static int g_config_index = 0; static CRYPTO_BUFFER_POOL *g_pool = nullptr; static void init_once() { g_config_index = SSL_get_ex_new_index(0, NULL, NULL, NULL, NULL); if (g_config_index < 0) { abort(); } g_pool = CRYPTO_BUFFER_POOL_new(); if (!g_pool) { abort(); } } bool SetTestConfig(SSL *ssl, const TestConfig *config) { CRYPTO_once(&once, init_once); return SSL_set_ex_data(ssl, g_config_index, (void *)config) == 1; } const TestConfig *GetTestConfig(const SSL *ssl) { CRYPTO_once(&once, init_once); return (const TestConfig *)SSL_get_ex_data(ssl, g_config_index); } static int LegacyOCSPCallback(SSL *ssl, void *arg) { const TestConfig *config = GetTestConfig(ssl); if (!SSL_is_server(ssl)) { return !config->fail_ocsp_callback; } if (!config->ocsp_response.empty() && config->set_ocsp_in_callback && !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(), config->ocsp_response.size())) { return SSL_TLSEXT_ERR_ALERT_FATAL; } if (config->fail_ocsp_callback) { return SSL_TLSEXT_ERR_ALERT_FATAL; } if (config->decline_ocsp_callback) { return SSL_TLSEXT_ERR_NOACK; } return SSL_TLSEXT_ERR_OK; } static int ServerNameCallback(SSL *ssl, int *out_alert, void *arg) { // SNI must be accessible from the SNI callback. const TestConfig *config = GetTestConfig(ssl); const char *server_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (server_name == nullptr || std::string(server_name) != config->expect_server_name) { fprintf(stderr, ""servername mismatch (got %s; want %s).\\n"", server_name, config->expect_server_name.c_str()); return SSL_TLSEXT_ERR_ALERT_FATAL; } return SSL_TLSEXT_ERR_OK; } static int NextProtoSelectCallback(SSL *ssl, uint8_t **out, uint8_t *outlen, const uint8_t *in, unsigned inlen, void *arg) { const TestConfig *config = GetTestConfig(ssl); if (config->select_next_proto.empty()) { return SSL_TLSEXT_ERR_NOACK; } *out = (uint8_t *)config->select_next_proto.data(); *outlen = config->select_next_proto.size(); return SSL_TLSEXT_ERR_OK; } static int NextProtosAdvertisedCallback(SSL *ssl, const uint8_t **out, unsigned int *out_len, void *arg) { const TestConfig *config = GetTestConfig(ssl); if (config->advertise_npn.empty()) { return SSL_TLSEXT_ERR_NOACK; } *out = (const uint8_t *)config->advertise_npn.data(); *out_len = config->advertise_npn.size(); return SSL_TLSEXT_ERR_OK; } static void MessageCallback(int is_write, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg) { const uint8_t *buf_u8 = reinterpret_cast(buf); const TestConfig *config = GetTestConfig(ssl); TestState *state = GetTestState(ssl); if (!state->msg_callback_ok) { return; } if (content_type == SSL3_RT_HEADER) { if (len != (config->is_dtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH)) { fprintf(stderr, ""Incorrect length for record header: %zu.\\n"", len); state->msg_callback_ok = false; } return; } state->msg_callback_text += is_write ? ""write "" : ""read ""; switch (content_type) { case 0: if (version != SSL2_VERSION) { fprintf(stderr, ""Incorrect version for V2ClientHello: %x.\\n"", version); state->msg_callback_ok = false; return; } state->msg_callback_text += ""v2clienthello\\n""; return; case SSL3_RT_HANDSHAKE: { CBS cbs; CBS_init(&cbs, buf_u8, len); uint8_t type; uint32_t msg_len; if (!CBS_get_u8(&cbs, &type) || // TODO(davidben): Reporting on entire messages would be more // consistent than fragments. (config->is_dtls && !CBS_skip(&cbs, 3 /* total */ + 2 /* seq */ + 3 /* frag_off */)) || !CBS_get_u24(&cbs, &msg_len) || !CBS_skip(&cbs, msg_len) || CBS_len(&cbs) != 0) { fprintf(stderr, ""Could not parse handshake message.\\n""); state->msg_callback_ok = false; return; } char text[16]; snprintf(text, sizeof(text), ""hs %d\\n"", type); state->msg_callback_text += text; return; } case SSL3_RT_CHANGE_CIPHER_SPEC: if (len != 1 || buf_u8[0] != 1) { fprintf(stderr, ""Invalid ChangeCipherSpec.\\n""); state->msg_callback_ok = false; return; } state->msg_callback_text += ""ccs\\n""; return; case SSL3_RT_ALERT: if (len != 2) { fprintf(stderr, ""Invalid alert.\\n""); state->msg_callback_ok = false; return; } char text[16]; snprintf(text, sizeof(text), ""alert %d %d\\n"", buf_u8[0], buf_u8[1]); state->msg_callback_text += text; return; default: fprintf(stderr, ""Invalid content_type: %d.\\n"", content_type); state->msg_callback_ok = false; } } static int TicketKeyCallback(SSL *ssl, uint8_t *key_name, uint8_t *iv, EVP_CIPHER_CTX *ctx, HMAC_CTX *hmac_ctx, int encrypt) { if (!encrypt) { if (GetTestState(ssl)->ticket_decrypt_done) { fprintf(stderr, ""TicketKeyCallback called after completion.\\n""); return -1; } GetTestState(ssl)->ticket_decrypt_done = true; } // This is just test code, so use the all-zeros key. static const uint8_t kZeros[16] = {0}; if (encrypt) { OPENSSL_memcpy(key_name, kZeros, sizeof(kZeros)); RAND_bytes(iv, 16); } else if (OPENSSL_memcmp(key_name, kZeros, 16) != 0) { return 0; } if (!HMAC_Init_ex(hmac_ctx, kZeros, sizeof(kZeros), EVP_sha256(), NULL) || !EVP_CipherInit_ex(ctx, EVP_aes_128_cbc(), NULL, kZeros, iv, encrypt)) { return -1; } if (!encrypt) { return GetTestConfig(ssl)->renew_ticket ? 2 : 1; } return 1; } static int NewSessionCallback(SSL *ssl, SSL_SESSION *session) { // This callback is called as the handshake completes. |SSL_get_session| // must continue to work and, historically, |SSL_in_init| returned false at // this point. if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) { fprintf(stderr, ""Invalid state for NewSessionCallback.\\n""); abort(); } GetTestState(ssl)->got_new_session = true; GetTestState(ssl)->new_session.reset(session); return 1; } static void InfoCallback(const SSL *ssl, int type, int val) { if (type == SSL_CB_HANDSHAKE_DONE) { if (GetTestConfig(ssl)->handshake_never_done) { fprintf(stderr, ""Handshake unexpectedly completed.\\n""); // Abort before any expected error code is printed, to ensure the overall // test fails. abort(); } // This callback is called when the handshake completes. |SSL_get_session| // must continue to work and |SSL_in_init| must return false. if (SSL_in_init(ssl) || SSL_get_session(ssl) == nullptr) { fprintf(stderr, ""Invalid state for SSL_CB_HANDSHAKE_DONE.\\n""); abort(); } GetTestState(ssl)->handshake_done = true; // Callbacks may be called again on a new handshake. GetTestState(ssl)->ticket_decrypt_done = false; GetTestState(ssl)->alpn_select_done = false; } } static void ChannelIdCallback(SSL *ssl, EVP_PKEY **out_pkey) { *out_pkey = GetTestState(ssl)->channel_id.release(); } static SSL_SESSION *GetSessionCallback(SSL *ssl, const uint8_t *data, int len, int *copy) { TestState *async_state = GetTestState(ssl); if (async_state->session) { *copy = 0; return async_state->session.release(); } else if (async_state->pending_session) { return SSL_magic_pending_session_ptr(); } else { return NULL; } } static void CurrentTimeCallback(const SSL *ssl, timeval *out_clock) { *out_clock = *GetClock(); } static int AlpnSelectCallback(SSL *ssl, const uint8_t **out, uint8_t *outlen, const uint8_t *in, unsigned inlen, void *arg) { if (GetTestState(ssl)->alpn_select_done) { fprintf(stderr, ""AlpnSelectCallback called after completion.\\n""); exit(1); } GetTestState(ssl)->alpn_select_done = true; const TestConfig *config = GetTestConfig(ssl); if (config->decline_alpn) { return SSL_TLSEXT_ERR_NOACK; } if (config->reject_alpn) { return SSL_TLSEXT_ERR_ALERT_FATAL; } if (!config->expect_advertised_alpn.empty() && (config->expect_advertised_alpn.size() != inlen || OPENSSL_memcmp(config->expect_advertised_alpn.data(), in, inlen) != 0)) { fprintf(stderr, ""bad ALPN select callback inputs.\\n""); exit(1); } if (config->defer_alps) { for (const auto &pair : config->application_settings) { if (!SSL_add_application_settings( ssl, reinterpret_cast(pair.first.data()), pair.first.size(), reinterpret_cast(pair.second.data()), pair.second.size())) { fprintf(stderr, ""error configuring ALPS.\\n""); exit(1); } } } assert(config->select_alpn.empty() || !config->select_empty_alpn); *out = (const uint8_t *)config->select_alpn.data(); *outlen = config->select_alpn.size(); return SSL_TLSEXT_ERR_OK; } static bool CheckVerifyCallback(SSL *ssl) { const TestConfig *config = GetTestConfig(ssl); if (!config->expect_ocsp_response.empty()) { const uint8_t *data; size_t len; SSL_get0_ocsp_response(ssl, &data, &len); if (len == 0) { fprintf(stderr, ""OCSP response not available in verify callback.\\n""); return false; } } if (GetTestState(ssl)->cert_verified) { fprintf(stderr, ""Certificate verified twice.\\n""); return false; } return true; } static int CertVerifyCallback(X509_STORE_CTX *store_ctx, void *arg) { SSL *ssl = (SSL *)X509_STORE_CTX_get_ex_data( store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); const TestConfig *config = GetTestConfig(ssl); if (!CheckVerifyCallback(ssl)) { return 0; } GetTestState(ssl)->cert_verified = true; if (config->verify_fail) { store_ctx->error = X509_V_ERR_APPLICATION_VERIFICATION; return 0; } return 1; } bool LoadCertificate(bssl::UniquePtr *out_x509, bssl::UniquePtr *out_chain, const std::string &file) { bssl::UniquePtr bio(BIO_new(BIO_s_file())); if (!bio || !BIO_read_filename(bio.get(), file.c_str())) { return false; } out_x509->reset(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr)); if (!*out_x509) { return false; } out_chain->reset(sk_X509_new_null()); if (!*out_chain) { return false; } // Keep reading the certificate chain. for (;;) { bssl::UniquePtr cert( PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr)); if (!cert) { break; } if (!bssl::PushToStack(out_chain->get(), std::move(cert))) { return false; } } uint32_t err = ERR_peek_last_error(); if (ERR_GET_LIB(err) != ERR_LIB_PEM || ERR_GET_REASON(err) != PEM_R_NO_START_LINE) { return false; } ERR_clear_error(); return true; } bssl::UniquePtr LoadPrivateKey(const std::string &file) { bssl::UniquePtr bio(BIO_new(BIO_s_file())); if (!bio || !BIO_read_filename(bio.get(), file.c_str())) { return nullptr; } return bssl::UniquePtr( PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL)); } static bool GetCertificate(SSL *ssl, bssl::UniquePtr *out_x509, bssl::UniquePtr *out_chain, bssl::UniquePtr *out_pkey) { const TestConfig *config = GetTestConfig(ssl); if (!config->signing_prefs.empty()) { std::vector u16s(config->signing_prefs.begin(), config->signing_prefs.end()); if (!SSL_set_signing_algorithm_prefs(ssl, u16s.data(), u16s.size())) { return false; } } if (!config->key_file.empty()) { *out_pkey = LoadPrivateKey(config->key_file.c_str()); if (!*out_pkey) { return false; } } if (!config->cert_file.empty() && !LoadCertificate(out_x509, out_chain, config->cert_file.c_str())) { return false; } if (!config->ocsp_response.empty() && !config->set_ocsp_in_callback && !SSL_set_ocsp_response(ssl, (const uint8_t *)config->ocsp_response.data(), config->ocsp_response.size())) { return false; } return true; } static bool FromHexDigit(uint8_t *out, char c) { if ('0' <= c && c <= '9') { *out = c - '0'; return true; } if ('a' <= c && c <= 'f') { *out = c - 'a' + 10; return true; } if ('A' <= c && c <= 'F') { *out = c - 'A' + 10; return true; } return false; } static bool HexDecode(std::string *out, const std::string &in) { if ((in.size() & 1) != 0) { return false; } std::unique_ptr buf(new uint8_t[in.size() / 2]); for (size_t i = 0; i < in.size() / 2; i++) { uint8_t high, low; if (!FromHexDigit(&high, in[i * 2]) || !FromHexDigit(&low, in[i * 2 + 1])) { return false; } buf[i] = (high << 4) | low; } out->assign(reinterpret_cast(buf.get()), in.size() / 2); return true; } static std::vector SplitParts(const std::string &in, const char delim) { std::vector ret; size_t start = 0; for (size_t i = 0; i < in.size(); i++) { if (in[i] == delim) { ret.push_back(in.substr(start, i - start)); start = i + 1; } } ret.push_back(in.substr(start, std::string::npos)); return ret; } static std::vector DecodeHexStrings( const std::string &hex_strings) { std::vector ret; const std::vector parts = SplitParts(hex_strings, ','); for (const auto &part : parts) { std::string binary; if (!HexDecode(&binary, part)) { fprintf(stderr, ""Bad hex string: %s.\\n"", part.c_str()); return ret; } ret.push_back(binary); } return ret; } static bssl::UniquePtr DecodeHexX509Names( const std::string &hex_names) { const std::vector der_names = DecodeHexStrings(hex_names); bssl::UniquePtr ret(sk_X509_NAME_new_null()); if (!ret) { return nullptr; } for (const auto &der_name : der_names) { const uint8_t *const data = reinterpret_cast(der_name.data()); const uint8_t *derp = data; bssl::UniquePtr name( d2i_X509_NAME(nullptr, &derp, der_name.size())); if (!name || derp != data + der_name.size()) { fprintf(stderr, ""Failed to parse X509_NAME.\\n""); return nullptr; } if (!bssl::PushToStack(ret.get(), std::move(name))) { return nullptr; } } return ret; } static bool CheckPeerVerifyPrefs(SSL *ssl) { const TestConfig *config = GetTestConfig(ssl); if (!config->expect_peer_verify_prefs.empty()) { const uint16_t *peer_sigalgs; size_t num_peer_sigalgs = SSL_get0_peer_verify_algorithms(ssl, &peer_sigalgs); if (config->expect_peer_verify_prefs.size() != num_peer_sigalgs) { fprintf(stderr, ""peer verify preferences length mismatch (got %zu, wanted %zu)\\n"", num_peer_sigalgs, config->expect_peer_verify_prefs.size()); return false; } for (size_t i = 0; i < num_peer_sigalgs; i++) { if (static_cast(peer_sigalgs[i]) != config->expect_peer_verify_prefs[i]) { fprintf(stderr, ""peer verify preference %zu mismatch (got %04x, wanted %04x\\n"", i, peer_sigalgs[i], config->expect_peer_verify_prefs[i]); return false; } } } return true; } static bool CheckCertificateRequest(SSL *ssl) { const TestConfig *config = GetTestConfig(ssl); if (!CheckPeerVerifyPrefs(ssl)) { return false; } if (!config->expect_certificate_types.empty()) { const uint8_t *certificate_types; size_t certificate_types_len = SSL_get0_certificate_types(ssl, &certificate_types); if (certificate_types_len != config->expect_certificate_types.size() || OPENSSL_memcmp(certificate_types, config->expect_certificate_types.data(), certificate_types_len) != 0) { fprintf(stderr, ""certificate types mismatch.\\n""); return false; } } if (!config->expect_client_ca_list.empty()) { bssl::UniquePtr expected = DecodeHexX509Names(config->expect_client_ca_list); const size_t num_expected = sk_X509_NAME_num(expected.get()); const STACK_OF(X509_NAME) *received = SSL_get_client_CA_list(ssl); const size_t num_received = sk_X509_NAME_num(received); if (num_received != num_expected) { fprintf(stderr, ""expected %u names in CertificateRequest but got %u.\\n"", static_cast(num_expected), static_cast(num_received)); return false; } for (size_t i = 0; i < num_received; i++) { if (X509_NAME_cmp(sk_X509_NAME_value(received, i), sk_X509_NAME_value(expected.get(), i)) != 0) { fprintf(stderr, ""names in CertificateRequest differ at index #%d.\\n"", static_cast(i)); return false; } } const STACK_OF(CRYPTO_BUFFER) *buffers = SSL_get0_server_requested_CAs(ssl); if (sk_CRYPTO_BUFFER_num(buffers) != num_received) { fprintf(stderr, ""Mismatch between SSL_get_server_requested_CAs and "" ""SSL_get_client_CA_list.\\n""); return false; } } return true; } static int ClientCertCallback(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) { if (!CheckCertificateRequest(ssl)) { return -1; } if (GetTestConfig(ssl)->async && !GetTestState(ssl)->cert_ready) { return -1; } bssl::UniquePtr x509; bssl::UniquePtr chain; bssl::UniquePtr pkey; if (!GetCertificate(ssl, &x509, &chain, &pkey)) { return -1; } // Return zero for no certificate. if (!x509) { return 0; } // Chains and asynchronous private keys are not supported with client_cert_cb. *out_x509 = x509.release(); *out_pkey = pkey.release(); return 1; } static ssl_private_key_result_t AsyncPrivateKeySign( SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out, uint16_t signature_algorithm, const uint8_t *in, size_t in_len) { TestState *test_state = GetTestState(ssl); if (!test_state->private_key_result.empty()) { fprintf(stderr, ""AsyncPrivateKeySign called with operation pending.\\n""); abort(); } if (EVP_PKEY_id(test_state->private_key.get()) != SSL_get_signature_algorithm_key_type(signature_algorithm)) { fprintf(stderr, ""Key type does not match signature algorithm.\\n""); abort(); } // Determine the hash. const EVP_MD *md = SSL_get_signature_algorithm_digest(signature_algorithm); bssl::ScopedEVP_MD_CTX ctx; EVP_PKEY_CTX *pctx; if (!EVP_DigestSignInit(ctx.get(), &pctx, md, nullptr, test_state->private_key.get())) { return ssl_private_key_failure; } // Configure additional signature parameters. if (SSL_is_signature_algorithm_rsa_pss(signature_algorithm)) { if (!EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) || !EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, -1 /* salt len = hash len */)) { return ssl_private_key_failure; } } // Write the signature into |test_state|. size_t len = 0; if (!EVP_DigestSign(ctx.get(), nullptr, &len, in, in_len)) { return ssl_private_key_failure; } test_state->private_key_result.resize(len); if (!EVP_DigestSign(ctx.get(), test_state->private_key_result.data(), &len, in, in_len)) { return ssl_private_key_failure; } test_state->private_key_result.resize(len); // The signature will be released asynchronously in |AsyncPrivateKeyComplete|. return ssl_private_key_retry; } static ssl_private_key_result_t AsyncPrivateKeyDecrypt(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out, const uint8_t *in, size_t in_len) { TestState *test_state = GetTestState(ssl); if (!test_state->private_key_result.empty()) { fprintf(stderr, ""AsyncPrivateKeyDecrypt called with operation pending.\\n""); abort(); } RSA *rsa = EVP_PKEY_get0_RSA(test_state->private_key.get()); if (rsa == NULL) { fprintf(stderr, ""AsyncPrivateKeyDecrypt called with incorrect key type.\\n""); abort(); } test_state->private_key_result.resize(RSA_size(rsa)); if (!RSA_decrypt(rsa, out_len, test_state->private_key_result.data(), RSA_size(rsa), in, in_len, RSA_NO_PADDING)) { return ssl_private_key_failure; } test_state->private_key_result.resize(*out_len); // The decryption will be released asynchronously in |AsyncPrivateComplete|. return ssl_private_key_retry; } static ssl_private_key_result_t AsyncPrivateKeyComplete(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out) { TestState *test_state = GetTestState(ssl); if (test_state->private_key_result.empty()) { fprintf(stderr, ""AsyncPrivateKeyComplete called without operation pending.\\n""); abort(); } if (test_state->private_key_retries < 2) { // Only return the decryption on the second attempt, to test both incomplete // |decrypt| and |decrypt_complete|. return ssl_private_key_retry; } if (max_out < test_state->private_key_result.size()) { fprintf(stderr, ""Output buffer too small.\\n""); return ssl_private_key_failure; } OPENSSL_memcpy(out, test_state->private_key_result.data(), test_state->private_key_result.size()); *out_len = test_state->private_key_result.size(); test_state->private_key_result.clear(); test_state->private_key_retries = 0; return ssl_private_key_success; } static const SSL_PRIVATE_KEY_METHOD g_async_private_key_method = { AsyncPrivateKeySign, AsyncPrivateKeyDecrypt, AsyncPrivateKeyComplete, }; static bool InstallCertificate(SSL *ssl) { bssl::UniquePtr x509; bssl::UniquePtr chain; bssl::UniquePtr pkey; if (!GetCertificate(ssl, &x509, &chain, &pkey)) { return false; } if (pkey) { TestState *test_state = GetTestState(ssl); const TestConfig *config = GetTestConfig(ssl); if (config->async) { test_state->private_key = std::move(pkey); SSL_set_private_key_method(ssl, &g_async_private_key_method); } else if (!SSL_use_PrivateKey(ssl, pkey.get())) { return false; } } if (x509 && !SSL_use_certificate(ssl, x509.get())) { return false; } if (sk_X509_num(chain.get()) > 0 && !SSL_set1_chain(ssl, chain.get())) { return false; } return true; } static enum ssl_select_cert_result_t SelectCertificateCallback( const SSL_CLIENT_HELLO *client_hello) { const TestConfig *config = GetTestConfig(client_hello->ssl); GetTestState(client_hello->ssl)->early_callback_called = true; if (!config->expect_server_name.empty()) { const char *server_name = SSL_get_servername(client_hello->ssl, TLSEXT_NAMETYPE_host_name); if (server_name == nullptr || std::string(server_name) != config->expect_server_name) { fprintf(stderr, ""Server name mismatch in early callback (got %s; want %s).\\n"", server_name, config->expect_server_name.c_str()); return ssl_select_cert_error; } } if (config->fail_early_callback) { return ssl_select_cert_error; } // Install the certificate in the early callback. if (config->use_early_callback) { bool early_callback_ready = GetTestState(client_hello->ssl)->early_callback_ready; if (config->async && !early_callback_ready) { // Install the certificate asynchronously. return ssl_select_cert_retry; } if (!InstallCertificate(client_hello->ssl)) { return ssl_select_cert_error; } } return ssl_select_cert_success; } static int SetQuicReadSecret(SSL *ssl, enum ssl_encryption_level_t level, const SSL_CIPHER *cipher, const uint8_t *secret, size_t secret_len) { return GetTestState(ssl)->quic_transport->SetReadSecret(level, cipher, secret, secret_len); } static int SetQuicWriteSecret(SSL *ssl, enum ssl_encryption_level_t level, const SSL_CIPHER *cipher, const uint8_t *secret, size_t secret_len) { return GetTestState(ssl)->quic_transport->SetWriteSecret(level, cipher, secret, secret_len); } static int AddQuicHandshakeData(SSL *ssl, enum ssl_encryption_level_t level, const uint8_t *data, size_t len) { return GetTestState(ssl)->quic_transport->WriteHandshakeData(level, data, len); } static int FlushQuicFlight(SSL *ssl) { return GetTestState(ssl)->quic_transport->Flush(); } static int SendQuicAlert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert) { return GetTestState(ssl)->quic_transport->SendAlert(level, alert); } static const SSL_QUIC_METHOD g_quic_method = { SetQuicReadSecret, SetQuicWriteSecret, AddQuicHandshakeData, FlushQuicFlight, SendQuicAlert, }; bssl::UniquePtr TestConfig::SetupCtx(SSL_CTX *old_ctx) const { bssl::UniquePtr ssl_ctx( SSL_CTX_new(is_dtls ? DTLS_method() : TLS_method())); if (!ssl_ctx) { return nullptr; } CRYPTO_once(&once, init_once); SSL_CTX_set0_buffer_pool(ssl_ctx.get(), g_pool); std::string cipher_list = ""ALL""; if (!cipher.empty()) { cipher_list = cipher; SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE); } if (!SSL_CTX_set_strict_cipher_list(ssl_ctx.get(), cipher_list.c_str())) { return nullptr; } if (async && is_server) { // Disable the internal session cache. To test asynchronous session lookup, // we use an external session cache. SSL_CTX_set_session_cache_mode( ssl_ctx.get(), SSL_SESS_CACHE_BOTH | SSL_SESS_CACHE_NO_INTERNAL); SSL_CTX_sess_set_get_cb(ssl_ctx.get(), GetSessionCallback); } else { SSL_CTX_set_session_cache_mode(ssl_ctx.get(), SSL_SESS_CACHE_BOTH); } SSL_CTX_set_select_certificate_cb(ssl_ctx.get(), SelectCertificateCallback); if (use_old_client_cert_callback) { SSL_CTX_set_client_cert_cb(ssl_ctx.get(), ClientCertCallback); } SSL_CTX_set_next_protos_advertised_cb(ssl_ctx.get(), NextProtosAdvertisedCallback, NULL); if (!select_next_proto.empty()) { SSL_CTX_set_next_proto_select_cb(ssl_ctx.get(), NextProtoSelectCallback, NULL); } if (!select_alpn.empty() || decline_alpn || reject_alpn || select_empty_alpn) { SSL_CTX_set_alpn_select_cb(ssl_ctx.get(), AlpnSelectCallback, NULL); } SSL_CTX_set_channel_id_cb(ssl_ctx.get(), ChannelIdCallback); SSL_CTX_set_current_time_cb(ssl_ctx.get(), CurrentTimeCallback); SSL_CTX_set_info_callback(ssl_ctx.get(), InfoCallback); SSL_CTX_sess_set_new_cb(ssl_ctx.get(), NewSessionCallback); if (use_ticket_callback) { SSL_CTX_set_tlsext_ticket_key_cb(ssl_ctx.get(), TicketKeyCallback); } if (!use_custom_verify_callback) { SSL_CTX_set_cert_verify_callback(ssl_ctx.get(), CertVerifyCallback, NULL); } if (!signed_cert_timestamps.empty() && !SSL_CTX_set_signed_cert_timestamp_list( ssl_ctx.get(), (const uint8_t *)signed_cert_timestamps.data(), signed_cert_timestamps.size())) { return nullptr; } if (!use_client_ca_list.empty()) { if (use_client_ca_list == """") { SSL_CTX_set_client_CA_list(ssl_ctx.get(), nullptr); } else if (use_client_ca_list == """") { bssl::UniquePtr names; SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release()); } else { bssl::UniquePtr names = DecodeHexX509Names(use_client_ca_list); SSL_CTX_set_client_CA_list(ssl_ctx.get(), names.release()); } } if (enable_grease) { SSL_CTX_set_grease_enabled(ssl_ctx.get(), 1); } if (!expect_server_name.empty()) { SSL_CTX_set_tlsext_servername_callback(ssl_ctx.get(), ServerNameCallback); } if (enable_early_data) { SSL_CTX_set_early_data_enabled(ssl_ctx.get(), 1); } if (allow_unknown_alpn_protos) { SSL_CTX_set_allow_unknown_alpn_protos(ssl_ctx.get(), 1); } if (!verify_prefs.empty()) { std::vector u16s(verify_prefs.begin(), verify_prefs.end()); if (!SSL_CTX_set_verify_algorithm_prefs(ssl_ctx.get(), u16s.data(), u16s.size())) { return nullptr; } } SSL_CTX_set_msg_callback(ssl_ctx.get(), MessageCallback); if (allow_false_start_without_alpn) { SSL_CTX_set_false_start_allowed_without_alpn(ssl_ctx.get(), 1); } if (use_ocsp_callback) { SSL_CTX_set_tlsext_status_cb(ssl_ctx.get(), LegacyOCSPCallback); } if (old_ctx) { uint8_t keys[48]; if (!SSL_CTX_get_tlsext_ticket_keys(old_ctx, &keys, sizeof(keys)) || !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), keys, sizeof(keys))) { return nullptr; } CopySessions(ssl_ctx.get(), old_ctx); } else if (!ticket_key.empty() && !SSL_CTX_set_tlsext_ticket_keys(ssl_ctx.get(), ticket_key.data(), ticket_key.size())) { return nullptr; } if (install_cert_compression_algs && (!SSL_CTX_add_cert_compression_alg( ssl_ctx.get(), 0xff02, [](SSL *ssl, CBB *out, const uint8_t *in, size_t in_len) -> int { if (!CBB_add_u8(out, 1) || !CBB_add_u8(out, 2) || !CBB_add_u8(out, 3) || !CBB_add_u8(out, 4) || !CBB_add_bytes(out, in, in_len)) { return 0; } return 1; }, [](SSL *ssl, CRYPTO_BUFFER **out, size_t uncompressed_len, const uint8_t *in, size_t in_len) -> int { if (in_len < 4 || in[0] != 1 || in[1] != 2 || in[2] != 3 || in[3] != 4 || uncompressed_len != in_len - 4) { return 0; } const bssl::Span uncompressed(in + 4, in_len - 4); *out = CRYPTO_BUFFER_new(uncompressed.data(), uncompressed.size(), nullptr); return 1; }) || !SSL_CTX_add_cert_compression_alg( ssl_ctx.get(), 0xff01, [](SSL *ssl, CBB *out, const uint8_t *in, size_t in_len) -> int { if (in_len < 2 || in[0] != 0 || in[1] != 0) { return 0; } return CBB_add_bytes(out, in + 2, in_len - 2); }, [](SSL *ssl, CRYPTO_BUFFER **out, size_t uncompressed_len, const uint8_t *in, size_t in_len) -> int { if (uncompressed_len != 2 + in_len) { return 0; } std::unique_ptr buf(new uint8_t[2 + in_len]); buf[0] = 0; buf[1] = 0; OPENSSL_memcpy(&buf[2], in, in_len); *out = CRYPTO_BUFFER_new(buf.get(), 2 + in_len, nullptr); return 1; }))) { fprintf(stderr, ""SSL_CTX_add_cert_compression_alg failed.\\n""); abort(); } if (server_preference) { SSL_CTX_set_options(ssl_ctx.get(), SSL_OP_CIPHER_SERVER_PREFERENCE); } if (is_quic) { SSL_CTX_set_quic_method(ssl_ctx.get(), &g_quic_method); } return ssl_ctx; } static int DDoSCallback(const SSL_CLIENT_HELLO *client_hello) { const TestConfig *config = GetTestConfig(client_hello->ssl); return config->fail_ddos_callback ? 0 : 1; } static unsigned PskClientCallback(SSL *ssl, const char *hint, char *out_identity, unsigned max_identity_len, uint8_t *out_psk, unsigned max_psk_len) { const TestConfig *config = GetTestConfig(ssl); if (config->psk_identity.empty()) { if (hint != nullptr) { fprintf(stderr, ""Server PSK hint was non-null.\\n""); return 0; } } else if (hint == nullptr || strcmp(hint, config->psk_identity.c_str()) != 0) { fprintf(stderr, ""Server PSK hint did not match.\\n""); return 0; } // Account for the trailing '\\0' for the identity. if (config->psk_identity.size() >= max_identity_len || config->psk.size() > max_psk_len) { fprintf(stderr, ""PSK buffers too small.\\n""); return 0; } OPENSSL_strlcpy(out_identity, config->psk_identity.c_str(), max_identity_len); OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size()); return config->psk.size(); } static unsigned PskServerCallback(SSL *ssl, const char *identity, uint8_t *out_psk, unsigned max_psk_len) { const TestConfig *config = GetTestConfig(ssl); if (strcmp(identity, config->psk_identity.c_str()) != 0) { fprintf(stderr, ""Client PSK identity did not match.\\n""); return 0; } if (config->psk.size() > max_psk_len) { fprintf(stderr, ""PSK buffers too small.\\n""); return 0; } OPENSSL_memcpy(out_psk, config->psk.data(), config->psk.size()); return config->psk.size(); } static ssl_verify_result_t CustomVerifyCallback(SSL *ssl, uint8_t *out_alert) { const TestConfig *config = GetTestConfig(ssl); if (!CheckVerifyCallback(ssl)) { return ssl_verify_invalid; } if (config->async && !GetTestState(ssl)->custom_verify_ready) { return ssl_verify_retry; } GetTestState(ssl)->cert_verified = true; if (config->verify_fail) { return ssl_verify_invalid; } return ssl_verify_ok; } static int CertCallback(SSL *ssl, void *arg) { const TestConfig *config = GetTestConfig(ssl); // Check the peer certificate metadata is as expected. if ((!SSL_is_server(ssl) && !CheckCertificateRequest(ssl)) || !CheckPeerVerifyPrefs(ssl)) { return -1; } if (config->fail_cert_callback) { return 0; } // The certificate will be installed via other means. if (!config->async || config->use_early_callback) { return 1; } if (!GetTestState(ssl)->cert_ready) { return -1; } if (!InstallCertificate(ssl)) { return 0; } return 1; } bssl::UniquePtr TestConfig::NewSSL( SSL_CTX *ssl_ctx, SSL_SESSION *session, bool is_resume, std::unique_ptr test_state) const { bssl::UniquePtr ssl(SSL_new(ssl_ctx)); if (!ssl) { return nullptr; } if (!SetTestConfig(ssl.get(), this)) { return nullptr; } if (test_state != nullptr) { if (!SetTestState(ssl.get(), std::move(test_state))) { return nullptr; } GetTestState(ssl.get())->is_resume = is_resume; } if (fallback_scsv && !SSL_set_mode(ssl.get(), SSL_MODE_SEND_FALLBACK_SCSV)) { return nullptr; } // Install the certificate synchronously if nothing else will handle it. if (!use_early_callback && !use_old_client_cert_callback && !async && !InstallCertificate(ssl.get())) { return nullptr; } if (!use_old_client_cert_callback) { SSL_set_cert_cb(ssl.get(), CertCallback, nullptr); } int mode = SSL_VERIFY_NONE; if (require_any_client_certificate) { mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; } if (verify_peer) { mode = SSL_VERIFY_PEER; } if (verify_peer_if_no_obc) { // Set SSL_VERIFY_FAIL_IF_NO_PEER_CERT so testing whether client // certificates were requested is easy. mode = SSL_VERIFY_PEER | SSL_VERIFY_PEER_IF_NO_OBC | SSL_VERIFY_FAIL_IF_NO_PEER_CERT; } if (use_custom_verify_callback) { SSL_set_custom_verify(ssl.get(), mode, CustomVerifyCallback); } else if (mode != SSL_VERIFY_NONE) { SSL_set_verify(ssl.get(), mode, NULL); } if (false_start) { SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_FALSE_START); } if (cbc_record_splitting) { SSL_set_mode(ssl.get(), SSL_MODE_CBC_RECORD_SPLITTING); } if (partial_write) { SSL_set_mode(ssl.get(), SSL_MODE_ENABLE_PARTIAL_WRITE); } if (reverify_on_resume) { SSL_CTX_set_reverify_on_resume(ssl_ctx, 1); } if (enforce_rsa_key_usage) { SSL_set_enforce_rsa_key_usage(ssl.get(), 1); } if (no_tls13) { SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_3); } if (no_tls12) { SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_2); } if (no_tls11) { SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1_1); } if (no_tls1) { SSL_set_options(ssl.get(), SSL_OP_NO_TLSv1); } if (no_ticket) { SSL_set_options(ssl.get(), SSL_OP_NO_TICKET); } if (!expect_channel_id.empty() || enable_channel_id) { SSL_set_tls_channel_id_enabled(ssl.get(), 1); } if (enable_ech_grease) { SSL_set_enable_ech_grease(ssl.get(), 1); } if (!send_channel_id.empty()) { SSL_set_tls_channel_id_enabled(ssl.get(), 1); if (!async) { // The async case will be supplied by |ChannelIdCallback|. bssl::UniquePtr pkey = LoadPrivateKey(send_channel_id); if (!pkey || !SSL_set1_tls_channel_id(ssl.get(), pkey.get())) { return nullptr; } } } if (!send_token_binding_params.empty()) { SSL_set_token_binding_params( ssl.get(), reinterpret_cast(send_token_binding_params.data()), send_token_binding_params.length()); } if (!host_name.empty() && !SSL_set_tlsext_host_name(ssl.get(), host_name.c_str())) { return nullptr; } if (!advertise_alpn.empty() && SSL_set_alpn_protos( ssl.get(), reinterpret_cast(advertise_alpn.data()), advertise_alpn.size()) != 0) { return nullptr; } if (!defer_alps) { for (const auto &pair : application_settings) { if (!SSL_add_application_settings( ssl.get(), reinterpret_cast(pair.first.data()), pair.first.size(), reinterpret_cast(pair.second.data()), pair.second.size())) { return nullptr; } } } if (!psk.empty()) { SSL_set_psk_client_callback(ssl.get(), PskClientCallback); SSL_set_psk_server_callback(ssl.get(), PskServerCallback); } if (!psk_identity.empty() && !SSL_use_psk_identity_hint(ssl.get(), psk_identity.c_str())) { return nullptr; } if (!srtp_profiles.empty() && !SSL_set_srtp_profiles(ssl.get(), srtp_profiles.c_str())) { return nullptr; } if (enable_ocsp_stapling) { SSL_enable_ocsp_stapling(ssl.get()); } if (enable_signed_cert_timestamps) { SSL_enable_signed_cert_timestamps(ssl.get()); } if (min_version != 0 && !SSL_set_min_proto_version(ssl.get(), (uint16_t)min_version)) { return nullptr; } if (max_version != 0 && !SSL_set_max_proto_version(ssl.get(), (uint16_t)max_version)) { return nullptr; } if (mtu != 0) { SSL_set_options(ssl.get(), SSL_OP_NO_QUERY_MTU); SSL_set_mtu(ssl.get(), mtu); } if (install_ddos_callback) { SSL_CTX_set_dos_protection_cb(ssl_ctx, DDoSCallback); } SSL_set_shed_handshake_config(ssl.get(), true); if (renegotiate_once) { SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_once); } if (renegotiate_freely || forbid_renegotiation_after_handshake) { // |forbid_renegotiation_after_handshake| will disable renegotiation later. SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_freely); } if (renegotiate_ignore) { SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_ignore); } if (renegotiate_explicit) { SSL_set_renegotiate_mode(ssl.get(), ssl_renegotiate_explicit); } if (!check_close_notify) { SSL_set_quiet_shutdown(ssl.get(), 1); } if (!curves.empty()) { std::vector nids; for (auto curve : curves) { switch (curve) { case SSL_CURVE_SECP224R1: nids.push_back(NID_secp224r1); break; case SSL_CURVE_SECP256R1: nids.push_back(NID_X9_62_prime256v1); break; case SSL_CURVE_SECP384R1: nids.push_back(NID_secp384r1); break; case SSL_CURVE_SECP521R1: nids.push_back(NID_secp521r1); break; case SSL_CURVE_X25519: nids.push_back(NID_X25519); break; case SSL_CURVE_CECPQ2: nids.push_back(NID_CECPQ2); break; } if (!SSL_set1_curves(ssl.get(), &nids[0], nids.size())) { return nullptr; } } } if (initial_timeout_duration_ms > 0) { DTLSv1_set_initial_timeout_duration(ssl.get(), initial_timeout_duration_ms); } if (max_cert_list > 0) { SSL_set_max_cert_list(ssl.get(), max_cert_list); } if (retain_only_sha256_client_cert) { SSL_set_retain_only_sha256_of_client_certs(ssl.get(), 1); } if (max_send_fragment > 0) { SSL_set_max_send_fragment(ssl.get(), max_send_fragment); } if (quic_use_legacy_codepoint != -1) { SSL_set_quic_use_legacy_codepoint(ssl.get(), quic_use_legacy_codepoint); } if (!quic_transport_params.empty()) { if (!SSL_set_quic_transport_params( ssl.get(), reinterpret_cast(quic_transport_params.data()), quic_transport_params.size())) { return nullptr; } } if (jdk11_workaround) { SSL_set_jdk11_workaround(ssl.get(), 1); } if (session != NULL) { if (!is_server) { if (SSL_set_session(ssl.get(), session) != 1) { return nullptr; } } else if (async) { // The internal session cache is disabled, so install the session // manually. SSL_SESSION_up_ref(session); GetTestState(ssl.get())->pending_session.reset(session); } } if (!delegated_credential.empty()) { std::string::size_type comma = delegated_credential.find(','); if (comma == std::string::npos) { fprintf(stderr, ""failed to find comma in delegated credential argument.\\n""); return nullptr; } const std::string dc_hex = delegated_credential.substr(0, comma); const std::string pkcs8_hex = delegated_credential.substr(comma + 1); std::string dc, pkcs8; if (!HexDecode(&dc, dc_hex) || !HexDecode(&pkcs8, pkcs8_hex)) { fprintf(stderr, ""failed to hex decode delegated credential argument.\\n""); return nullptr; } CBS dc_cbs(bssl::Span( reinterpret_cast(dc.data()), dc.size())); CBS pkcs8_cbs(bssl::Span( reinterpret_cast(pkcs8.data()), pkcs8.size())); bssl::UniquePtr priv(EVP_parse_private_key(&pkcs8_cbs)); if (!priv) { fprintf(stderr, ""failed to parse delegated credential private key.\\n""); return nullptr; } bssl::UniquePtr dc_buf( CRYPTO_BUFFER_new_from_CBS(&dc_cbs, nullptr)); if (!SSL_set1_delegated_credential(ssl.get(), dc_buf.get(), priv.get(), nullptr)) { fprintf(stderr, ""SSL_set1_delegated_credential failed.\\n""); return nullptr; } } if (!quic_early_data_context.empty() && !SSL_set_quic_early_data_context( ssl.get(), reinterpret_cast(quic_early_data_context.data()), quic_early_data_context.size())) { return nullptr; } return ssl; } ",16281,True,2703.0286983980627,median "// rvm use 2.3@asciidoctor.org --create // asciidoctor -D /tmp/ -a data-uri user-manual.adoc // Document conventions: // * directory (not folder) // * set/unset attributes (not define) // * US spelling (single t in formating, ize not ise, color). // * e.g. not eg // * ""AsciiDoc"" is the language, ""AsciiDoc Python"" is the original processor, ""Asciidoctor"" is the modern processor. // * Processors ""convert"" AsciiDoc to whatever, browsers ""render"" content. // * The author is ""we"" or ""Asciidoctor"" // * The reader is ""you"" = Asciidoctor User Manual Sarah White ; Dan Allen :description: This guide describes the Asciidoctor attributes, values, and layout options available for producing a customized and polished document. :keywords: AsciiDoc, Asciidoctor, syntax, reference, learn, how to, AsciiMath, LaTeX math, MathJax, Pygments, CodeRay :doctype: book :compat-mode!: :page-layout!: :toc: left :toclevels: 2 :sectanchors: :sectlinks: :sectnums: :linkattrs: :icons: font :source-highlighter: coderay :source-language: asciidoc :experimental: :stem: :idprefix: :idseparator: - :ast: * :dagger: pass:normal[^†^] :endash: – :y: icon:check[role=""green""] :n: icon:times[role=""red""] :c: icon:file-text-o[role=""blue""] :table-caption!: :example-caption!: :figure-caption!: :imagesdir: ../images :includedir: _includes :underscore: _ :adp: AsciiDoc Python :adr: Asciidoctor // Refs :uri-home: http://asciidoctor.org :uri-gem: http://rubygems.org/gems/asciidoctor :uri-org: https://github.com/asciidoctor :uri-repo: {uri-org}/asciidoctor :uri-tilt: https://github.com/rtomayko/tilt :uri-jruby: http://jruby.org :uri-man: {uri-home}/man/asciidoctor :uri-rewrite: https://github.com/ocpsoft/rewrite/tree/master/transform-markup :markup-ref: http://en.wikipedia.org/wiki/Lightweight_markup_language :markdown-ref: http://daringfireball.net/projects/markdown :fedora-docs: http://docs.fedoraproject.org :java: http://asciidoctor.org/docs/asciidoctorj :uri-anttask: https://github.com/asciidoctor/asciidoctor-ant#asciidoctor-ant-task :tests: https://github.com/asciidoctor/asciidoctor/tree/master/test :asciidoc-edit-ref: http://asciidoc.org/#_editor_support :docref: link:/docs :doc-asciidoctorj: {docref}/asciidoctorj :editing-ref: {docref}/editing-asciidoc-with-live-preview :asciidoclet-ref: {docref}/install-and-use-asciidoclet/ :docbook-info-ref: http://www.docbook.org/tdg5/en/html/info.html :richfaces-docinfo: https://github.com/richfaces/richfaces-docs/blob/master/Developer_Guide/src/main/docbook/en-US/Developer_Guide-docinfo.xml :air-ref: http://en.wikipedia.org/wiki/Air_quotes :uri-xml: http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references :uri-unicode: http://en.wikipedia.org/wiki/List_of_Unicode_characters :fontawesome-ref: http://fortawesome.github.io/Font-Awesome/ :factory-ref: http://github.com/asciidoctor/asciidoctor-stylesheet-factory :uri-http: http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html :pygments-org: http://pygments.org :pygments-gem: https://rubygems.org/gems/pygments.rb :pygments-lang: {pygments-org}/languages/ :coderay-uri: http://coderay.rubychan.de/ :coderay-gem: https://rubygems.org/gems/coderay :highlightjs-org: https://highlightjs.org/ :highlightjs-lang: https://highlightjs.org/download/ :showcase-ref: http://themes.asciidoctor.org/preview/ :uri-docbook5: http://www.docbook.org/tdg5/en/html/ch01.html#introduction-whats-new :uri-yelp: https://wiki.gnome.org/action/show/Apps/Yelp :publican: http://fedorahosted.org/publican :uri-a2x-manpage: http://asciidoc.org/a2x.1.html :man-raw: https://raw.githubusercontent.com/asciidoctor/asciidoctor/master/man/asciidoctor.adoc :fopub-ref: https://github.com/asciidoctor/asciidoctor-fopub :fopub-doc-ref: https://github.com/asciidoctor/asciidoctor-fopub/blob/master/README.adoc :guard-doc-ref: https://github.com/asciidoctor/guard-asciidoc/blob/master/README.adoc :backend-git: http://github.com/asciidoctor/asciidoctor-backends :deckjs-org: http://imakewebthings.com/deck.js :deckjs-git: https://github.com/imakewebthings/deck.js :deckjs-zip: {deckjs-git}/archive/latest.zip :decksplitjs-git: https://github.com/houqp/deck.split.js :compass-ref: http://compass-style.org :sass-ref: http://sass-lang.com :uri-foundation: http://foundation.zurb.com :get-ruby-ref: http://www.ruby-lang.org/en/downloads :bundler-ref: http://rubygems.org/gems/bundler :issue-ref: https://github.com/asciidoctor/asciidoctor/issues :license: https://github.com/asciidoctor/asciidoctor/blob/master/LICENSE.adoc :mojavelinux: https://github.com/mojavelinux :erebor: https://github.com/erebor :lightguard: https://github.com/lightguard :nickh: http://github.com/nickh :contributors: https://github.com/asciidoctor/asciidoctor/graphs/contributors :gitscm-next: https://github.com/github/gitscm-next :seed-contribution: https://github.com/github/gitscm-next/commits/master/lib/asciidoc.rb :uri-asciimath: http://docs.mathjax.org/en/latest/asciimath.html :uri-latexmath: http://docs.mathjax.org/en/latest/tex.html :uri-mathjax: http://www.mathjax.org :uri-mathjax-docs: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference :uri-mailinglist: http://discuss.asciidoctor.org :uri-ad-org-issues: https://github.com/asciidoctor/asciidoctor.org/issues :uri-asciidoctorj: {uri-org}/asciidoctorj :uri-asciidoctorjs: {uri-org}/asciidoctor.js :uri-irc: irc://irc.freenode.org/#asciidoctor :uri-asciidoc-leveloffset: http://asciidoc.org/userguide.html#X90 :uri-asciidoctor-pdf: https://github.com/asciidoctor/asciidoctor-pdf :uri-asciidoctor-pdf-readme: https://github.com/asciidoctor/asciidoctor-pdf/blob/master/README.adoc :uri-asciidoctor-pdf-theming-guide: http://gist.asciidoctor.org/?github-asciidoctor%2Fasciidoctor-pdf%2F%2Fdocs%2Ftheming-guide.adoc [NOTE] .This document is under active development and discussion! ==== If you find errors or omissions in this document, please don't hesitate to {uri-ad-org-issues}[submit an issue or open a pull request] with a fix. We also encourage you to ask questions and discuss any aspects of the project on the {uri-mailinglist}[mailing list] or {uri-irc}[IRC]. New contributors are always welcome! ==== This manual assumes you are using Asciidoctor to produce and render your document. Asciidoctor implements more syntax, attributes and functions than the legacy AsciiDoc.py processor. <> lists which features are available to the Asciidoctor and AsciiDoc processors. //// == Navigating this document The first sections define the general concepts and terms used by Asciidoctor Next, each Asciidoctor feature, its capabilities, and how it can be customized is reviewed. And when applicable, the feature's attributes and options are summarized in a table at the section's end. //// = Introduction to Asciidoctor .Discuss and Contribute TIP: Use {uri-ad-org-issues}/433[Issue 433] to drive development of this section. Your contributions make a difference. No contribution is too small. include::{includedir}/about-asciidoctor.adoc[] === Asciidoctor's Most Notable Benefits include::{includedir}/benefits.adoc[] ==== AsciiDoc Syntax Processing Asciidoctor reads and parses text written in the AsciiDoc syntax, then feeds the parse tree into a set of built-in templates to produce HTML5, PDF, DocBook 5, etc. You have the option of writing your own converter or providing {uri-tilt}[Tilt]-supported templates to customize the generated output or produce alternative formats. NOTE: Asciidoctor is a drop-in replacement for the original AsciiDoc Python processor (`asciidoc.py`). The Asciidoctor test suite has > 1,500 tests to ensure compatibility with the AsciiDoc syntax. In addition to the standard AsciiDoc syntax, Asciidoctor recognizes additional markup and formatting options, such as font-based icons (e.g., [x-]`icon:fire[]`) and UI elements (e.g., [x-]`button:[Save]`). Asciidoctor also offers a modern, responsive theme based on {uri-foundation}[Foundation] to style the HTML5 output. //// === Compared to AsciiDoc .Discuss and Contribute TIP: Use {uri-ad-org-issues}/434[Issue 434] to drive development of this section. Your contributions make a difference. No contribution is too small. //// //// .What is AsciiDoc? AsciiDoc is two things: . A mature{empty}footnote:[AsciiDoc is over 10 years old. It was first introduced in 2002.], plain-text format for authoring notes, articles, documentation, books, ebooks, web pages, slide decks, blog posts, man pages and more. . A text processor and toolchain for translating AsciiDoc documents into various formats (called _backends_), including HTML, DocBook, PDF and ePub{empty}footnote:[There are two implementations of the AsciiDoc processor. The original processor, named AsciiDoc, is written in Python. A more modern implementation, named Asciidoctor, is written in Ruby.]. AsciiDoc belongs to the family of {markup-ref}[lightweight markup languages], the most renowned of which is {markdown-ref}[Markdown]. AsciiDoc stands out from this group because it supports all the structural elements necessary for drafting articles, technical manuals, books, presentations and prose. In fact, it's capable of meeting even the most advanced publishing requirements and technical semantics. Serving as testament of this fact, many O'Reilly authors, including https://github.com/matthewmccullough[Matthew McCullough], https://github.com/tlberglund[Tim Berglund], https://github.com/oreillymedia/etudes-for-erlang[Simon St.Laurent] and http://www.apeth.net/matt/iosbooktoolchain.html[Matt Neuburg], have used AsciiDoc to write their books for that iconic technical library. From the very beginning, AsciiDoc was designed to be a shorthand replacement for http://www.docbook.org/whatis[DocBook], one of the formats AsciiDoc can generate. AsciiDoc can also produce beautiful HTML 5, PDFs, eBooks, man pages and even slide decks. It has you covered from first draft to publishing. //// === Compared to MarkDown include::{includedir}/asciidoc-vs-markdown.adoc[] = Quick Starts [partintro] -- NOTE: Section Pending -- == Installation Quick Start .Discuss and Contribute TIP: Use {uri-ad-org-issues}/436[Issue 436] to drive development of this section. Your contributions make a difference. No contribution is too small. == Usage Quick Start .Discuss and Contribute TIP: Use {uri-ad-org-issues}/437[Issue 437] to drive development of this section. Your contributions make a difference. No contribution is too small. === Using the Command Line Interface include::{includedir}/command-line-usage.adoc[] === Using the Ruby API include::{includedir}/api-intro.adoc[] include::{includedir}/load-render-api.adoc[] You can also use the API to <> and <>. == Syntax Quick Start .Discuss and Contribute TIP: Use {uri-ad-org-issues}/441[Issue 441] to drive development of this section. Your contributions make a difference. No contribution is too small. == Custom Output Quick Start .Discuss and Contribute TIP: Use {uri-ad-org-issues}/442[Issue 442] to drive development of this section. Your contributions make a difference. No contribution is too small. = Getting Started [partintro] -- NOTE: Section Pending -- == System Requirements include::{includedir}/install-upgrade-asciidoctor.adoc[tags=systemreq] == Installing the Asciidoctor Ruby Gem include::{includedir}/install-upgrade-asciidoctor.adoc[tags=intro] === Install using `gem` include::{includedir}/install-upgrade-asciidoctor.adoc[tags=gem] === Install using Bundler include::{includedir}/install-upgrade-asciidoctor.adoc[tags=bundler] === Install using `yum` or `dnf` on Fedora include::{includedir}/install-upgrade-asciidoctor.adoc[tag=yum] === Install using `apt-get` on Debian or Ubuntu include::{includedir}/install-upgrade-asciidoctor.adoc[tag=aptget] === Install using `apk` on Alpine Linux include::{includedir}/install-upgrade-asciidoctor.adoc[tag=apk] == Upgrading the Asciidoctor Ruby Gem include::{includedir}/install-upgrade-asciidoctor.adoc[tags=upgrade] == Extensions and Integrations See <>. = Terms and Concepts [partintro] -- All of the content in an Asciidoctor document, including lines of text, predefined styles, and processing commands, is classified as either a block or an inline element. Within each of these elements are an array of styles, options, and functions that can be applied to your content. This section will provide you with an overview of what each of these elements and sub-elements are and the basic syntax and rules for using them. -- == Elements include::{includedir}/element.adoc[] == Macros .Discuss and Contribute TIP: Use {uri-ad-org-issues}/443[Issue 443] to drive development of this section. Your contributions make a difference. No contribution is too small. == Formatting Marks include::{includedir}/formatting-marks.adoc[] == Attributes include::{includedir}/attr.adoc[tags=intro] include::{includedir}/attr.adoc[tags=attributesyntax] === Attribute Assignment Precedence include::{includedir}/attr.adoc[tags=order] === Using Attributes: Set, Assign, and Reference include::{includedir}/attr-use.adoc[] === Setting Attributes on a Document include::{includedir}/attr-doc.adoc[] === Setting Attributes on an Element include::{includedir}/attr-element.adoc[tags=intro] ==== Positional Attribute include::{includedir}/attr-element.adoc[tags=pos] ==== Named Attribute include::{includedir}/attr-element.adoc[tags=name] ==== Style include::{includedir}/attr-style.adoc[tags=intro] ==== Id include::{includedir}/attr-style.adoc[tags=id] ===== Block Assignment include::{includedir}/attr-style.adoc[tags=bl] ===== Inline Assignment include::{includedir}/attr-style.adoc[tags=in] ==== Role NOTE: Section introduction pending An element can be assigned numerous roles. ===== Block Assignment In an attribute list, there are two ways to assign a role attribute to a block element. . Prefixing the name with a dot (`.`). . Specifying the name with `role=`. [source] ---- [.summary] * Review 1 * Review 2 ---- [source] ---- [role=""summary""] * Review 1 * Review 2 ---- To specify multiple roles using the shorthand syntax, separate them by dots. [source] ---- [.summary.incremental] * Review 1 * Review 2 ---- [source] ---- [role=""summary,incremental""] * Review 1 * Review 2 ---- ===== Inline Assignment The role (`.`) shorthand can be used on inline quoted text. .Quoted text with role assignments using traditional AsciiDoc syntax ---- [big goal]*free the world* ---- .Quoted text with role assignments using Asciidoctor shorthand ---- [.big.goal]*free the world* ---- TIP: The attribute list preceding formatted text can be escaped using a backslash (e.g., `+[role]*bold*+`). In this case, the text will still be formatted, but the attribute list will be unescaped and output verbatim. .Role-playing for text enclosed in backticks To align with other formatted (i.e., quoted) text in AsciiDoc, roles can now be assigned to text enclosed in backticks. Given: ``` [rolename]`monospace text` ``` the following HTML is produced: ```html monospace text ``` Using the shorthand notation, an id (i.e., anchor) can also be specified: ``` [#idname.rolename]`monospace text` ``` which produces: ```html monospace text ``` ==== Options The options attribute is a versatile named attribute that can contain a comma separated list of values. It can also be defined globally with an attribute entry. ===== Block Assignment In an attribute list, there are three ways to assign an options attribute to a block element. . Prefixing the value with a percent sign (`%`). . Specifying the value with `opts=` . Specifying the value with `options=`. Consider a table block with the three option values `header`, `footer`, and `autowidth`. Here's how the options are assigned to the table using the shorthand notation (`%`). .Shorthand Asciidoctor syntax ---- [%header%footer%autowidth] |=== | Cell A | Cell B |=== ---- Here's how the options are assigned to the table using `options`. .Traditional AsciiDoc syntax ---- [options=""header,footer,autowidth""] |=== | Cell A | Cell B |=== ---- Let's consider the options when combined with other attributes. .Shorthand Asciidoctor block syntax ---- [horizontal.properties%step] property 1:: does stuff property 2:: does different stuff ---- .Traditional AsciiDoc block syntax ---- [horizontal, role=""properties"", options=""step""] property 1:: does stuff property 2:: does different stuff ---- === Assigning Document Attributes Inline Document attributes can be assigned using the following syntax: {set:[!][:]} For example: [source] {set:sourcedir:src/main/java} is effectively the same as: :sourcedir: src/main/java This is important for being able to assign document attributes in places where attribute entry lines are not normally processed, such as in a table cell. === Attribute Conventions .Discuss and Contribute TIP: Use {uri-ad-org-issues}/444[Issue 444] to drive development of this section. Your contributions make a difference. No contribution is too small. ==== Catch a Missing or Undefined Attribute include::{includedir}/attr-miss.adoc[] = Building a Document [partintro] -- NOTE: Introduction Pending -- == Text Editor include::{includedir}/text-editor.adoc[] == Document Types include::{includedir}/doctype.adoc[] == Basic Document Anatomy .Discuss and Contribute TIP: Use {uri-ad-org-issues}/445[Issue 445] to drive development of this section. Your contributions make a difference. No contribution is too small. [#doc-header] == Header include::{includedir}/header-intro.adoc[] === Document Title include::{includedir}/header-title.adoc[] === Author and Email include::{includedir}/author.adoc[] === Revision Number, Date and Remark include::{includedir}/revision.adoc[] === Subtitle Partitioning include::{includedir}/subtitle.adoc[] === Metadata include::{includedir}/meta.adoc[tags=intro] ==== Description include::{includedir}/meta.adoc[tags=desc] ==== Keywords include::{includedir}/meta.adoc[tags=key] ==== Alternate Title include::{includedir}/meta.adoc[tags=atitle] ==== Custom Metadata, Styles and Functions include::{includedir}/meta.adoc[tags=cmeta] === Header Summary include::{includedir}/sum-header.adoc[] [[doc-preamble]] == Preamble include::{includedir}/preamble-tut.adoc[] == Sections include::{includedir}/sections.adoc[tags=intro] === Titles as HTML Headings include::{includedir}/sections.adoc[tags=heading] === Auto-generated IDs include::{includedir}/sections.adoc[tags=autoid] === Custom IDs include::{includedir}/sections.adoc[tags=custom-id] === Links include::{includedir}/sections.adoc[tags=link] === Anchors include::{includedir}/sections.adoc[tags=anchor] === Numbering include::{includedir}/sections.adoc[tags=number] === Discrete Headings (aka Floating Titles) include::{includedir}/discrete-heading.adoc[] === Section Styles include::{includedir}/section-styles.adoc[] === Sections Summary include::{includedir}/sum-section.adoc[] == Blocks include::{includedir}/block.adoc[] == Paragraph include::{includedir}/para.adoc[] === Line Breaks include::{includedir}/para-line-break.adoc[] === Lead Style include::{includedir}/para-lead.adoc[] == Text Formatting include::{includedir}/text.adoc[] === Bold and Italic include::{includedir}/text-bold-italic.adoc[] [[curved]] === Quotation Marks and Apostrophes include::{includedir}/text-quote-apos.adoc[] === Subscript and Superscript include::{includedir}/text-sub-sup.adoc[] [[mono]] === Monospace include::{includedir}/text-mono.adoc[] === Custom Styling With Attributes include::{includedir}/text-css.adoc[] == Unordered Lists include::{includedir}/u-list.adoc[] === Nested include::{includedir}/u-list-nest.adoc[] === Complex List Content include::{includedir}/u-list-complex.adoc[] === Custom Markers include::{includedir}/u-list-marker.adoc[] === Checklist include::{includedir}/u-list-check.adoc[] === Summary .Discuss and Contribute TIP: Use {uri-ad-org-issues}/466[Issue 466] to drive development of this section. Your contributions make a difference. No contribution is too small. == Ordered Lists include::{includedir}/o-list.adoc[] === Nested include::{includedir}/o-list-nest.adoc[] === Numbering Styles include::{includedir}/o-list-num.adoc[] === Summary .Discuss and Contribute TIP: Use {uri-ad-org-issues}/446[Issue 446] to drive development of this section. Your contributions make a difference. No contribution is too small. == Labeled List include::{includedir}/dlist.adoc[] === Question and Answer Style List include::{includedir}/dlist-qa.adoc[] === Summary .Discuss and Contribute TIP: Use {uri-ad-org-issues}/447[Issue 447] to drive development of this section. Your contributions make a difference. No contribution is too small. == Tables include::{includedir}/table.adoc[] include::{includedir}/table-col.adoc[] include::{includedir}/table-cell.adoc[] include::{includedir}/table-formatting.adoc[] include::{includedir}/table-data.adoc[] [#summary-tables] === Summary include::{includedir}/sum-table.adoc[] == Horizontal Rules include::{includedir}/hr.adoc[] == Page Break include::{includedir}/page-break.adoc[] [[url]] == URLs include::{includedir}/url.adoc[] === Link to Relative Files include::{includedir}/url-relative.adoc[] === Summary include::{includedir}/sum-url.adoc[] [[xref]] == Cross References A link to another location within an AsciiDoc document or between AsciiDoc documents is called a _cross reference_ (also referred to as an _xref_). To be able to create a cross reference, you first need to define the location where the reference will point to. This is the anchor definition. [[anchordef]] === Defining an Anchor include::{includedir}/xref-anchor.adoc[] === Internal Cross References include::{includedir}/xref.adoc[] === Customizing the Cross Reference Text include::{includedir}/xrefstyle.adoc[] === Inter-document Cross References include::{includedir}/xref-interdoc.adoc[] == Include Directive include::{includedir}/include-directive.adoc[] [[include-partial]] === Select Portions of a Document to Include include::{includedir}/include-lines-tags.adoc[] === Normalize Block Indentation include::{includedir}/indent-include.adoc[] [[include-uri]] === Include Content from a URI include::{includedir}/uri-include.adoc[] [[include-multiple]] === Include a File Multiple Times in the Same Document include::{includedir}/multiple-include.adoc[] == Images include::{includedir}/image.adoc[] === Setting the Location of Images include::{includedir}/image-dir.adoc[] ==== Include Images by Full URL include::{includedir}/image-url.adoc[] === Putting Images in Their Place include::{includedir}/image-position.adoc[] === Sizing Images include::{includedir}/image-sizing.adoc[] === Summary include::{includedir}/sum-image.adoc[] == Video include::{includedir}/video.adoc[] === Supported Attributes include::{includedir}/sum-video.adoc[] == Audio NOTE: Pending //// Macro name: audio::ocean_waves.mp3[options=loop] //// === Summary include::{includedir}/sum-audio.adoc[] == Admonition include::{includedir}/admonition.adoc[] == Sidebar include::{includedir}/sidebar.adoc[] == Example include::{includedir}/example.adoc[] == Prose Excerpts, Quotes and Verses include::{includedir}/quote.adoc[tags=intro] === Quote include::{includedir}/quote.adoc[tags=basic] include::{includedir}/quote-alt.adoc[] === Verse include::{includedir}/verse.adoc[] == Comments include::{includedir}/comment.adoc[] = Controlling Your Content [partintro] -- NOTE: Part introduction pending -- [[subs]] == Text Substitutions include::{includedir}/subs.adoc[] === Special Characters include::{includedir}/subs-specchar.adoc[] === Quotes include::{includedir}/subs-quote.adoc[] === Attributes include::{includedir}/subs-attr.adoc[] === Replacements include::{includedir}/subs-repl.adoc[] [[subs-mac]] === Macros include::{includedir}/subs-macro.adoc[] === Post Replacements include::{includedir}/subs-post.adoc[] === Applying Substitutions include::{includedir}/subs-apply.adoc[] === Preventing Substitutions include::{includedir}/subs-prevent.adoc[] == Literal Text and Blocks include::{includedir}/literal.adoc[] == Listing Blocks include::{includedir}/listing.adoc[] === To Wrap or to Scroll include::{includedir}/listing-wrap.adoc[] === Summary NOTE: Pending [#passthroughs] == Passthroughs include::{includedir}/pass-intro.adoc[] [#pass-macros] === Passthrough Macros include::{includedir}/pass-macro.adoc[] ==== Nesting blocks and passthrough macros When you're using passthroughs inside literal and listing blocks, it can be easy to forget that the triple-plus, double-dollar, and backtick passthroughs are macros (not quotes). If you want to enable the passthroughs, make sure to assign the `macros` value to the `subs` attribute. .... [source,java,subs=""+quotes,+macros""] ---- protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() **.antMatchers(""/resources/$$**$$"").permitAll()** .anyRequest().authenticated() .and() .formLogin() .loginPage(""/login"") .permitAll(); ---- .... ==== [source,java,subs=""+quotes,+macros""] ---- protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() **.antMatchers(""/resources/$$**$$"").permitAll()** .anyRequest().authenticated() .and() .formLogin() .loginPage(""/login"") .permitAll(); ---- ==== [#pass-blocks] === Passthrough Blocks include::{includedir}/pass-block.adoc[] == Open Blocks include::{includedir}/open.adoc[] = Enriching Your Content [partintro] -- NOTE: Part introduction pending -- [[stem]] == Equations and Formulas include::{includedir}/stem.adoc[tags=intro] [[stem-in]] === Inline Stem Content include::{includedir}/stem.adoc[tags=in] [[stem-bl]] === Block Stem Content include::{includedir}/stem.adoc[tags=bl] === Using Multiple Stem Interpreters include::{includedir}/stem.adoc[tags=inter] [#stem-docbook] === Enabling STEM expressions in the DocBook Toolchain include::{includedir}/stem.adoc[tag=docbook] == User Interface Macros include::{includedir}/ui.adoc[] == Icons include::{includedir}/icons.adoc[] [[syntax-highlighting]] [[source-code-blocks]] == Syntax Highlighting Source Code include::{includedir}/src.adoc[] === Pygments include::{includedir}/src-pygments.adoc[] === CodeRay include::{includedir}/src-coderay.adoc[] === highlight.js include::{includedir}/src-highlightjs.adoc[] == Callouts include::{includedir}/callout-intro.adoc[] === Copy and Paste Friendly Callouts include::{includedir}/callout-copy.adoc[] ==== XML Callouts include::{includedir}/callout-xml.adoc[] === Callout Icons include::{includedir}/callout-icon.adoc[] == Conditional Preprocessor Directives include::{includedir}/conditional-preprocessor-directives.adoc[] [#docinfo-file] == Docinfo Files include::{includedir}/docinfo.adoc[] == Counters include::{includedir}/counter.adoc[] = Structuring, Navigating, and Referencing Your Content [partintro] -- include::{includedir}/structure-intro.adoc[] -- == Title Page .Discuss and Contribute TIP: Use {uri-ad-org-issues}/448[Issue 448] to drive development of this section. Your contributions make a difference. No contribution is too small. [[user-colophon]] == Colophon include::{includedir}/colophon.adoc[] [#user-toc] == Table of Contents include::{includedir}/toc-intro.adoc[] [#manual-placement] === In-Document Placement include::{includedir}/toc-layout.adoc[tags=place] [#left-or-right-column-layout] === Side Column Placement include::{includedir}/toc-layout.adoc[tags=column] [#user-toc-title] === Title include::{includedir}/toc-custom.adoc[tags=title] [#user-toc-levels] === Levels include::{includedir}/toc-custom.adoc[tags=level] === Using a TOC with Embeddable HTML include::{includedir}/toc-embeddable-html.adoc[] === Table of Contents Summary include::{includedir}/sum-toc.adoc[] [[user-abstract]] == Abstract include::{includedir}/abstract.adoc[] [[user-preface]] == Preface include::{includedir}/preface.adoc[] [[user-dedication]] == Dedication include::{includedir}/dedication.adoc[] [[book-parts-and-chapters]] == Book Parts and Chapters include::{includedir}/book-part.adoc[] [[user-appendix]] == Appendix include::{includedir}/appendix.adoc[] [[user-glossary]] == Glossary include::{includedir}/glossary.adoc[] [[user-biblio]] == Bibliography include::{includedir}/biblio.adoc[] [[user-index]] == Index include::{includedir}/index.adoc[] [[user-footnotes]] == Footnotes include::{includedir}/footnote.adoc[] = Processing Your Content [partintro] -- include::{includedir}/process-intro.adoc[] -- == Selecting an Output Format include::{includedir}/output-format.adoc[] //// The AsciiDoc processor supports numerous backends, including: `xhtml11`:: XHTML 1.1 markup styled with CSS2. AsciiDoc's default backend. //// == HTML // TODO: expand this introduction Asciidoctor's default output format is HTML. `html5`:: HTML 5 markup styled with CSS3. === Using the Command Line include::{includedir}/html-command-line.adoc[] === Using the Ruby API include::{includedir}/html-ruby-api.adoc[] === Styling the HTML with CSS include::{includedir}/html-styles.adoc[] === Managing Images include::{includedir}/html-manage-images.adoc[] [[hl-css]] === CodeRay and Pygments Stylesheets include::{includedir}/html-code-styles.adoc[] == XHTML include::{includedir}/xhtml.adoc[] == DocBook include::{includedir}/docbook.adoc[] == Man Pages include::{includedir}/manpage.adoc[] == PDFs Conversion from AsciiDoc to PDF is made possible by a number of tools. {uri-asciidoctor-pdf}[Asciidoctor PDF]:: A native PDF converter for Asciidoctor (converts directly from AsciiDoc to PDF using Prawn). + Instructions for installing and using Asciidoctor PDF are documented in the project's {uri-asciidoctor-pdf-readme}[README]. The tool provides built-in theming via a YAML configuration file, which is documented in the {uri-asciidoctor-pdf-theming-guide}[theming guide]. + TIP: Asciidoctor PDF is the preferred tool for converting to PDF and is fully supported by the Asciidoctor community. a2x:: A DocBook toolchain frontend provided by that AsciiDoc Python project. + To use this tool, you should first convert to DocBook using Asciidoctor, then convert the DocBook to PDF using a2x. a2x accepts a DocBook file as input and can convert it to a PDF using either Apache FOP or dblatex. Instructions for using a2x are documented in the project's {uri-a2x-manpage}[man page]. {fopub-ref}[asciidoctor-fopub]:: A DocBook toolchain frontend similar to a2x, but which only requires Java to be installed on your machine. + Instructions for using asciidoctor-fopub are documented in the project's {fopub-doc-ref}[README]. To alter the look and feel of the PDF, it's necessary to pass XSL parameters or modify the XSLT. More information about customization can be found in http://www.sagehill.net/docbookxsl/[DocBook XSL: The Complete Guide]. == Preview Your Content .Discuss and Contribute TIP: Use {uri-ad-org-issues}/449[Issue 449] to drive development of this section. Your contributions make a difference. No contribution is too small. === Guard/Live Viewer Guard::AsciiDoc is a plugin for https://github.com/guard/guard[Guard] that renders watched AsciiDoc files to the specified output format whenever they change using Asciidoctor. Instructions for using the Guard/Live viewer are documented in the project's {guard-doc-ref}[README]. == Process Multiple Source Files from the CLI include::{includedir}/process-multi.adoc[] == Specifying an Output File include::{includedir}/file-output.adoc[] == Running Asciidoctor Securely include::{includedir}/secure.adoc[] === Set the Safe Mode in the CLI include::{includedir}/secure-cli.adoc[] === Set the Safe Mode in the API include::{includedir}/secure-api.adoc[] === Set Attributes Based on the Safe Mode include::{includedir}/secure-attr.adoc[] = Customizing Your Output [partintro] -- Asciidoctor provides a default stylesheet and built-in converters so you can quickly process and render your document, but it also lets you use custom stylesheets and converters. The Asciidoctor project includes alternative stylesheet themes from <> and <>, such as the <>. You can also create your own <> and <>. -- == Custom Themes NOTE: Section introduction pending === Creating a Theme include::{includedir}/create-theme.adoc[] === Applying a Theme include::{includedir}/apply-theme.adoc[] == Stylesheet Factory include::{includedir}/factory-intro.adoc[] === Setting up the Factory include::{includedir}/factory-setup.adoc[tags=setup] ==== Install the Gems include::{includedir}/factory-setup.adoc[tags=gem] ==== Build the Stylesheets include::{includedir}/factory-setup.adoc[tags=build] === Applying a Stylesheet include::{includedir}/factory-apply.adoc[] === Generate an HTML Document include::{includedir}/factory-gen.adoc[] === External Preview include::{includedir}/factory-preview.adoc[] == Slideshows The conversion to HTML-based slides is handled by a custom backend. The backends usually requires that you adhere to a set of conventions to define a slide and its content. But there's nothing in that content that restricts the document from being converted to a regular HTML page or PDF. The first backend created was the one for deck.js. Asciidoctor has backends for generating dzslides and reveal.js presentations as well. Backends for other presentation frameworks are in the works. [[deckjs]] === Deck.js The {backend-git}[deck.js backend] for Asciidoctor is a collection of Haml templates that transform an AsciiDoc document to HTML 5-based slides animated by {deckjs-org}[deck.js]. ==== Gem Requirements The Asciidoctor deck.js backend requires the following gems: * asciidoctor * tilt * haml To determine what gems are installed on your system, open a terminal window and type: $ gem list --local A list of installed gems will be returned. If you're missing the `asciidoctor`, `tilt`, or `haml` gems, install them from the command line with `gem install`. $ gem install asciidoctor tilt haml ==== Backend and deck.js Installation . Download or `git clone` the {backend-git}[Asciidoctor backends] repository. $ git clone git://github.com/asciidoctor/asciidoctor-backends.git . Create a directory named `deck.js` inside your working directory (i.e. where your AsciiDoc document resides). . {deckjs-zip}[Download] and extract the deck.js archive or `git clone` the {deckjs-git}[deck.js] repository into the `deck.js` directory you created in step 2. $ git clone git://github.com/imakewebthings/deck.js.git . If you plan to split your slides, {decksplitjs-git}[download the `deck.split.js` extension] and copy it into the `deck.js/extensions` directory. . If you want to use the fullscreen photo feature, create an `images` directory in your working directory. ==== Deckjs Backend Attributes There are a number of document attributes specific to the `deckjs` backend. .`deckjs` backend document attributes [cols=""2,1,2m""] |=== |Attribute |Description |Example |:backend: deckjs |Activates the deck.js backend to render the document as a deck.js presentation |:backend: deckjs |:deckjs_theme: |Sets the deck.js theme to neon, swiss or web-2.0 |:deckjs_theme: web-2.0 |:deckjs_transition: |Sets the transition style to horizontal-slide, vertical-slide or fade |:deckjs_transition: fade |:customjs: |Sets a custom javascript file; can be used as a deck.js custom configuration |:customjs: |:customcss: |Sets a custom css file |:customcss: |:menu: |Toggle to and from a grid layout overview of all the slides by pressing the `m` key |:menu: |:navigation: |Renders clickable previous and next navigation icons on the slides |:navigation: |:status: |Renders the current slide number and total number of slides |:status: |:split: |Registers the split module for use in the document |:split: |=== NOTE: You can also specify a custom stylesheet using the `stylesheet` attribute, which customizes AsciiDoc elements like section, paragraph, images, etc. The attributes described in the table above are set in the header of your document. .Header with `deckjs` backend attributes .... = Presentation Title Presenter Name :backend: deckjs :deckjs_theme: web-2.0 :deckjs_transition: horizontal-slide :navigation: .... ==== Slide syntax Examples Structuring a slideshow and writing the slide content uses the same syntax as a typical AsciiDoc document, with a few added features. Let's see some examples of the `deckjs` backend features: .Slide titles and background images ---- = Title of Presentation <1> Presenter Name :backend: deckjs :deckjs_transition: fade :navigation: == Title of Slide One <2> This is the first slide after the title slide. [canvas-image=""images/example.jpg""] <3> == Slide Two's Title will not be displayed <4> [role=""canvas-caption"", position=""center-up""] <5> This text is displayed on top of the example.jpg image. ---- <1> The presentation title and author's name will be displayed on the title slide. <2> Each new slide is designated by a level 1 section title (`==`). <3> The `canvas-image` attribute embeds a fullscreen image as a slide background. Position the attribute above the title of the slide you want the image applied to. <4> When the `canvas-image` attribute is applied to a slide, that slide's title will not be displayed. <5> `canvas-caption` applies a colored box around the caption text. `position` specifies the location of the caption block (bottom-left, top-left, bottom-right, top-right, center-up, center-down) .Stepped paragraphs, lists, and blocks [listing] .... == Stepped paragraphs [options=""step""] This paragraph is displayed first. [options=""step""] Then this paragraph is displayed when the _Next_ arrow is clicked. == Stepped list items [options=""step""] * A bullet is displayed each time the _Next_ arrow is clicked. * B * C == Stepped blocks [options=""step""] ---- Block one ---- [options=""step""] ---- Block two ---- .... The `step` option reveals each paragraph, bullet, etc. separately each time you click the _Next_ arrow. WARNING: The original AsciiDoc `deckjs` backend for the AsciiDoc processor used the option `incremental` instead of `step`. We've changed it to `step` in order to save you some typing. .Split ---- = Presentation Title Presenter Name :backend: deckjs :split: <1> == This Slide is Split This Slide will act like <<< <2> three individual slides with the same title <<< once the document is rendered. ---- <1> To create multiple, consecutive slides with the same title, set the `split` attribute in the document header. <2> Then, within a slide, insert `<<<` to specify the slide breaks. // Should this read ""Converting""? ==== Rendering To render your presentation as HTML5, execute the command: $ asciidoctor -T ../asciidoctor-backends/haml presentation.adoc . The command `-T` (`--template-dir`) tells the Asciidoctor processor to override the built-in backends. . Directly after `-T` is the path to where you saved or cloned the Asciidoctor backends repository containing the `deckjs` backend (step 1 under the <>). == Custom Backends .Discuss and Contribute TIP: Use {uri-ad-org-issues}/451[Issue 451] to drive development of this section. Your contributions make a difference. No contribution is too small. === Creating a Backend .Discuss and Contribute TIP: Use {uri-ad-org-issues}/452[Issue 452] to drive development of this section. Your contributions make a difference. No contribution is too small. ==== Storing Multiple Templates Custom templates can be stored in multiple directories. That means you can build on an existing backend by copying only the templates you want to modify. Then, just pass both the directory holding the original templates and the directory containing your customized templates when you invoke Asciidoctor. In the CLI, multiple template directories are specified by using the `-T` option multiple times. $ asciidoctor -T /path/to/original/templates -T /path/to/modified/templates mysample.adoc In the API, multiple template directories are specified by passing an array to the `template_dirs` option: ```ruby Asciidoctor.convert_file 'mysample.adoc', safe: :safe template_dirs: %w(/path/to/original/templates /path/to/modified/templates) ``` //// Styling DocBook and PDF Output NOTE: Section pending //// [[language-support]] == Using Asciidoctor with Other Languages include::{includedir}/language-support.adoc[] = Publishing Your Content [partintro] NOTE: Section pending == Repositories .Discuss and Contribute TIP: Use {uri-ad-org-issues}/453[Issue 453] to drive development of this section. Your contributions make a difference. No contribution is too small. == Static Website Generators .Discuss and Contribute TIP: Use {uri-ad-org-issues}/454[Issue 454] to drive development of this section. Your contributions make a difference. No contribution is too small. === Front Matter Added for Static Site Generators include::{includedir}/static-front.adoc[] ==== Configuring Attributes for Awestruct include::{includedir}/static-awe.adoc[] [[api]] = Using Asciidoctor's API [partintro] -- include::{includedir}/api-intro.adoc[] -- // load and convert? == Load and Render a File Using the API include::{includedir}/load-render-api.adoc[] === Render Strings include::{includedir}/string-api.adoc[] == Provide Custom Templates include::{includedir}/templates-api.adoc[] = Extensions [partintro] -- include::{includedir}/exten-intro.adoc[] -- == Extension Points include::{includedir}/exten-point.adoc[] == Example Extensions Below are several examples of extensions and how they are registered. === Preprocessor Example include::{includedir}/exten-pre.adoc[] === Treeprocessor Example include::{includedir}/exten-tree.adoc[] === Postprocessor Example include::{includedir}/exten-post.adoc[] === Block Processor Example include::{includedir}/exten-block.adoc[] === Block Macro Processor Example include::{includedir}/exten-macro.adoc[] === Inline Macro Processor Example include::{includedir}/exten-in-macro.adoc[] === Include Processor Example include::{includedir}/exten-include.adoc[] You can see plenty more extension examples in the https://github.com/asciidoctor/asciidoctor-extensions-lab[extensions lab]. = Build Integrations and Implementations [partintro] NOTE: Section pending == Java .Discuss and Contribute TIP: Use {uri-ad-org-issues}/455[Issue 455] to drive development of this section. Your contributions make a difference. No contribution is too small. == Gradle .Discuss and Contribute TIP: Use {uri-ad-org-issues}/456[Issue 456] to drive development of this section. Your contributions make a difference. No contribution is too small. == Maven .Discuss and Contribute TIP: Use {uri-ad-org-issues}/457[Issue 457] to drive development of this section. Your contributions make a difference. No contribution is too small. == Apache Ant include::{includedir}/asciidoctor-ant.adoc[] == JavaDoc .Discuss and Contribute TIP: Use {uri-ad-org-issues}/458[Issue 458] to drive development of this section. Your contributions make a difference. No contribution is too small. == JavaScript .Discuss and Contribute TIP: Use {uri-ad-org-issues}/459[Issue 459] to drive development of this section. Your contributions make a difference. No contribution is too small. == Yard .Discuss and Contribute TIP: Use {uri-ad-org-issues}/460[Issue 460] to drive development of this section. Your contributions make a difference. No contribution is too small. == Rdoc .Discuss and Contribute TIP: Use {uri-ad-org-issues}/461[Issue 461] to drive development of this section. Your contributions make a difference. No contribution is too small. = Conversions and Migrations [partintro] -- In this part, you'll learn how to migrate documents written in other documentation languages to AsciiDoc. We'll start with the simplest migration, switching from AsciiDoc Python, the original implementation of AsciiDoc, to Asciidoctor, the modern implementation. We'll then cover how to move to AsciiDoc from other documentation languages like DocBook, Markdown and HTML. In addition to differences in the syntax, many of the sections also suggest tools you can use to ease the migration. -- [[migrating-from-asciidoc-python]] include::{includedir}/migrating-from-asciidoc-python.adoc[] == Convert DocBook XML to AsciiDoc include::{includedir}/docbookrx.adoc[] == Convert Markdown to AsciiDoc .Discuss and Contribute TIP: Use {uri-ad-org-issues}/462[Issue 462] to drive development of this section. Your contributions make a difference. No contribution is too small. == Convert Confluence XHTML to AsciiDoc include::{includedir}/convert-from-confluence-xhtml.adoc[] = Resources [partintro] NOTE: Section pending == Copyright and License include::{includedir}/project-lic.adoc[] == Authors include::{includedir}/project-author.adoc[] // TODO fill in this section and enable // Thanks, acknowledgments, and credits :leveloffset: 1 [[troubleshoot]] include::{includedir}/troubleshoot.adoc[] :leveloffset: 0 [glossary] == Glossary .Discuss and Contribute TIP: Use {uri-ad-org-issues}/465[Issue 465] to drive development of this section. Your contributions make a difference. No contribution is too small. [glossary] admonition:: a callout paragraph or block that has a label or icon indicating its priority. backend:: a moniker for the expected output format; used as a key to select which converter to use; often used interchangeably with the name of a converter (i.e., the ""html5"" backend""). block attribute:: an attribute associated with a delimited block or paragraph; these attributes can affect processing of the block, and are available to block processors, but cannot be referenced using an attribute reference. built-in attribute:: a document attribute that controls processing, integrations, styling, and localization. cross reference:: a link from one location in the document to another location marked by an anchor. document attribute:: an attribute associated with the document (node); in other words, an attribute in the global document attributes dictionary; the value of these attributes can be referenced using an attribute reference; if defined in the header, the document attribute is known as a header attribute. environment attribute:: a dynamic document attribute that pertains to, or gives information about, the runtime environment. header attribute:: a document attribute defined in the document header; visible from all nodes in the document; often required for global settings such as the source highlighter or icons mode. list continuation:: a plus sign (`+`) on a line by itself that connects adjacent lines of text to a list item. macro attribute:: an attribute associated with a block or inline macro; these attributes can affect processing of the macro, and are available to macro processors, but cannot be referenced using an attribute reference. predefined attribute:: a document attribute defined for convenience; often used for inserting special content characters. quoted text:: text which is enclosed in special punctuation to give it emphasis or special meaning. user-defined attribute:: a document attribute defined by the content author; used for storing reusable content, and controlling conditional inclusion. [appendix#attribute-catalog] == Catalog of Document Attributes This appendix catalogs all the recognized document attributes in Asciidoctor. It includes environment, built-in and predefined (aka character reference) attributes. Authors may define any number of additional attributes (aka user-defined attributes) for their own purposes. include::{includedir}/attrs-env.adoc[leveloffset=2] include::{includedir}/attrs-builtin.adoc[leveloffset=2] include::{includedir}/attrs-charref.adoc[leveloffset=2] [appendix#cli-options] == CLI Options include::{includedir}/cli-options.adoc[] [appendix#ruby-api-options] == Ruby API Options include::{includedir}/ruby-api-options.adoc[] [appendix#app-messages] == Application Messages include::{includedir}/messages.adoc[] //// Include license and copyright == Index NOTE: Section pending //// ",12523,False,2330.521448335041,median "[[box-component]] = Box Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-box/camel-box-component/src/main/docs/box-component.adoc :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[] *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[] ",12347,True,2565.813502951094,median