code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
---|---|---|---|---|---|
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2007 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/Image>
#include <osg/Notify>
#include <osg/Geode>
#include <osg/GL>
#include <osgDB/Registry>
#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>
#include <osgDB/ImageOptions>
#include <OpenThreads/ScopedLock>
#include <OpenThreads/ReentrantMutex>
#include <memory>
#include <gdal_priv.h>
#include "DataSetLayer.h"
#define SERIALIZER() OpenThreads::ScopedLock<OpenThreads::ReentrantMutex> lock(_serializerMutex)
// From easyrgb.com
float Hue_2_RGB( float v1, float v2, float vH )
{
if ( vH < 0 ) vH += 1;
if ( vH > 1 ) vH -= 1;
if ( ( 6 * vH ) < 1 ) return ( v1 + ( v2 - v1 ) * 6 * vH );
if ( ( 2 * vH ) < 1 ) return ( v2 );
if ( ( 3 * vH ) < 2 ) return ( v1 + ( v2 - v1 ) * ( ( 2 / 3 ) - vH ) * 6 );
return ( v1 );
}
class ReaderWriterGDAL : public osgDB::ReaderWriter
{
public:
ReaderWriterGDAL()
{
supportsExtension("gdal","GDAL Image reader");
}
virtual const char* className() const { return "GDAL Image Reader"; }
virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options) const
{
if (file.empty()) return ReadResult::FILE_NOT_FOUND;
if (osgDB::equalCaseInsensitive(osgDB::getFileExtension(file),"gdal"))
{
return readObject(osgDB::getNameLessExtension(file),options);
}
OpenThreads::ScopedLock<OpenThreads::ReentrantMutex> lock(_serializerMutex);
std::string fileName = osgDB::findDataFile( file, options );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
initGDAL();
// open a DataSetLayer.
osg::ref_ptr<GDALPlugin::DataSetLayer> dataset = new GDALPlugin::DataSetLayer(fileName);
dataset->setGdalReader(this);
if (dataset->isOpen()) return dataset.release();
return ReadResult::FILE_NOT_HANDLED;
}
virtual ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
if (osgDB::equalCaseInsensitive(osgDB::getFileExtension(fileName),"gdal"))
{
return readImage(osgDB::getNameLessExtension(fileName),options);
}
OpenThreads::ScopedLock<OpenThreads::ReentrantMutex> lock(_serializerMutex);
return const_cast<ReaderWriterGDAL*>(this)->local_readImage(fileName, options);
}
virtual ReadResult readHeightField(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
if (osgDB::equalCaseInsensitive(osgDB::getFileExtension(fileName),"gdal"))
{
return readHeightField(osgDB::getNameLessExtension(fileName),options);
}
OpenThreads::ScopedLock<OpenThreads::ReentrantMutex> lock(_serializerMutex);
return const_cast<ReaderWriterGDAL*>(this)->local_readHeightField(fileName, options);
}
virtual ReadResult local_readImage(const std::string& file, const osgDB::ReaderWriter::Options* options)
{
// Looks like gdal's GDALRasterBand::GetColorInterpretation()
// is not giving proper values for ecw images. There is small
// hack to get around
bool ecwLoad = osgDB::equalCaseInsensitive(osgDB::getFileExtension(file),"ecw");
//if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
OSG_INFO << "GDAL : " << file << std::endl;
std::string fileName = osgDB::findDataFile( file, options );
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
initGDAL();
std::auto_ptr<GDALDataset> dataset((GDALDataset*)GDALOpen(fileName.c_str(),GA_ReadOnly));
if (!dataset.get()) return ReadResult::FILE_NOT_HANDLED;
int dataWidth = dataset->GetRasterXSize();
int dataHeight = dataset->GetRasterYSize();
int windowX = 0;
int windowY = 0;
int windowWidth = dataWidth;
int windowHeight = dataHeight;
int destX = 0;
int destY = 0;
int destWidth = osg::minimum(dataWidth,4096);
int destHeight = osg::minimum(dataHeight,4096);
// int destWidth = osg::minimum(dataWidth,4096);
// int destHeight = osg::minimum(dataHeight,4096);
osg::ref_ptr<osgDB::ImageOptions::TexCoordRange> texCoordRange;
osgDB::ImageOptions* imageOptions = dynamic_cast<osgDB::ImageOptions*>(const_cast<osgDB::ReaderWriter::Options*>(options));
if (imageOptions)
{
OSG_INFO<<"Got ImageOptions"<<std::endl;
int margin = 0;
switch(imageOptions->_sourceImageWindowMode)
{
case(osgDB::ImageOptions::RATIO_WINDOW):
{
double desiredX = (double)dataWidth * imageOptions->_sourceRatioWindow.windowX;
double desiredY = (double)dataHeight * imageOptions->_sourceRatioWindow.windowY;
double desiredWidth = (double)dataWidth * imageOptions->_sourceRatioWindow.windowWidth;
double desiredHeight = (double)dataHeight * imageOptions->_sourceRatioWindow.windowHeight;
windowX = osg::maximum((int)(floor(desiredX))-margin,0);
windowY = osg::maximum((int)(floor(desiredY))-margin,0);
windowWidth = osg::minimum((int)(ceil(desiredX + desiredWidth))+margin,dataWidth)-windowX;
windowHeight = osg::minimum((int)(ceil(desiredY + desiredHeight))+margin,dataHeight)-windowY;
texCoordRange = new osgDB::ImageOptions::TexCoordRange;
texCoordRange->set((desiredX-(double)windowX)/(double)windowWidth,
((double)(windowY+windowHeight) -(desiredY+desiredHeight))/(double)windowHeight,
(desiredWidth)/(double)windowWidth,
(desiredHeight)/(double)windowHeight);
OSG_INFO<<"tex coord range "<<texCoordRange->_x<<" "<<texCoordRange->_y<<" "<<texCoordRange->_w<<" "<<texCoordRange->_h<<std::endl;
}
break;
case(osgDB::ImageOptions::PIXEL_WINDOW):
windowX = imageOptions->_sourcePixelWindow.windowX;
windowY = imageOptions->_sourcePixelWindow.windowY;
windowWidth = imageOptions->_sourcePixelWindow.windowWidth;
windowHeight = imageOptions->_sourcePixelWindow.windowHeight;
break;
default:
// leave source window dimensions as whole image.
break;
}
// reapply the window coords to the pixel window so that calling code
// knows the original pixel size
imageOptions->_sourcePixelWindow.windowX = windowX;
imageOptions->_sourcePixelWindow.windowY = windowY;
imageOptions->_sourcePixelWindow.windowWidth = windowWidth;
imageOptions->_sourcePixelWindow.windowHeight = windowHeight;
switch(imageOptions->_destinationImageWindowMode)
{
case(osgDB::ImageOptions::RATIO_WINDOW):
destX = (unsigned int)(floor((double)dataWidth * imageOptions->_destinationRatioWindow.windowX));
destY = (unsigned int)(floor((double)dataHeight * imageOptions->_destinationRatioWindow.windowY));
destWidth = (unsigned int)(ceil((double)dataWidth * (imageOptions->_destinationRatioWindow.windowX + imageOptions->_destinationRatioWindow.windowWidth)))-windowX;
destHeight = (unsigned int)(ceil((double)dataHeight * (imageOptions->_destinationRatioWindow.windowY + imageOptions->_destinationRatioWindow.windowHeight)))-windowY;
break;
case(osgDB::ImageOptions::PIXEL_WINDOW):
destX = imageOptions->_destinationPixelWindow.windowX;
destY = imageOptions->_destinationPixelWindow.windowY;
destWidth = imageOptions->_destinationPixelWindow.windowWidth;
destHeight = imageOptions->_destinationPixelWindow.windowHeight;
break;
default:
// leave source window dimensions as whole image.
break;
}
}
// windowX = 0;
// windowY = 0;
// windowWidth = destWidth;
// windowHeight = destHeight;
OSG_INFO << " windowX = "<<windowX<<std::endl;
OSG_INFO << " windowY = "<<windowY<<std::endl;
OSG_INFO << " windowWidth = "<<windowWidth<<std::endl;
OSG_INFO << " windowHeight = "<<windowHeight<<std::endl;
OSG_INFO << std::endl;
OSG_INFO << " destX = "<<destX<<std::endl;
OSG_INFO << " destY = "<<destY<<std::endl;
OSG_INFO << " destWidth = "<<destWidth<<std::endl;
OSG_INFO << " destHeight = "<<destHeight<<std::endl;
OSG_INFO << std::endl;
OSG_INFO << " GetRaterCount() "<< dataset->GetRasterCount()<<std::endl;
OSG_INFO << " GetProjectionRef() "<< dataset->GetProjectionRef()<<std::endl;
double geoTransform[6];
if (dataset->GetGeoTransform(geoTransform)==CE_None)
{
OSG_INFO << " GetGeoTransform "<< std::endl;
OSG_INFO << " Origin = "<<geoTransform[0]<<" "<<geoTransform[3]<<std::endl;
OSG_INFO << " Pixel X = "<<geoTransform[1]<<" "<<geoTransform[4]<<std::endl;
OSG_INFO << " Pixel Y = "<<geoTransform[2]<<" "<<geoTransform[5]<<std::endl;
}
int numBands = dataset->GetRasterCount();
GDALRasterBand* bandGray = 0;
GDALRasterBand* bandRed = 0;
GDALRasterBand* bandGreen = 0;
GDALRasterBand* bandBlue = 0;
GDALRasterBand* bandAlpha = 0;
GDALRasterBand* bandPalette = 0;
int internalFormat = GL_LUMINANCE;
unsigned int pixelFormat = GL_LUMINANCE;
unsigned int dataType = 0;
unsigned int numBytesPerComponent = 0;
GDALDataType targetGDALType = GDT_Byte;
for(int b=1;b<=numBands;++b)
{
GDALRasterBand* band = dataset->GetRasterBand(b);
OSG_INFO << " Band "<<b<<std::endl;
OSG_INFO << " GetOverviewCount() = "<< band->GetOverviewCount()<<std::endl;
OSG_INFO << " GetColorTable() = "<< band->GetColorTable()<<std::endl;
OSG_INFO << " DataTypeName() = "<< GDALGetDataTypeName(band->GetRasterDataType())<<std::endl;
OSG_INFO << " ColorIntepretationName() = "<< GDALGetColorInterpretationName(band->GetColorInterpretation())<<std::endl;
bool bandNotHandled = true;
if (ecwLoad)
{
bandNotHandled = false;
switch (b)
{
case 1:
bandRed = band;
break;
case 2:
bandGreen = band;
break;
case 3:
bandBlue = band;
break;
default:
bandNotHandled = true;
}
}
if (bandNotHandled)
{
if (band->GetColorInterpretation()==GCI_GrayIndex) bandGray = band;
else if (band->GetColorInterpretation()==GCI_RedBand) bandRed = band;
else if (band->GetColorInterpretation()==GCI_GreenBand) bandGreen = band;
else if (band->GetColorInterpretation()==GCI_BlueBand) bandBlue = band;
else if (band->GetColorInterpretation()==GCI_AlphaBand) bandAlpha = band;
else if (band->GetColorInterpretation()==GCI_PaletteIndex) bandPalette = band;
else bandGray = band;
}
if (bandPalette)
{
OSG_INFO << " Palette Interpretation: " << GDALGetPaletteInterpretationName(band->GetColorTable()->GetPaletteInterpretation()) << std::endl;
}
// int gotMin,gotMax;
// double minmax[2];
//
// minmax[0] = band->GetMinimum(&gotMin);
// minmax[1] = band->GetMaximum(&gotMax);
// if (!(gotMin && gotMax))
// {
// OSG_INFO<<" computing min max"<<std::endl;
// GDALComputeRasterMinMax(band,TRUE,minmax);
// }
//
// OSG_INFO << " min "<<minmax[0]<<std::endl;
// OSG_INFO << " max "<<minmax[1]<<std::endl;
if (dataType==0)
{
targetGDALType = band->GetRasterDataType();
switch(band->GetRasterDataType())
{
case(GDT_Byte): dataType = GL_UNSIGNED_BYTE; numBytesPerComponent = 1; break;
case(GDT_UInt16): dataType = GL_UNSIGNED_SHORT; numBytesPerComponent = 2; break;
case(GDT_Int16): dataType = GL_SHORT; numBytesPerComponent = 2; break;
case(GDT_UInt32): dataType = GL_UNSIGNED_INT; numBytesPerComponent = 4; break;
case(GDT_Int32): dataType = GL_INT; numBytesPerComponent = 4; break;
case(GDT_Float32): dataType = GL_FLOAT; numBytesPerComponent = 4; break;
case(GDT_Float64): dataType = GL_DOUBLE; numBytesPerComponent = 8; break; // not handled
default: dataType = 0; numBytesPerComponent = 0; break; // not handled
}
}
}
int s = destWidth;
int t = destHeight;
int r = 1;
if (dataType==0)
{
dataType = GL_UNSIGNED_BYTE;
numBytesPerComponent = 1;
targetGDALType = GDT_Byte;
}
unsigned char* imageData = 0;
if (bandRed && bandGreen && bandBlue)
{
if (bandAlpha)
{
// RGBA
int pixelSpace=4*numBytesPerComponent;
int lineSpace=destWidth * pixelSpace;
imageData = new unsigned char[destWidth * destHeight * pixelSpace];
pixelFormat = GL_RGBA;
internalFormat = GL_RGBA;
OSG_INFO << "reading RGBA"<<std::endl;
bandRed->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+0),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
bandGreen->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+1*numBytesPerComponent),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
bandBlue->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+2*numBytesPerComponent),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
bandAlpha->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+3*numBytesPerComponent),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
}
else
{
// RGB
int pixelSpace=3*numBytesPerComponent;
int lineSpace=destWidth * pixelSpace;
imageData = new unsigned char[destWidth * destHeight * pixelSpace];
pixelFormat = GL_RGB;
internalFormat = GL_RGB;
OSG_INFO << "reading RGB"<<std::endl;
bandRed->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+0),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
bandGreen->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+1*numBytesPerComponent),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
bandBlue->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+2*numBytesPerComponent),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
}
}
else if (bandGray)
{
if (bandAlpha)
{
// Luminance alpha
int pixelSpace=2*numBytesPerComponent;
int lineSpace=destWidth * pixelSpace;
imageData = new unsigned char[destWidth * destHeight * pixelSpace];
pixelFormat = GL_LUMINANCE_ALPHA;
internalFormat = GL_LUMINANCE_ALPHA;
OSG_INFO << "reading grey + alpha"<<std::endl;
bandGray->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+0),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
bandAlpha->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+1*numBytesPerComponent),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
}
else
{
// Luminance map
int pixelSpace=1*numBytesPerComponent;
int lineSpace=destWidth * pixelSpace;
imageData = new unsigned char[destWidth * destHeight * pixelSpace];
pixelFormat = GL_LUMINANCE;
internalFormat = GL_LUMINANCE;
OSG_INFO << "reading grey"<<std::endl;
bandGray->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+0),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
}
}
else if (bandAlpha)
{
// alpha map
int pixelSpace=1*numBytesPerComponent;
int lineSpace=destWidth * pixelSpace;
imageData = new unsigned char[destWidth * destHeight * pixelSpace];
pixelFormat = GL_ALPHA;
internalFormat = GL_ALPHA;
OSG_INFO << "reading alpha"<<std::endl;
bandAlpha->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(imageData+0),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
}
else if (bandPalette)
{
// Paletted map
int pixelSpace=1*numBytesPerComponent;
int lineSpace=destWidth * pixelSpace;
unsigned char *rawImageData;
rawImageData = new unsigned char[destWidth * destHeight * pixelSpace];
imageData = new unsigned char[destWidth * destHeight * 4/*RGBA*/];
pixelFormat = GL_RGBA;
internalFormat = GL_RGBA;
OSG_INFO << "reading palette"<<std::endl;
OSG_INFO << "numBytesPerComponent: " << numBytesPerComponent << std::endl;
bandPalette->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(rawImageData),destWidth,destHeight,targetGDALType,pixelSpace,lineSpace);
// Map the indexes to an actual RGBA Value.
for (int i = 0; i < destWidth * destHeight; i++)
{
const GDALColorEntry *colorEntry = bandPalette->GetColorTable()->GetColorEntry(rawImageData[i]);
GDALPaletteInterp interp = bandPalette->GetColorTable()->GetPaletteInterpretation();
if (!colorEntry)
{
//FIXME: What to do here?
//OSG_INFO << "NO COLOR ENTRY FOR COLOR " << rawImageData[i] << std::endl;
imageData[4*i+0] = 255;
imageData[4*i+1] = 0;
imageData[4*i+2] = 0;
imageData[4*i+3] = 1;
}
else
{
if (interp == GPI_RGB)
{
imageData[4*i+0] = colorEntry->c1;
imageData[4*i+1] = colorEntry->c2;
imageData[4*i+2] = colorEntry->c3;
imageData[4*i+3] = colorEntry->c4;
}
else if (interp == GPI_CMYK)
{
// from wikipedia.org
short C = colorEntry->c1;
short M = colorEntry->c2;
short Y = colorEntry->c3;
short K = colorEntry->c4;
imageData[4*i+0] = 255 - C*(255 - K) - K;
imageData[4*i+1] = 255 - M*(255 - K) - K;
imageData[4*i+2] = 255 - Y*(255 - K) - K;
imageData[4*i+3] = 255;
}
else if (interp == GPI_HLS)
{
// from easyrgb.com
float H = colorEntry->c1;
float S = colorEntry->c3;
float L = colorEntry->c2;
float R, G, B;
if ( S == 0 ) //HSL values = 0 - 1
{
R = L; //RGB results = 0 - 1
G = L;
B = L;
}
else
{
float var_2, var_1;
if ( L < 0.5 )
var_2 = L * ( 1 + S );
else
var_2 = ( L + S ) - ( S * L );
var_1 = 2 * L - var_2;
R = Hue_2_RGB( var_1, var_2, H + ( 1 / 3 ) );
G = Hue_2_RGB( var_1, var_2, H );
B = Hue_2_RGB( var_1, var_2, H - ( 1 / 3 ) );
}
imageData[4*i+0] = static_cast<unsigned char>(R*255.0f);
imageData[4*i+1] = static_cast<unsigned char>(G*255.0f);
imageData[4*i+2] = static_cast<unsigned char>(B*255.0f);
imageData[4*i+3] = static_cast<unsigned char>(255.0f);
}
else if (interp == GPI_Gray)
{
imageData[4*i+0] = static_cast<unsigned char>(colorEntry->c1*255.0f);
imageData[4*i+1] = static_cast<unsigned char>(colorEntry->c1*255.0f);
imageData[4*i+2] = static_cast<unsigned char>(colorEntry->c1*255.0f);
imageData[4*i+3] = static_cast<unsigned char>(255.0f);
}
}
}
delete [] rawImageData;
}
else
{
OSG_INFO << "not found any usable bands in file."<<std::endl;
}
//GDALOpen(dataset);
if (imageData)
{
osg::Image* image = new osg::Image;
image->setFileName(fileName.c_str());
image->setImage(s,t,r,
internalFormat,
pixelFormat,
dataType,
(unsigned char *)imageData,
osg::Image::USE_NEW_DELETE);
if (texCoordRange.valid()) image->setUserData(texCoordRange.get());
image->flipVertical();
return image;
}
return 0;
}
ReadResult local_readHeightField(const std::string& fileName, const osgDB::ReaderWriter::Options* options)
{
//std::string ext = osgDB::getFileExtension(fileName);
//if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
initGDAL();
std::auto_ptr<GDALDataset> dataset((GDALDataset*)GDALOpen(fileName.c_str(),GA_ReadOnly));
if (!dataset.get()) return ReadResult::FILE_NOT_HANDLED;
int dataWidth = dataset->GetRasterXSize();
int dataHeight = dataset->GetRasterYSize();
int windowX = 0;
int windowY = 0;
int windowWidth = dataWidth;
int windowHeight = dataHeight;
int destX = 0;
int destY = 0;
int destWidth = osg::minimum(dataWidth,4096);
int destHeight = osg::minimum(dataHeight,4096);
osg::ref_ptr<osgDB::ImageOptions::TexCoordRange> texCoordRange;
const osgDB::ImageOptions* imageOptions = dynamic_cast<const osgDB::ImageOptions*>(options);
if (imageOptions)
{
OSG_INFO<<"Got ImageOptions"<<std::endl;
int margin = 0;
switch(imageOptions->_sourceImageWindowMode)
{
case(osgDB::ImageOptions::RATIO_WINDOW):
{
double desiredX = (double)dataWidth * imageOptions->_sourceRatioWindow.windowX;
double desiredY = (double)dataHeight * imageOptions->_sourceRatioWindow.windowY;
double desiredWidth = (double)dataWidth * imageOptions->_sourceRatioWindow.windowWidth;
double desiredHeight = (double)dataHeight * imageOptions->_sourceRatioWindow.windowHeight;
windowX = osg::maximum((int)(floor(desiredX))-margin,0);
windowY = osg::maximum((int)(floor(desiredY))-margin,0);
windowWidth = osg::minimum((int)(ceil(desiredX + desiredWidth))+margin,dataWidth)-windowX;
windowHeight = osg::minimum((int)(ceil(desiredY + desiredHeight))+margin,dataHeight)-windowY;
texCoordRange = new osgDB::ImageOptions::TexCoordRange;
texCoordRange->set((desiredX-(double)windowX)/(double)windowWidth,
((double)(windowY+windowHeight) -(desiredY+desiredHeight))/(double)windowHeight,
(desiredWidth)/(double)windowWidth,
(desiredHeight)/(double)windowHeight);
OSG_INFO<<"tex coord range "<<texCoordRange->_x<<" "<<texCoordRange->_y<<" "<<texCoordRange->_w<<" "<<texCoordRange->_h<<std::endl;
}
break;
case(osgDB::ImageOptions::PIXEL_WINDOW):
windowX = imageOptions->_sourcePixelWindow.windowX;
windowY = imageOptions->_sourcePixelWindow.windowY;
windowWidth = imageOptions->_sourcePixelWindow.windowWidth;
windowHeight = imageOptions->_sourcePixelWindow.windowHeight;
break;
default:
// leave source window dimensions as whole image.
break;
}
switch(imageOptions->_destinationImageWindowMode)
{
case(osgDB::ImageOptions::RATIO_WINDOW):
destX = (unsigned int)(floor((double)dataWidth * imageOptions->_destinationRatioWindow.windowX));
destY = (unsigned int)(floor((double)dataHeight * imageOptions->_destinationRatioWindow.windowY));
destWidth = (unsigned int)(ceil((double)dataWidth * (imageOptions->_destinationRatioWindow.windowX + imageOptions->_destinationRatioWindow.windowWidth)))-windowX;
destHeight = (unsigned int)(ceil((double)dataHeight * (imageOptions->_destinationRatioWindow.windowY + imageOptions->_destinationRatioWindow.windowHeight)))-windowY;
break;
case(osgDB::ImageOptions::PIXEL_WINDOW):
destX = imageOptions->_destinationPixelWindow.windowX;
destY = imageOptions->_destinationPixelWindow.windowY;
destWidth = imageOptions->_destinationPixelWindow.windowWidth;
destHeight = imageOptions->_destinationPixelWindow.windowHeight;
break;
default:
// leave source window dimensions as whole image.
break;
}
}
// windowX = 0;
// windowY = 0;
// windowWidth = destWidth;
// windowHeight = destHeight;
OSG_INFO << " windowX = "<<windowX<<std::endl;
OSG_INFO << " windowY = "<<windowY<<std::endl;
OSG_INFO << " windowWidth = "<<windowWidth<<std::endl;
OSG_INFO << " windowHeight = "<<windowHeight<<std::endl;
OSG_INFO << std::endl;
OSG_INFO << " destX = "<<destX<<std::endl;
OSG_INFO << " destY = "<<destY<<std::endl;
OSG_INFO << " destWidth = "<<destWidth<<std::endl;
OSG_INFO << " destHeight = "<<destHeight<<std::endl;
OSG_INFO << std::endl;
OSG_INFO << " GetRaterCount() "<< dataset->GetRasterCount()<<std::endl;
OSG_INFO << " GetProjectionRef() "<< dataset->GetProjectionRef()<<std::endl;
double geoTransform[6];
CPLErr err = dataset->GetGeoTransform(geoTransform);
OSG_INFO << " GetGeoTransform == "<< err <<" == CE_None"<<std::endl;
OSG_INFO << " GetGeoTransform "<< std::endl;
OSG_INFO << " Origin = "<<geoTransform[0]<<" "<<geoTransform[3]<<std::endl;
OSG_INFO << " Pixel X = "<<geoTransform[1]<<" "<<geoTransform[4]<<std::endl;
OSG_INFO << " Pixel Y = "<<geoTransform[2]<<" "<<geoTransform[5]<<std::endl;
double TopLeft[2],BottomLeft[2],BottomRight[2],TopRight[2];
TopLeft[0] = geoTransform[0];
TopLeft[1] = geoTransform[3];
BottomLeft[0] = TopLeft[0]+geoTransform[2]*(dataHeight-1);
BottomLeft[1] = TopLeft[1]+geoTransform[5]*(dataHeight-1);
BottomRight[0] = BottomLeft[0]+geoTransform[1]*(dataWidth-1);
BottomRight[1] = BottomLeft[1]+geoTransform[4]*(dataWidth-1);
TopRight[0] = TopLeft[0]+geoTransform[1]*(dataWidth-1);
TopRight[1] = TopLeft[1]+geoTransform[4]*(dataWidth-1);
double rotation = atan2(geoTransform[2], geoTransform[1]);
OSG_INFO<<"GDAL rotation = "<<rotation<<std::endl;
OSG_INFO << "TopLeft "<<TopLeft[0]<<"\t"<<TopLeft[1]<<std::endl;
OSG_INFO << "BottomLeft "<<BottomLeft[0]<<"\t"<<BottomLeft[1]<<std::endl;
OSG_INFO << "BottomRight "<<BottomRight[0]<<"\t"<<BottomRight[1]<<std::endl;
OSG_INFO << "TopRight "<<TopRight[0]<<"\t"<<TopRight[1]<<std::endl;
OSG_INFO<<" GDALGetGCPCount "<<dataset->GetGCPCount()<<std::endl;
int numBands = dataset->GetRasterCount();
GDALRasterBand* bandGray = 0;
GDALRasterBand* bandRed = 0;
GDALRasterBand* bandGreen = 0;
GDALRasterBand* bandBlue = 0;
GDALRasterBand* bandAlpha = 0;
for(int b=1;b<=numBands;++b)
{
GDALRasterBand* band = dataset->GetRasterBand(b);
OSG_INFO << " Band "<<b<<std::endl;
OSG_INFO << " GetOverviewCount() = "<< band->GetOverviewCount()<<std::endl;
OSG_INFO << " GetColorTable() = "<< band->GetColorTable()<<std::endl;
OSG_INFO << " DataTypeName() = "<< GDALGetDataTypeName(band->GetRasterDataType())<<std::endl;
OSG_INFO << " ColorIntepretationName() = "<< GDALGetColorInterpretationName(band->GetColorInterpretation())<<std::endl;
OSG_INFO << std::endl;
OSG_INFO << " GetNoDataValue() = "<< band->GetNoDataValue()<<std::endl;
OSG_INFO << " GetMinimum() = "<< band->GetMinimum()<<std::endl;
OSG_INFO << " GetMaximum() = "<< band->GetMaximum()<<std::endl;
OSG_INFO << " GetOffset() = "<< band->GetOffset()<<std::endl;
OSG_INFO << " GetScale() = "<< band->GetScale()<<std::endl;
OSG_INFO << " GetUnitType() = '"<< band->GetUnitType()<<"'"<<std::endl;
if (band->GetColorInterpretation()==GCI_GrayIndex) bandGray = band;
else if (band->GetColorInterpretation()==GCI_RedBand) bandRed = band;
else if (band->GetColorInterpretation()==GCI_GreenBand) bandGreen = band;
else if (band->GetColorInterpretation()==GCI_BlueBand) bandBlue = band;
else if (band->GetColorInterpretation()==GCI_AlphaBand) bandAlpha = band;
else bandGray = band;
}
GDALRasterBand* bandSelected = 0;
if (!bandSelected && bandGray) bandSelected = bandGray;
else if (!bandSelected && bandAlpha) bandSelected = bandAlpha;
else if (!bandSelected && bandRed) bandSelected = bandRed;
else if (!bandSelected && bandGreen) bandSelected = bandGreen;
else if (!bandSelected && bandBlue) bandSelected = bandBlue;
if (bandSelected)
{
osg::HeightField* hf = new osg::HeightField;
hf->allocate(destWidth,destHeight);
bandSelected->RasterIO(GF_Read,windowX,windowY,windowWidth,windowHeight,(void*)(&(hf->getHeightList().front())),destWidth,destHeight,GDT_Float32,0,0);
// now need to flip since the OSG's origin is in lower left corner.
OSG_INFO<<"flipping"<<std::endl;
unsigned int copy_r = hf->getNumRows()-1;
for(unsigned int r=0;r<copy_r;++r,--copy_r)
{
for(unsigned int c=0;c<hf->getNumColumns();++c)
{
float temp = hf->getHeight(c,r);
hf->setHeight(c,r,hf->getHeight(c,copy_r));
hf->setHeight(c,copy_r,temp);
}
}
hf->setOrigin(osg::Vec3(BottomLeft[0],BottomLeft[1],0));
hf->setXInterval(sqrt(geoTransform[1]*geoTransform[1] + geoTransform[2]*geoTransform[2]));
hf->setYInterval(sqrt(geoTransform[4]*geoTransform[4] + geoTransform[5]*geoTransform[5]));
hf->setRotation(osg::Quat(rotation, osg::Vec3d(0.0, 0.0, 1.0)));
return hf;
}
return ReadResult::FILE_NOT_HANDLED;
}
void initGDAL() const
{
static bool s_initialized = false;
if (!s_initialized)
{
s_initialized = true;
GDALAllRegister();
}
}
mutable OpenThreads::ReentrantMutex _serializerMutex;
};
// now register with Registry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(gdal, ReaderWriterGDAL)
| openscenegraph/osg | src/osgPlugins/gdal/ReaderWriterGDAL.cpp | C++ | lgpl-2.1 | 36,961 |
from PySide.QtCore import *
from PySide.QtGui import *
import unittest
class MyModel (QAbstractListModel):
stupidLine = QLine(0, 0, 10, 10)
def rowCount(self, parent):
return 1
def data(self, index, role):
return self.stupidLine
class TestBug693(unittest.TestCase):
def testIt(self):
app = QApplication([])
model = MyModel()
view = QListView()
view.setModel(model)
view.show()
# This must NOT throw the exception:
# RuntimeError: Internal C++ object (PySide.QtCore.QLine) already deleted.
MyModel.stupidLine.isNull()
if __name__ == "__main__":
unittest.main()
| enthought/pyside | tests/QtGui/bug_693.py | Python | lgpl-2.1 | 670 |
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin 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.
//
// Bytecoin 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 Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include "BaseTests.h"
#include <System/Timer.h>
#include "WalletLegacy/WalletLegacy.h"
#include "WalletLegacyObserver.h"
using namespace Tests;
using namespace CryptoNote;
class WalletLegacyTests : public BaseTest {
};
TEST_F(WalletLegacyTests, checkNetworkShutdown) {
auto networkCfg = TestNetworkBuilder(3, Topology::Star).
setBlockchain("testnet_300").build();
networkCfg[0].nodeType = NodeType::InProcess;
network.addNodes(networkCfg);
network.waitNodesReady();
auto& daemon = network.getNode(0);
{
auto node = daemon.makeINode();
WalletLegacy wallet(currency, *node);
wallet.initAndGenerate("pass");
WalletLegacyObserver observer;
wallet.addObserver(&observer);
std::error_code syncResult;
ASSERT_TRUE(observer.m_syncResult.waitFor(std::chrono::seconds(10), syncResult));
ASSERT_TRUE(!syncResult);
// sync completed
auto syncProgress = observer.getSyncProgress();
network.getNode(1).stopDaemon();
network.getNode(2).stopDaemon();
System::Timer(dispatcher).sleep(std::chrono::seconds(10));
// check that sync progress was not updated
ASSERT_EQ(syncProgress, observer.getSyncProgress());
}
}
| forknote/forknote | tests/IntegrationTests/WalletLegacyTests.cpp | C++ | lgpl-3.0 | 1,965 |
#ifndef TEST_SDB_H
#define TEST_SDB_H
static void diff_cb(const SdbDiff *diff, void *user) {
char buf[2048];
if (sdb_diff_format (buf, sizeof (buf), diff) < 0) {
return;
}
printf ("%s\n", buf);
}
static inline void print_sdb(Sdb *sdb) {
Sdb *e = sdb_new0 ();
sdb_diff (e, sdb, diff_cb, NULL);
sdb_free (e);
}
#define assert_sdb_eq(actual, expected, msg) mu_assert ((msg), sdb_diff (expected, actual, diff_cb, NULL));
#endif //R2DB_TEST_UTILS_H
| unixfreaxjp/radare2 | test/unit/test_sdb.h | C | lgpl-3.0 | 457 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_03) on Tue May 22 06:24:55 CEST 2012 -->
<title>CollectionUtils (Apache Ant API)</title>
<meta name="date" content="2012-05-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="CollectionUtils (Apache Ant API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/tools/ant/util/ClasspathUtils.Delegate.html" title="class in org.apache.tools.ant.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.EmptyEnumeration.html" title="class in org.apache.tools.ant.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/tools/ant/util/CollectionUtils.html" target="_top">Frames</a></li>
<li><a href="CollectionUtils.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_class_summary">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.tools.ant.util</div>
<h2 title="Class CollectionUtils" class="title">Class CollectionUtils</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.tools.ant.util.CollectionUtils</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="strong">CollectionUtils</span>
extends java.lang.Object</pre>
<div class="block">A set of helper methods related to collection manipulation.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.5</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.EmptyEnumeration.html" title="class in org.apache.tools.ant.util">CollectionUtils.EmptyEnumeration</a></strong></code>
<div class="block">An empty enumeration.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.List</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#EMPTY_LIST">EMPTY_LIST</a></strong></code>
<div class="block">Collections.emptyList() is Java5+.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#CollectionUtils()">CollectionUtils</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.Enumeration</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#append(java.util.Enumeration, java.util.Enumeration)">append</a></strong>(java.util.Enumeration e1,
java.util.Enumeration e2)</code>
<div class="block">Append one enumeration to another.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.Collection</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#asCollection(java.util.Iterator)">asCollection</a></strong>(java.util.Iterator iter)</code>
<div class="block">Returns a collection containing all elements of the iterator.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.util.Enumeration</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#asEnumeration(java.util.Iterator)">asEnumeration</a></strong>(java.util.Iterator iter)</code>
<div class="block">Adapt the specified Iterator to the Enumeration interface.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static java.util.Iterator</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#asIterator(java.util.Enumeration)">asIterator</a></strong>(java.util.Enumeration e)</code>
<div class="block">Adapt the specified Enumeration to the Iterator interface.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#equals(java.util.Dictionary, java.util.Dictionary)">equals</a></strong>(java.util.Dictionary d1,
java.util.Dictionary d2)</code>
<div class="block"><strong>Deprecated.</strong>
<div class="block"><i>since 1.6.x.</i></div>
</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#equals(java.util.Vector, java.util.Vector)">equals</a></strong>(java.util.Vector v1,
java.util.Vector v2)</code>
<div class="block"><strong>Deprecated.</strong>
<div class="block"><i>since 1.6.x.</i></div>
</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#flattenToString(java.util.Collection)">flattenToString</a></strong>(java.util.Collection c)</code>
<div class="block">Creates a comma separated list of all values held in the given
collection.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#frequency(java.util.Collection, java.lang.Object)">frequency</a></strong>(java.util.Collection c,
java.lang.Object o)</code>
<div class="block">Counts how often the given Object occurs in the given
collection using equals() for comparison.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.html#putAll(java.util.Dictionary, java.util.Dictionary)">putAll</a></strong>(java.util.Dictionary m1,
java.util.Dictionary m2)</code>
<div class="block"><strong>Deprecated.</strong>
<div class="block"><i>since 1.6.x.</i></div>
</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_detail">
<!-- -->
</a>
<h3>Field Detail</h3>
<a name="EMPTY_LIST">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>EMPTY_LIST</h4>
<pre>public static final java.util.List EMPTY_LIST</pre>
<div class="block">Collections.emptyList() is Java5+.</div>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="CollectionUtils()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>CollectionUtils</h4>
<pre>public CollectionUtils()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="equals(java.util.Vector, java.util.Vector)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public static boolean equals(java.util.Vector v1,
java.util.Vector v2)</pre>
<div class="block"><span class="strong">Deprecated.</span> <i>since 1.6.x.</i></div>
<div class="block">Please use Vector.equals() or List.equals().</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>v1</code> - the first vector.</dd><dd><code>v2</code> - the second vector.</dd>
<dt><span class="strong">Returns:</span></dt><dd>true if the vectors are equal.</dd><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.5</dd></dl>
</li>
</ul>
<a name="equals(java.util.Dictionary, java.util.Dictionary)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public static boolean equals(java.util.Dictionary d1,
java.util.Dictionary d2)</pre>
<div class="block"><span class="strong">Deprecated.</span> <i>since 1.6.x.</i></div>
<div class="block">Dictionary does not have an equals.
Please use Map.equals().
<p>Follows the equals contract of Java 2's Map.</p></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>d1</code> - the first directory.</dd><dd><code>d2</code> - the second directory.</dd>
<dt><span class="strong">Returns:</span></dt><dd>true if the directories are equal.</dd><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.5</dd></dl>
</li>
</ul>
<a name="flattenToString(java.util.Collection)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>flattenToString</h4>
<pre>public static java.lang.String flattenToString(java.util.Collection c)</pre>
<div class="block">Creates a comma separated list of all values held in the given
collection.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.8.0</dd></dl>
</li>
</ul>
<a name="putAll(java.util.Dictionary, java.util.Dictionary)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>putAll</h4>
<pre>public static void putAll(java.util.Dictionary m1,
java.util.Dictionary m2)</pre>
<div class="block"><span class="strong">Deprecated.</span> <i>since 1.6.x.</i></div>
<div class="block">Dictionary does not know the putAll method. Please use Map.putAll().</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>m1</code> - the to directory.</dd><dd><code>m2</code> - the from directory.</dd><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.6</dd></dl>
</li>
</ul>
<a name="append(java.util.Enumeration, java.util.Enumeration)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>append</h4>
<pre>public static java.util.Enumeration append(java.util.Enumeration e1,
java.util.Enumeration e2)</pre>
<div class="block">Append one enumeration to another.
Elements are evaluated lazily.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>e1</code> - the first enumeration.</dd><dd><code>e2</code> - the subsequent enumeration.</dd>
<dt><span class="strong">Returns:</span></dt><dd>an enumeration representing e1 followed by e2.</dd><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.6.3</dd></dl>
</li>
</ul>
<a name="asEnumeration(java.util.Iterator)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>asEnumeration</h4>
<pre>public static java.util.Enumeration asEnumeration(java.util.Iterator iter)</pre>
<div class="block">Adapt the specified Iterator to the Enumeration interface.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>iter</code> - the Iterator to adapt.</dd>
<dt><span class="strong">Returns:</span></dt><dd>an Enumeration.</dd></dl>
</li>
</ul>
<a name="asIterator(java.util.Enumeration)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>asIterator</h4>
<pre>public static java.util.Iterator asIterator(java.util.Enumeration e)</pre>
<div class="block">Adapt the specified Enumeration to the Iterator interface.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>e</code> - the Enumeration to adapt.</dd>
<dt><span class="strong">Returns:</span></dt><dd>an Iterator.</dd></dl>
</li>
</ul>
<a name="asCollection(java.util.Iterator)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>asCollection</h4>
<pre>public static java.util.Collection asCollection(java.util.Iterator iter)</pre>
<div class="block">Returns a collection containing all elements of the iterator.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.8.0</dd></dl>
</li>
</ul>
<a name="frequency(java.util.Collection, java.lang.Object)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>frequency</h4>
<pre>public static int frequency(java.util.Collection c,
java.lang.Object o)</pre>
<div class="block">Counts how often the given Object occurs in the given
collection using equals() for comparison.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.8.0</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/tools/ant/util/ClasspathUtils.Delegate.html" title="class in org.apache.tools.ant.util"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/tools/ant/util/CollectionUtils.EmptyEnumeration.html" title="class in org.apache.tools.ant.util"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/tools/ant/util/CollectionUtils.html" target="_top">Frames</a></li>
<li><a href="CollectionUtils.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li><a href="#nested_class_summary">Nested</a> | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| SimoRihani/PFA-Qucit | www/node_modules/ant/ant/manual/api/org/apache/tools/ant/util/CollectionUtils.html | HTML | lgpl-3.0 | 19,356 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Example3 Tests</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{content-for 'head'}}
{{content-for 'test-head'}}
<link rel="stylesheet" href="assets/vendor.css">
<link rel="stylesheet" href="assets/example3.css">
<link rel="stylesheet" href="assets/test-support.css">
{{content-for 'head-footer'}}
{{content-for 'test-head-footer'}}
</head>
<body>
{{content-for 'body'}}
{{content-for 'test-body'}}
<script src="assets/vendor.js"></script>
<script src="assets/test-support.js"></script>
<script src="assets/example3.js"></script>
<script src="testem.js"></script>
<script src="assets/test-loader.js"></script>
{{content-for 'body-footer'}}
{{content-for 'test-body-footer'}}
</body>
</html>
| Rodic/emberjs-essentials | chapter-3/example3/tests/index.html | HTML | lgpl-3.0 | 969 |
<?php
echo "Hello World!";
| dmp1ce/decompose-nginx-php | skel/containers/source/http/index.php | PHP | unlicense | 27 |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/canbus/vehicle/gem/protocol/global_cmd_69.h"
#include "modules/drivers/canbus/common/byte.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
const int32_t Globalcmd69::ID = 0x69;
// public
Globalcmd69::Globalcmd69() { Reset(); }
uint32_t Globalcmd69::GetPeriod() const {
// TODO(QiL) :modify every protocol's period manually
static const uint32_t PERIOD = 20 * 1000;
return PERIOD;
}
void Globalcmd69::UpdateData(uint8_t* data) {
set_p_pacmod_enable(data, pacmod_enable_);
set_p_clear_override(data, clear_override_);
set_p_ignore_override(data, ignore_override_);
}
void Globalcmd69::Reset() {
// TODO(QiL) :you should check this manually
pacmod_enable_ = Global_cmd_69::PACMOD_ENABLE_CONTROL_DISABLED;
clear_override_ = Global_cmd_69::CLEAR_OVERRIDE_DON_T_CLEAR_ACTIVE_OVERRIDES;
ignore_override_ = Global_cmd_69::IGNORE_OVERRIDE_DON_T_IGNORE_USER_OVERRIDES;
}
Globalcmd69* Globalcmd69::set_pacmod_enable(
Global_cmd_69::Pacmod_enableType pacmod_enable) {
pacmod_enable_ = pacmod_enable;
return this;
}
// config detail: {'name': 'PACMOD_ENABLE', 'enum': {0:
// 'PACMOD_ENABLE_CONTROL_DISABLED', 1: 'PACMOD_ENABLE_CONTROL_ENABLED'},
// 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0,
// 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola',
// 'physical_unit': ''}
void Globalcmd69::set_p_pacmod_enable(
uint8_t* data, Global_cmd_69::Pacmod_enableType pacmod_enable) {
uint8_t x = pacmod_enable;
Byte to_set(data + 0);
to_set.set_value(static_cast<uint8_t>(x), 0, 1);
}
Globalcmd69* Globalcmd69::set_clear_override(
Global_cmd_69::Clear_overrideType clear_override) {
clear_override_ = clear_override;
return this;
}
// config detail: {'name': 'CLEAR_OVERRIDE', 'enum': {0:
// 'CLEAR_OVERRIDE_DON_T_CLEAR_ACTIVE_OVERRIDES', 1:
// 'CLEAR_OVERRIDE_CLEAR_ACTIVE_OVERRIDES'}, 'precision': 1.0, 'len': 1,
// 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1,
// 'type': 'enum', 'order': 'motorola', 'physical_unit': ''}
void Globalcmd69::set_p_clear_override(
uint8_t* data, Global_cmd_69::Clear_overrideType clear_override) {
uint8_t x = clear_override;
Byte to_set(data + 0);
to_set.set_value(static_cast<uint8_t>(x), 1, 1);
}
Globalcmd69* Globalcmd69::set_ignore_override(
Global_cmd_69::Ignore_overrideType ignore_override) {
ignore_override_ = ignore_override;
return this;
}
// config detail: {'name': 'IGNORE_OVERRIDE', 'enum': {0:
// 'IGNORE_OVERRIDE_DON_T_IGNORE_USER_OVERRIDES', 1:
// 'IGNORE_OVERRIDE_IGNORE_USER_OVERRIDES'}, 'precision': 1.0, 'len': 1,
// 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2,
// 'type': 'enum', 'order': 'motorola', 'physical_unit': ''}
void Globalcmd69::set_p_ignore_override(
uint8_t* data, Global_cmd_69::Ignore_overrideType ignore_override) {
uint8_t x = ignore_override;
Byte to_set(data + 0);
to_set.set_value(static_cast<uint8_t>(x), 2, 1);
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| msbeta/apollo | modules/canbus/vehicle/gem/protocol/global_cmd_69.cc | C++ | apache-2.0 | 3,874 |
package com.badlogic.gdx.backends.lwjgl3;
/**
* Convenience implementation of {@link Lwjgl3WindowListener}. Derive from this class
* and only overwrite the methods you are interested in.
* @author badlogic
*
*/
public class Lwjgl3WindowAdapter implements Lwjgl3WindowListener {
@Override
public void iconified() {
}
@Override
public void deiconified() {
}
@Override
public void focusLost() {
}
@Override
public void focusGained() {
}
@Override
public boolean windowIsClosing() {
return true;
}
}
| SidneyXu/libgdx | backends/gdx-backend-lwjgl3/src/com/badlogic/gdx/backends/lwjgl3/Lwjgl3WindowAdapter.java | Java | apache-2.0 | 523 |
/**
@license
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
import { ElementMixin, version } from './lib/mixins/element-mixin.js';
export { html } from './lib/utils/html-tag.js';
export { version };
/**
* Base class that provides the core API for Polymer's meta-programming
* features including template stamping, data-binding, attribute deserialization,
* and property change observation.
*
* @customElement
* @polymer
* @constructor
* @implements {Polymer_ElementMixin}
* @extends HTMLElement
* @appliesMixin ElementMixin
* @summary Custom element base class that provides the core API for Polymer's
* key meta-programming features including template stamping, data-binding,
* attribute deserialization, and property change observation
*/
export const PolymerElement = ElementMixin(HTMLElement);
| shapesecurity/shift-website | vendor/@polymer/polymer/polymer-element.js | JavaScript | apache-2.0 | 1,270 |
/*
* 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 <qpid/client/Connection.h>
#include <qpid/client/Session.h>
#include <qpid/client/SubscriptionManager.h>
#include <axis2_amqp_request_processor.h>
#include <axis2_amqp_defines.h>
#include <axis2_amqp_util.h>
#include <axis2_qpid_receiver_listener.h>
#include <axis2_qpid_receiver.h>
#include <list>
Axis2QpidReceiver::Axis2QpidReceiver(
const axutil_env_t* env,
axis2_conf_ctx_t* conf_ctx)
{
this->env = env;
this->conf_ctx = conf_ctx;
}
Axis2QpidReceiver::~Axis2QpidReceiver(
void)
{
}
bool
Axis2QpidReceiver::start(
void)
{
if(!conf_ctx)
return false;
Connection connection;
axis2_bool_t serverSide = AXIS2_TRUE;
serverSide = axis2_amqp_util_conf_ctx_get_server_side(conf_ctx, env);
while(true)
{
try
{
std::list<string> queueNameList;
string qpidBrokerIP = axis2_amqp_util_conf_ctx_get_qpid_broker_ip(conf_ctx, env);
int qpidBrokerPort = axis2_amqp_util_conf_ctx_get_qpid_broker_port(conf_ctx, env);
/* Check if Client Side and Resolve Dynamic Queue Name */
if(serverSide == AXIS2_TRUE) /* Server side */
{
std::cout << "Connecting to Qpid Broker on " << qpidBrokerIP << ":"
<< qpidBrokerPort << " ... ";
}
/* Create Connection to Qpid Broker */
connection.open(qpidBrokerIP, qpidBrokerPort);
if(serverSide == AXIS2_TRUE) /* Server side */
{
/* Create queue for each service. Queue name is equal to service name */
axis2_conf_t* conf = axis2_conf_ctx_get_conf(conf_ctx, env);
if(!conf)
return false;
axutil_hash_t* serviceMap = axis2_conf_get_all_svcs(conf, env);
if(!serviceMap)
return false;
axutil_hash_index_t* serviceHI = NULL;
void* serviceValue = NULL;
for(serviceHI = axutil_hash_first(serviceMap, env); serviceHI; serviceHI
= axutil_hash_next(env, serviceHI))
{
axutil_hash_this(serviceHI, NULL, NULL, &serviceValue);
axis2_svc_t* service = (axis2_svc_t*)serviceValue;
if(!service)
return false;
axis2_char_t* serviceName = axutil_qname_get_localpart(axis2_svc_get_qname(
service, env), env);
if(!serviceName)
return false;
queueNameList.push_back(serviceName);
}
std::cout << "CONNECTED" << std::endl;
}
else /* Client side separate listener in dual-channel case */
{
string queueName = axis2_amqp_util_conf_ctx_get_dual_channel_queue_name(conf_ctx,
env);
queueNameList.push_back(queueName);
}
/* Create new session */
Session session = connection.newSession();
/* Create Subscription manager */
SubscriptionManager subscriptionManager(session);
Axis2QpidReceiverListener qpidReceiverListener(env, conf_ctx);
/* Subscribe to queues */
while(!queueNameList.empty())
{
string queueName = queueNameList.front();
session.queueDeclare(arg::queue = queueName, arg::autoDelete = true);
session.exchangeBind(arg::exchange = AXIS2_AMQP_EXCHANGE_DIRECT, arg::queue
= queueName, arg::bindingKey = queueName);
subscriptionManager.subscribe(qpidReceiverListener, queueName);
queueNameList.pop_front();
}
/* Listen and Wait */
if(serverSide == AXIS2_TRUE) /* Server side */
{
std::cout << "Started Axis2 AMQP Server ..." << std::endl;
}
subscriptionManager.run();
return true;
}
catch(const std::exception& e)
{
connection.close();
if(serverSide == AXIS2_TRUE) /* Server side */
{
std::cout << "FAILED" << std::endl;
}
sleep(5);
}
}
connection.close();
return false;
}
bool
Axis2QpidReceiver::shutdown(
void)
{
return true;
}
| gillesgagniard/wso2-wsf-cpp-gg | wsf_c/axis2c/src/core/transport/amqp/receiver/qpid_receiver/axis2_qpid_receiver.cpp | C++ | apache-2.0 | 5,262 |
/* 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.
*/
package org.camunda.bpm.engine.impl.batch;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.core.variable.mapping.value.ConstantValueProvider;
import org.camunda.bpm.engine.impl.core.variable.mapping.value.ParameterValueProvider;
import org.camunda.bpm.engine.impl.jobexecutor.JobDeclaration;
import org.camunda.bpm.engine.impl.jobexecutor.JobHandlerConfiguration;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.MessageEntity;
public class BatchJobDeclaration extends JobDeclaration<BatchJobContext, MessageEntity> {
public BatchJobDeclaration(String jobHandlerType) {
super(jobHandlerType);
}
@Override
protected ExecutionEntity resolveExecution(BatchJobContext context) {
return null;
}
@Override
protected MessageEntity newJobInstance(BatchJobContext context) {
return new MessageEntity();
}
@Override
protected JobHandlerConfiguration resolveJobHandlerConfiguration(BatchJobContext context) {
return new BatchJobConfiguration(context.getConfiguration().getId());
}
@Override
protected String resolveJobDefinitionId(BatchJobContext context) {
return context.getBatch().getBatchJobDefinitionId();
}
public ParameterValueProvider getJobPriorityProvider() {
long batchJobPriority = Context.getProcessEngineConfiguration()
.getBatchJobPriority();
return new ConstantValueProvider(batchJobPriority);
}
}
| subhrajyotim/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/batch/BatchJobDeclaration.java | Java | apache-2.0 | 2,056 |
/*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.ovsdb.controller;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
/**
* The class representing a port type.
* This class is immutable.
*/
public class OvsdbPortType {
private final String value;
/**
* Constructor from a String.
*
* @param value the port type to use
*/
public OvsdbPortType(String value) {
checkNotNull(value, "value is not null");
this.value = value;
}
/**
* Gets the value of port type.
*
* @return the value of port type
*/
public String value() {
return value;
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof OvsdbPortType) {
final OvsdbPortType otherOvsdbPortType = (OvsdbPortType) obj;
return Objects.equals(this.value, otherOvsdbPortType.value);
}
return false;
}
@Override
public String toString() {
return toStringHelper(this).add("value", value).toString();
}
}
| gkatsikas/onos | protocols/ovsdb/api/src/main/java/org/onosproject/ovsdb/controller/OvsdbPortType.java | Java | apache-2.0 | 1,884 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* 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.
*/
package com.intellij.debugger.ui;
import com.intellij.codeInsight.hint.HintUtil;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerInvocationUtil;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.actions.DebuggerActions;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.JVMName;
import com.intellij.debugger.engine.JVMNameUtil;
import com.intellij.debugger.engine.evaluation.*;
import com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl;
import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator;
import com.intellij.debugger.engine.events.DebuggerContextCommandImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.impl.EditorTextProvider;
import com.intellij.debugger.ui.impl.DebuggerTreeRenderer;
import com.intellij.debugger.ui.impl.InspectDebuggerTree;
import com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl;
import com.intellij.debugger.ui.impl.watch.WatchItemDescriptor;
import com.intellij.debugger.ui.tree.render.DescriptorLabelListener;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.psi.*;
import com.intellij.ui.SimpleColoredText;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xdebugger.impl.evaluate.quick.common.AbstractValueHint;
import com.intellij.xdebugger.impl.evaluate.quick.common.ValueHintType;
import com.sun.jdi.Method;
import com.sun.jdi.PrimitiveValue;
import com.sun.jdi.Value;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
/**
* @author lex
* @since Nov 24, 2003
*/
public class ValueHint extends AbstractValueHint {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.ValueHint");
private PsiElement myCurrentExpression = null;
private Value myValueToShow = null;
private ValueHint(Project project, Editor editor, Point point, ValueHintType type, final PsiElement selectedExpression, final TextRange textRange) {
super(project, editor, point, type, textRange);
myCurrentExpression = selectedExpression;
}
public static ValueHint createValueHint(Project project, Editor editor, Point point, ValueHintType type) {
Trinity<PsiElement, TextRange, Value> trinity = getSelectedExpression(project, editor, point, type);
final ValueHint hint = new ValueHint(project, editor, point, type, trinity.getFirst(), trinity.getSecond());
hint.myValueToShow = trinity.getThird();
return hint;
}
@Override
protected boolean canShowHint() {
return myCurrentExpression != null;
}
@Nullable
private ExpressionEvaluator getExpressionEvaluator(DebuggerContextImpl debuggerContext) throws EvaluateException {
if (myCurrentExpression instanceof PsiExpression) {
return EvaluatorBuilderImpl.getInstance().build(myCurrentExpression, debuggerContext.getSourcePosition());
}
TextWithImportsImpl textWithImports = new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, myCurrentExpression.getText());
CodeFragmentFactory factory = DebuggerUtilsEx.findAppropriateCodeFragmentFactory(textWithImports, myCurrentExpression);
JavaCodeFragment codeFragment = factory.createCodeFragment(textWithImports, myCurrentExpression.getContext(), getProject());
return factory.getEvaluatorBuilder().build(codeFragment, debuggerContext.getSourcePosition());
}
@Override
protected void evaluateAndShowHint() {
final DebuggerContextImpl debuggerContext = DebuggerManagerEx.getInstanceEx(getProject()).getContext();
final DebuggerSession debuggerSession = debuggerContext.getDebuggerSession();
if(debuggerSession == null || !debuggerSession.isPaused()) return;
try {
final ExpressionEvaluator evaluator = getExpressionEvaluator(debuggerContext);
if (evaluator == null) return;
debuggerContext.getDebugProcess().getManagerThread().schedule(new DebuggerContextCommandImpl(debuggerContext) {
@Override
public Priority getPriority() {
return Priority.HIGH;
}
@Override
public void threadAction() {
try {
final EvaluationContextImpl evaluationContext = debuggerContext.createEvaluationContext();
final String expressionText = ReadAction.compute(() -> myCurrentExpression.getText());
final TextWithImports text = new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, expressionText);
final Value value = myValueToShow != null? myValueToShow : evaluator.evaluate(evaluationContext);
final WatchItemDescriptor descriptor = new WatchItemDescriptor(getProject(), text, value);
if (!isActiveTooltipApplicable(value) || getType() == ValueHintType.MOUSE_OVER_HINT) {
if (getType() == ValueHintType.MOUSE_OVER_HINT) {
// force using default renderer for mouse over hint in order to not to call accidentally methods while rendering
// otherwise, if the hint is invoked explicitly, show it with the right "auto" renderer
descriptor.setRenderer(DebugProcessImpl.getDefaultRenderer(value));
}
descriptor.updateRepresentation(evaluationContext, new DescriptorLabelListener() {
@Override
public void labelChanged() {
if(getCurrentRange() != null) {
if(getType() != ValueHintType.MOUSE_OVER_HINT || descriptor.isValueValid()) {
final SimpleColoredText simpleColoredText = DebuggerTreeRenderer.getDescriptorText(debuggerContext, descriptor, true);
if (isActiveTooltipApplicable(value)){
simpleColoredText.append(" (" + DebuggerBundle.message("active.tooltip.suggestion") + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
showHint(simpleColoredText, descriptor);
}
}
}
});
}
else {
createAndShowTree(expressionText, descriptor);
}
}
catch (EvaluateException e) {
LOG.debug(e);
}
}
});
}
catch (EvaluateException e) {
LOG.debug(e);
}
}
private void createAndShowTree(final String expressionText, final NodeDescriptorImpl descriptor) {
final DebuggerTreeCreatorImpl creator = new DebuggerTreeCreatorImpl(getProject());
DebuggerInvocationUtil.invokeLater(getProject(), () -> showTreePopup(creator, Pair.create(descriptor, expressionText)));
}
private static boolean isActiveTooltipApplicable(final Value value) {
return value != null && !(value instanceof PrimitiveValue);
}
private void showHint(final SimpleColoredText text, final WatchItemDescriptor descriptor) {
DebuggerInvocationUtil.invokeLater(getProject(), () -> {
if(!isHintHidden()) {
JComponent component;
if (!isActiveTooltipApplicable(descriptor.getValue())) {
component = HintUtil.createInformationLabel(text);
}
else {
component = createExpandableHintComponent(text, () -> {
final DebuggerContextImpl debuggerContext = DebuggerManagerEx.getInstanceEx(getProject()).getContext();
final DebugProcessImpl debugProcess = debuggerContext.getDebugProcess();
debugProcess.getManagerThread().schedule(new DebuggerContextCommandImpl(debuggerContext) {
@Override
public void threadAction() {
descriptor.setRenderer(debugProcess.getAutoRenderer(descriptor));
final String expressionText = ReadAction.compute(() -> myCurrentExpression.getText());
createAndShowTree(expressionText, descriptor);
}
});
});
}
if (!showHint(component)) return;
if(getType() == ValueHintType.MOUSE_CLICK_HINT) {
HintUtil.createInformationLabel(text).requestFocusInWindow();
}
}
});
}
public static InspectDebuggerTree createInspectTree(final NodeDescriptorImpl descriptor, Project project) {
final InspectDebuggerTree tree = new InspectDebuggerTree(project);
final AnAction setValueAction = ActionManager.getInstance().getAction(DebuggerActions.SET_VALUE);
setValueAction.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)), tree);
Disposer.register(tree, new Disposable() {
@Override
public void dispose() {
setValueAction.unregisterCustomShortcutSet(tree);
}
});
tree.setInspectDescriptor(descriptor);
DebuggerContextImpl context = DebuggerManagerEx.getInstanceEx(project).getContext();
tree.rebuild(context);
return tree;
}
@Nullable
private static Pair<PsiElement, TextRange> findExpression(PsiElement element, boolean allowMethodCalls) {
final EditorTextProvider textProvider = EditorTextProvider.EP.forLanguage(element.getLanguage());
if (textProvider != null) {
return textProvider.findExpression(element, allowMethodCalls);
}
return null;
}
private static Trinity<PsiElement, TextRange, Value> getSelectedExpression(final Project project, final Editor editor, final Point point, final ValueHintType type) {
final Ref<PsiElement> selectedExpression = Ref.create(null);
final Ref<TextRange> currentRange = Ref.create(null);
final Ref<Value> preCalculatedValue = Ref.create(null);
PsiDocumentManager.getInstance(project).commitAndRunReadAction(() -> {
// Point -> offset
final int offset = calculateOffset(editor, point);
PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if(psiFile == null || !psiFile.isValid()) {
return;
}
int selectionStart = editor.getSelectionModel().getSelectionStart();
int selectionEnd = editor.getSelectionModel().getSelectionEnd();
if((type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT) && (selectionStart <= offset && offset <= selectionEnd)) {
PsiElement ctx = (selectionStart > 0) ? psiFile.findElementAt(selectionStart - 1) : psiFile.findElementAt(selectionStart);
try {
String text = editor.getSelectionModel().getSelectedText();
if(text != null && ctx != null) {
final JVMElementFactory factory = JVMElementFactories.getFactory(ctx.getLanguage(), project);
if (factory == null) {
return;
}
selectedExpression.set(factory.createExpressionFromText(text, ctx));
currentRange.set(new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd()));
}
}
catch (IncorrectOperationException ignored) {
}
}
if(currentRange.get() == null) {
PsiElement elementAtCursor = psiFile.findElementAt(offset);
if (elementAtCursor == null) {
return;
}
Pair<PsiElement, TextRange> pair = findExpression(elementAtCursor, type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT);
if (pair == null) {
if (type == ValueHintType.MOUSE_OVER_HINT) {
final DebuggerSession debuggerSession = DebuggerManagerEx.getInstanceEx(project).getContext().getDebuggerSession();
if(debuggerSession != null && debuggerSession.isPaused()) {
final Pair<Method, Value> lastExecuted = debuggerSession.getProcess().getLastExecutedMethod();
if (lastExecuted != null) {
final Method method = lastExecuted.getFirst();
if (method != null) {
final Pair<PsiElement, TextRange> expressionPair = findExpression(elementAtCursor, true);
if (expressionPair != null && expressionPair.getFirst() instanceof PsiMethodCallExpression) {
final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)expressionPair.getFirst();
final PsiMethod psiMethod = methodCallExpression.resolveMethod();
if (psiMethod != null) {
final JVMName jvmSignature = JVMNameUtil.getJVMSignature(psiMethod);
try {
if (method.name().equals(psiMethod.getName()) && method.signature().equals(jvmSignature.getName(debuggerSession.getProcess()))) {
pair = expressionPair;
preCalculatedValue.set(lastExecuted.getSecond());
}
}
catch (EvaluateException ignored) {
}
}
}
}
}
}
}
}
if (pair == null) {
return;
}
selectedExpression.set(pair.getFirst());
currentRange.set(pair.getSecond());
}
});
return Trinity.create(selectedExpression.get(), currentRange.get(), preCalculatedValue.get());
}
}
| asedunov/intellij-community | java/debugger/impl/src/com/intellij/debugger/ui/ValueHint.java | Java | apache-2.0 | 14,440 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hu-HU">
<title>Directory List v2.3</title>
<maps>
<homeID>directorylistv2_3</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/directorylistv2_3/src/main/javahelp/help_hu_HU/helpset_hu_HU.hs | Haskell | apache-2.0 | 978 |
declare module "ui/layouts/wrap-layout" {
import layout = require("ui/layouts/layout-base");
import dependencyObservable = require("ui/core/dependency-observable");
/**
* WrapLayout position children in rows or columns depending on orientation property
* until space is filled and then wraps them on new row or column.
*/
class WrapLayout extends layout.LayoutBase {
/**
* Represents the observable property backing the orientation property of each WrapLayout instance.
*/
public static orientationProperty: dependencyObservable.Property;
/**
* Represents the observable property backing the itemWidth property of each WrapLayout instance.
*/
public static itemWidthProperty: dependencyObservable.Property;
/**
* Represents the observable property backing the itemHeight property of each WrapLayout instance.
*/
public static itemHeightProperty: dependencyObservable.Property;
/**
* Gets or sets the flow direction. Default value is horizontal.
* If orientation is horizontal items are arranged in rows, else items are arranged in columns.
*/
orientation: string;
/**
* Gets or sets the width used to measure and layout each child.
* Default value is Number.NaN which does not restrict children.
*/
itemWidth: number;
/**
* Gets or sets the height used to measure and layout each child.
* Default value is Number.NaN which does not restrict children.
*/
itemHeight: number;
}
} | PeterStaev/NativeScript-Status-Bar | sample/StatusBarSample/typings/tns-core-modules/ui/layouts/wrap-layout/wrap-layout.d.ts | TypeScript | apache-2.0 | 1,658 |
package io.cattle.platform.docker.storage.dao.impl;
import static io.cattle.platform.core.model.tables.InstanceTable.*;
import static io.cattle.platform.core.model.tables.ImageTable.*;
import static io.cattle.platform.core.model.tables.StoragePoolTable.*;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.model.Credential;
import io.cattle.platform.core.model.Image;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.StoragePool;
import io.cattle.platform.docker.constants.DockerStoragePoolConstants;
import io.cattle.platform.docker.storage.dao.DockerStorageDao;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.process.StandardProcess;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.storage.ImageCredentialLookup;
import io.cattle.platform.storage.service.StorageService;
import java.util.List;
import javax.inject.Inject;
public class DockerStorageDaoImpl implements DockerStorageDao {
@Inject
ObjectManager objectManager;
@Inject
ObjectProcessManager processManager;
@Inject
StorageService storageService;
List<ImageCredentialLookup> imageCredentialLookups;
@Override
public StoragePool getExternalStoragePool(StoragePool parentPool) {
return objectManager.findOne(StoragePool.class,
STORAGE_POOL.KIND, DockerStoragePoolConstants.DOCKER_KIND,
STORAGE_POOL.EXTERNAL, true);
}
@Override
public StoragePool createExternalStoragePool(StoragePool parentPool) {
StoragePool externalPool = objectManager.create(StoragePool.class,
STORAGE_POOL.NAME, "Docker Index",
STORAGE_POOL.ACCOUNT_ID, parentPool.getAccountId(),
STORAGE_POOL.EXTERNAL, true,
STORAGE_POOL.KIND, DockerStoragePoolConstants.DOCKER_KIND);
processManager.scheduleStandardProcess(StandardProcess.CREATE, externalPool, null);
return objectManager.reload(externalPool);
}
@Override
public Image createImageForInstance(Instance instance) {
String uuid = (String) DataAccessor.fields(instance).withKey(InstanceConstants.FIELD_IMAGE_UUID).get();
Image image = storageService.registerRemoteImage(uuid);
if (image != null) {
objectManager.setFields(instance, INSTANCE.IMAGE_ID, image.getId());
long currentAccount = instance.getAccountId();
Long id = instance.getRegistryCredentialId();
image = objectManager.loadResource(Image.class, instance.getImageId());
if (id == null) {
for (ImageCredentialLookup imageLookup: imageCredentialLookups){
Credential cred = imageLookup.getDefaultCredential(uuid, currentAccount);
if (cred == null){
continue;
}
if (cred.getId() != null){
objectManager.setFields(instance, INSTANCE.REGISTRY_CREDENTIAL_ID, cred.getId());
break;
}
}
}
if (instance.getRegistryCredentialId() != null) {
objectManager.setFields(image, IMAGE.REGISTRY_CREDENTIAL_ID, instance.getRegistryCredentialId());
}
}
return image;
}
public List<ImageCredentialLookup> getImageCredentialLookups() {
return imageCredentialLookups;
}
@Inject
public void setImageCredentialLookups(List<ImageCredentialLookup> imageCredentialLookups) {
this.imageCredentialLookups = imageCredentialLookups;
}
}
| dx9/cattle | code/implementation/docker/storage/src/main/java/io/cattle/platform/docker/storage/dao/impl/DockerStorageDaoImpl.java | Java | apache-2.0 | 3,750 |
/*
* 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.
*/
package org.apache.hadoop.hbase.client;
import java.util.Arrays;
import org.apache.hadoop.hbase.CellComparator;
import org.apache.hadoop.hbase.CellComparatorImpl;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An implementation of RegionInfo that adds mutable methods so can build a RegionInfo instance.
* Package private. Use {@link RegionInfoBuilder} creating instances of {@link RegionInfo}s.
*/
@InterfaceAudience.Private
class MutableRegionInfo implements RegionInfo {
private static final Logger LOG = LoggerFactory.getLogger(MutableRegionInfo.class);
private static final int MAX_REPLICA_ID = 0xFFFF;
/**
* The new format for a region name contains its encodedName at the end.
* The encoded name also serves as the directory name for the region
* in the filesystem.
*
* New region name format:
* <tablename>,,<startkey>,<regionIdTimestamp>.<encodedName>.
* where,
* <encodedName> is a hex version of the MD5 hash of
* <tablename>,<startkey>,<regionIdTimestamp>
*
* The old region name format:
* <tablename>,<startkey>,<regionIdTimestamp>
* For region names in the old format, the encoded name is a 32-bit
* JenkinsHash integer value (in its decimal notation, string form).
*<p>
* **NOTE**
*
* The first hbase:meta region, and regions created by an older
* version of HBase (0.20 or prior) will continue to use the
* old region name format.
*/
// This flag is in the parent of a split while the parent is still referenced by daughter
// regions. We USED to set this flag when we disabled a table but now table state is kept up in
// zookeeper as of 0.90.0 HBase. And now in DisableTableProcedure, finally we will create bunch
// of UnassignProcedures and at the last of the procedure we will set the region state to
// CLOSED, and will not change the offLine flag.
private boolean offLine;
private boolean split;
private final long regionId;
private final int replicaId;
private final byte[] regionName;
private final byte[] startKey;
private final byte[] endKey;
private final int hashCode;
private final String encodedName;
private final byte[] encodedNameAsBytes;
private final TableName tableName;
private static int generateHashCode(final TableName tableName, final byte[] startKey,
final byte[] endKey, final long regionId,
final int replicaId, boolean offLine, byte[] regionName) {
int result = Arrays.hashCode(regionName);
result = (int) (result ^ regionId);
result ^= Arrays.hashCode(checkStartKey(startKey));
result ^= Arrays.hashCode(checkEndKey(endKey));
result ^= Boolean.valueOf(offLine).hashCode();
result ^= Arrays.hashCode(tableName.getName());
result ^= replicaId;
return result;
}
private static byte[] checkStartKey(byte[] startKey) {
return startKey == null? HConstants.EMPTY_START_ROW: startKey;
}
private static byte[] checkEndKey(byte[] endKey) {
return endKey == null? HConstants.EMPTY_END_ROW: endKey;
}
private static TableName checkTableName(TableName tableName) {
if (tableName == null) {
throw new IllegalArgumentException("TableName cannot be null");
}
return tableName;
}
private static int checkReplicaId(int regionId) {
if (regionId > MAX_REPLICA_ID) {
throw new IllegalArgumentException("ReplicaId cannot be greater than" + MAX_REPLICA_ID);
}
return regionId;
}
/**
* Package private constructor used constructing MutableRegionInfo for the first meta regions
*/
MutableRegionInfo(long regionId, TableName tableName, int replicaId) {
this(tableName, HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, false, regionId,
replicaId, false);
}
MutableRegionInfo(final TableName tableName, final byte[] startKey, final byte[] endKey,
final boolean split, final long regionId, final int replicaId, boolean offLine) {
this.tableName = checkTableName(tableName);
this.startKey = checkStartKey(startKey);
this.endKey = checkEndKey(endKey);
this.split = split;
this.regionId = regionId;
this.replicaId = checkReplicaId(replicaId);
this.offLine = offLine;
this.regionName = RegionInfo.createRegionName(this.tableName, this.startKey, this.regionId,
this.replicaId, !this.tableName.equals(TableName.META_TABLE_NAME));
this.encodedName = RegionInfo.encodeRegionName(this.regionName);
this.hashCode = generateHashCode(this.tableName, this.startKey, this.endKey, this.regionId,
this.replicaId, this.offLine, this.regionName);
this.encodedNameAsBytes = Bytes.toBytes(this.encodedName);
}
/**
* @return Return a short, printable name for this region (usually encoded name) for us logging.
*/
@Override
public String getShortNameToLog() {
return RegionInfo.prettyPrint(this.getEncodedName());
}
/** @return the regionId */
@Override
public long getRegionId(){
return regionId;
}
/**
* @return the regionName as an array of bytes.
* @see #getRegionNameAsString()
*/
@Override
public byte[] getRegionName() {
return regionName;
}
/**
* @return Region name as a String for use in logging, etc.
*/
@Override
public String getRegionNameAsString() {
return RegionInfo.getRegionNameAsString(this, this.regionName);
}
/** @return the encoded region name */
@Override
public String getEncodedName() {
return this.encodedName;
}
@Override
public byte[] getEncodedNameAsBytes() {
return this.encodedNameAsBytes;
}
/** @return the startKey */
@Override
public byte[] getStartKey() {
return startKey;
}
/** @return the endKey */
@Override
public byte[] getEndKey() {
return endKey;
}
/**
* Get current table name of the region
* @return TableName
*/
@Override
public TableName getTable() {
return this.tableName;
}
/**
* Returns true if the given inclusive range of rows is fully contained
* by this region. For example, if the region is foo,a,g and this is
* passed ["b","c"] or ["a","c"] it will return true, but if this is passed
* ["b","z"] it will return false.
* @throws IllegalArgumentException if the range passed is invalid (ie. end < start)
*/
@Override
public boolean containsRange(byte[] rangeStartKey, byte[] rangeEndKey) {
CellComparator cellComparator = CellComparatorImpl.getCellComparator(tableName);
if (cellComparator.compareRows(rangeStartKey, rangeEndKey) > 0) {
throw new IllegalArgumentException(
"Invalid range: " + Bytes.toStringBinary(rangeStartKey) +
" > " + Bytes.toStringBinary(rangeEndKey));
}
boolean firstKeyInRange = cellComparator.compareRows(rangeStartKey, startKey) >= 0;
boolean lastKeyInRange =
cellComparator.compareRows(rangeEndKey, endKey) < 0 ||
Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY);
return firstKeyInRange && lastKeyInRange;
}
/**
* Return true if the given row falls in this region.
*/
@Override
public boolean containsRow(byte[] row) {
CellComparator cellComparator = CellComparatorImpl.getCellComparator(tableName);
return cellComparator.compareRows(row, startKey) >= 0 &&
(cellComparator.compareRows(row, endKey) < 0 ||
Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY));
}
/** @return true if this region is a meta region */
@Override
public boolean isMetaRegion() {
return tableName.equals(TableName.META_TABLE_NAME);
}
/**
* @return True if has been split and has daughters.
*/
@Override
public boolean isSplit() {
return this.split;
}
/**
* @param split set split status
* @return MutableRegionInfo
*/
public MutableRegionInfo setSplit(boolean split) {
this.split = split;
return this;
}
/**
* @return True if this region is offline.
* @deprecated since 3.0.0 and will be removed in 4.0.0
* @see <a href="https://issues.apache.org/jira/browse/HBASE-25210">HBASE-25210</a>
*/
@Override
@Deprecated
public boolean isOffline() {
return this.offLine;
}
/**
* The parent of a region split is offline while split daughters hold
* references to the parent. Offlined regions are closed.
* @param offLine Set online/offline status.
* @return MutableRegionInfo
*/
public MutableRegionInfo setOffline(boolean offLine) {
this.offLine = offLine;
return this;
}
/**
* @return True if this is a split parent region.
* @deprecated since 3.0.0 and will be removed in 4.0.0, Use {@link #isSplit()} instead.
* @see <a href="https://issues.apache.org/jira/browse/HBASE-25210">HBASE-25210</a>
*/
@Override
@Deprecated
public boolean isSplitParent() {
if (!isSplit()) {
return false;
}
if (!isOffline()) {
LOG.warn("Region is split but NOT offline: " + getRegionNameAsString());
}
return true;
}
/**
* Returns the region replica id
* @return returns region replica id
*/
@Override
public int getReplicaId() {
return replicaId;
}
/**
* @see Object#toString()
*/
@Override
public String toString() {
return "{ENCODED => " + getEncodedName() + ", " +
HConstants.NAME + " => '" + Bytes.toStringBinary(this.regionName)
+ "', STARTKEY => '" +
Bytes.toStringBinary(this.startKey) + "', ENDKEY => '" +
Bytes.toStringBinary(this.endKey) + "'" +
(isOffline()? ", OFFLINE => true": "") +
(isSplit()? ", SPLIT => true": "") +
((replicaId > 0)? ", REPLICA_ID => " + replicaId : "") + "}";
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (!(o instanceof RegionInfo)) {
return false;
}
return compareTo((RegionInfo)o) == 0;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
return this.hashCode;
}
}
| mahak/hbase | hbase-client/src/main/java/org/apache/hadoop/hbase/client/MutableRegionInfo.java | Java | apache-2.0 | 11,012 |
/*************************GO-LICENSE-START*********************************
* Copyright 2015 ThoughtWorks, Inc.
*
* 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.
*************************GO-LICENSE-END***********************************/
package com.thoughtworks.cruise.page;
import com.thoughtworks.cruise.state.ConfigState;
import com.thoughtworks.cruise.state.ScenarioState;
import com.thoughtworks.cruise.utils.Assertions;
import com.thoughtworks.cruise.utils.Assertions.Function;
import com.thoughtworks.cruise.utils.Timeout;
import net.sf.sahi.client.Browser;
import org.apache.commons.lang.StringUtils;
import org.junit.Assert;
import static junit.framework.Assert.assertEquals;
import static org.hamcrest.Matchers.containsString;
public abstract class CruiseAdminPage extends CruisePage{
public CruiseAdminPage(ScenarioState scenarioState, boolean alreadyOn, Browser browser) {
super(scenarioState, alreadyOn, browser);
}
public void assertMD5() throws Exception {
String md5value = scenarioState.getValueFromStore(ConfigState.md5key);
assertEquals(browser.hidden("config_md5").getValue(), md5value);
}
public void verifySuccessfulMergeMessageShowUp() throws Exception {
Assert.assertThat(message(), containsString("Saved configuration successfully. The configuration was modified by someone else, but your changes were merged successfully."));
}
protected String message() {
return Assertions.waitFor(Timeout.TWENTY_SECONDS, new Function<String>() {
public String call() {
String message = browser.byId("message_pane").getText().trim();
if (StringUtils.isBlank(message)) {
return null;
}
return message;
}
});
}
}
| jyotisingh/functional-tests | src/test/java/com/thoughtworks/cruise/page/CruiseAdminPage.java | Java | apache-2.0 | 2,207 |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp
Public Class LocalConflictTests
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(539939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539939")>
Public Sub ConflictingLocalWithLocal()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
int {|Conflict:y|} = 2;
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", type:=RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(539939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539939")>
Public Sub ConflictingLocalWithParameter()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] {|Conflict:args|})
{
int {|stmt1:$$x|} = 1;
}
}
</Document>
</Project>
</Workspace>, renameTo:="args")
result.AssertLabeledSpansAre("stmt1", "args", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithForEachRangeVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
foreach (var {|Conflict:y|} in args) { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithForLoopVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
for (int {|Conflict:y|} = 0; ; } { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithUsingBlockVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program : IDisposable
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
using (var {|Conflict:y|} = new Program()) { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithSimpleLambdaParameter()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
Func<int> lambda = {|Conflict:y|} => 42;
}
}
]]></Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingLocalWithParenthesizedLambdaParameter()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
class Program
{
static void Main(string[] args)
{
int {|stmt1:$$x|} = 1;
Func<int> lambda = ({|Conflict:y|}) => 42;
}
}
]]></Document>
</Project>
</Workspace>, renameTo:="y")
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingFromClauseWithLetClause()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C
{
static void Main(string[] args)
{
var temp = from [|$$x|] in "abc"
let {|DeclarationConflict:y|} = [|x|].ToString()
select {|Conflict:y|};
}
}
</Document>
</Project>
</Workspace>, renameTo:="y")
' We have two kinds of conflicts here: we flag a declaration conflict on the let:
result.AssertLabeledSpansAre("DeclarationConflict", type:=RelatedLocationType.UnresolvedConflict)
' And also for the y in the select clause. The compiler binds the "y" to the let
' clause's y.
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabelsInSameMethod()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
public class C
{
public void Foo()
{
{|stmt1:$$Bar|}:;
{|Conflict:Foo|}:;
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabelInMethodAndLambda()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
public class C
{
public void Foo()
{
{|stmt1:$$Bar|}: ;
Action x = () => { {|Conflict:Foo|}:;};
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictBetweenLabelsInLambda()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
public class C
{
Action x = () =>
{
{|Conflict:Foo|}:;
{|stmt1:$$Bar|}: ;
};
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Fact>
<WorkItem(543407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543407")>
<Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictBetweenLabelsInTwoNonNestedLambdas()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
public class C
{
public void Foo()
{
Action x = () => { Foo:; };
Action x = () => { {|stmt1:$$Bar|}:; };
}
}
</Document>
</Project>
</Workspace>, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(545468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545468")>
Public Sub NoConflictsWithCatchBlockWithoutExceptionVariable()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
try
{
int {|stmt1:$$i|};
}
catch (System.Exception)
{
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1081066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081066")>
Public Sub NoConflictsBetweenCatchClauses()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
static void Main()
{
try { } catch (Exception {|stmt1:$$ex|}) { }
try { } catch (Exception j) { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(1081066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081066")>
Public Sub ConflictsWithinCatchClause()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Test
{
static void Main()
{
try { } catch (Exception {|stmt1:$$ex|}) { int {|stmt2:j|}; }
try { } catch (Exception j) { }
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.UnresolvableConflict)
result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(546163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546163")>
Public Sub NoConflictsWithCatchExceptionWithoutDeclaration()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
try
{
int {|stmt1:$$i|};
}
catch
{
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(992721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992721")>
Public Sub ConflictingLocalWithFieldWithExtensionMethodInvolved()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
private List<object> {|def:_list|};
public Program(IEnumerable<object> list)
{
{|stmt2:_list|} = list.ToList();
foreach (var i in {|stmt1:$$_list|}.OfType<int>()){}
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="list")
result.AssertLabeledSpansAre("def", "list", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt1", "foreach (var i in this.list.OfType<int>()){}", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("stmt2", "this.list = list.ToList();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")>
Public Sub ConflictsBetweenSwitchCaseStatementsWithoutBlocks()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
switch (true)
{
case true:
object {|stmt1:$$i|} = null;
break;
case false:
object {|stmt2:j|} = null;
break;
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")>
Public Sub NoConflictsBetweenSwitchCaseStatementsWithBlocks()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
switch (true)
{
case true:
{
object {|stmt1:$$i|} = null;
break;
}
case false:
{
object j = null;
break;
}
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")>
Public Sub NoConflictsBetweenSwitchCaseStatementFirstStatementWithBlock()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
switch (true)
{
case true:
{
object {|stmt1:$$i|} = null;
break;
}
case false:
object {|stmt2:j|} = null;
break;
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(17177, "https://github.com/dotnet/roslyn/issues/17177")>
Public Sub NoConflictsBetweenSwitchCaseStatementSecondStatementWithBlock()
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Test
{
static void Main()
{
switch (true)
{
case true:
object {|stmt1:$$i|} = null;
break;
case false:
{
object {|stmt2:j|} = null;
break;
}
}
}
}
</Document>
</Project>
</Workspace>, renameTo:="j")
result.AssertLabeledSpansAre("stmt1", "j", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "j", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
End Class
End Namespace
| amcasey/roslyn | src/EditorFeatures/Test2/Rename/CSharp/LocalConflictTests.vb | Visual Basic | apache-2.0 | 20,257 |
/*
* Copyright 2014 gitblit.com.
*
* 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.
*/
package com.gitblit.tickets;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jgit.lib.Repository;
import com.gitblit.Constants;
import com.gitblit.manager.INotificationManager;
import com.gitblit.manager.IPluginManager;
import com.gitblit.manager.IRepositoryManager;
import com.gitblit.manager.IRuntimeManager;
import com.gitblit.manager.IUserManager;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.TicketModel;
import com.gitblit.models.TicketModel.Attachment;
import com.gitblit.models.TicketModel.Change;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.FileUtils;
import com.gitblit.utils.StringUtils;
/**
* Implementation of a ticket service based on a directory within the repository.
* All tickets are serialized as a list of JSON changes and persisted in a hashed
* directory structure, similar to the standard git loose object structure.
*
* @author James Moger
*
*/
public class FileTicketService extends ITicketService {
private static final String JOURNAL = "journal.json";
private static final String TICKETS_PATH = "tickets/";
private final Map<String, AtomicLong> lastAssignedId;
public FileTicketService(
IRuntimeManager runtimeManager,
IPluginManager pluginManager,
INotificationManager notificationManager,
IUserManager userManager,
IRepositoryManager repositoryManager) {
super(runtimeManager,
pluginManager,
notificationManager,
userManager,
repositoryManager);
lastAssignedId = new ConcurrentHashMap<String, AtomicLong>();
}
@Override
public FileTicketService start() {
return this;
}
@Override
protected void resetCachesImpl() {
lastAssignedId.clear();
}
@Override
protected void resetCachesImpl(RepositoryModel repository) {
if (lastAssignedId.containsKey(repository.name)) {
lastAssignedId.get(repository.name).set(0);
}
}
@Override
protected void close() {
}
/**
* Returns the ticket path. This follows the same scheme as Git's object
* store path where the first two characters of the hash id are the root
* folder with the remaining characters as a subfolder within that folder.
*
* @param ticketId
* @return the root path of the ticket content in the ticket directory
*/
private String toTicketPath(long ticketId) {
StringBuilder sb = new StringBuilder();
sb.append(TICKETS_PATH);
long m = ticketId % 100L;
if (m < 10) {
sb.append('0');
}
sb.append(m);
sb.append('/');
sb.append(ticketId);
return sb.toString();
}
/**
* Returns the path to the attachment for the specified ticket.
*
* @param ticketId
* @param filename
* @return the path to the specified attachment
*/
private String toAttachmentPath(long ticketId, String filename) {
return toTicketPath(ticketId) + "/attachments/" + filename;
}
/**
* Ensures that we have a ticket for this ticket id.
*
* @param repository
* @param ticketId
* @return true if the ticket exists
*/
@Override
public boolean hasTicket(RepositoryModel repository, long ticketId) {
boolean hasTicket = false;
Repository db = repositoryManager.getRepository(repository.name);
try {
String journalPath = toTicketPath(ticketId) + "/" + JOURNAL;
hasTicket = new File(db.getDirectory(), journalPath).exists();
} finally {
db.close();
}
return hasTicket;
}
/**
* Assigns a new ticket id.
*
* @param repository
* @return a new long id
*/
@Override
public synchronized long assignNewId(RepositoryModel repository) {
long newId = 0L;
Repository db = repositoryManager.getRepository(repository.name);
try {
if (!lastAssignedId.containsKey(repository.name)) {
lastAssignedId.put(repository.name, new AtomicLong(0));
}
AtomicLong lastId = lastAssignedId.get(repository.name);
if (lastId.get() <= 0) {
// identify current highest ticket id by scanning the paths in the tip tree
File dir = new File(db.getDirectory(), TICKETS_PATH);
dir.mkdirs();
List<File> journals = findAll(dir, JOURNAL);
for (File journal : journals) {
// Reconstruct ticketId from the path
// id/26/326/journal.json
String path = FileUtils.getRelativePath(dir, journal);
String tid = path.split("/")[1];
long ticketId = Long.parseLong(tid);
if (ticketId > lastId.get()) {
lastId.set(ticketId);
}
}
}
// assign the id and touch an empty journal to hold it's place
newId = lastId.incrementAndGet();
String journalPath = toTicketPath(newId) + "/" + JOURNAL;
File journal = new File(db.getDirectory(), journalPath);
journal.getParentFile().mkdirs();
journal.createNewFile();
} catch (IOException e) {
log.error("failed to assign ticket id", e);
return 0L;
} finally {
db.close();
}
return newId;
}
/**
* Returns all the tickets in the repository. Querying tickets from the
* repository requires deserializing all tickets. This is an expensive
* process and not recommended. Tickets are indexed by Lucene and queries
* should be executed against that index.
*
* @param repository
* @param filter
* optional filter to only return matching results
* @return a list of tickets
*/
@Override
public List<TicketModel> getTickets(RepositoryModel repository, TicketFilter filter) {
List<TicketModel> list = new ArrayList<TicketModel>();
Repository db = repositoryManager.getRepository(repository.name);
try {
// Collect the set of all json files
File dir = new File(db.getDirectory(), TICKETS_PATH);
List<File> journals = findAll(dir, JOURNAL);
// Deserialize each ticket and optionally filter out unwanted tickets
for (File journal : journals) {
String json = null;
try {
json = new String(FileUtils.readContent(journal), Constants.ENCODING);
} catch (Exception e) {
log.error(null, e);
}
if (StringUtils.isEmpty(json)) {
// journal was touched but no changes were written
continue;
}
try {
// Reconstruct ticketId from the path
// id/26/326/journal.json
String path = FileUtils.getRelativePath(dir, journal);
String tid = path.split("/")[1];
long ticketId = Long.parseLong(tid);
List<Change> changes = TicketSerializer.deserializeJournal(json);
if (ArrayUtils.isEmpty(changes)) {
log.warn("Empty journal for {}:{}", repository, journal);
continue;
}
TicketModel ticket = TicketModel.buildTicket(changes);
ticket.project = repository.projectPath;
ticket.repository = repository.name;
ticket.number = ticketId;
// add the ticket, conditionally, to the list
if (filter == null) {
list.add(ticket);
} else {
if (filter.accept(ticket)) {
list.add(ticket);
}
}
} catch (Exception e) {
log.error("failed to deserialize {}/{}\n{}",
new Object [] { repository, journal, e.getMessage()});
log.error(null, e);
}
}
// sort the tickets by creation
Collections.sort(list);
return list;
} finally {
db.close();
}
}
private List<File> findAll(File dir, String filename) {
List<File> list = new ArrayList<File>();
File [] files = dir.listFiles();
if (files == null) {
return list;
}
for (File file : files) {
if (file.isDirectory()) {
list.addAll(findAll(file, filename));
} else if (file.isFile()) {
if (file.getName().equalsIgnoreCase(filename)) {
list.add(file);
}
}
}
return list;
}
/**
* Retrieves the ticket from the repository by first looking-up the changeId
* associated with the ticketId.
*
* @param repository
* @param ticketId
* @return a ticket, if it exists, otherwise null
*/
@Override
protected TicketModel getTicketImpl(RepositoryModel repository, long ticketId) {
Repository db = repositoryManager.getRepository(repository.name);
try {
List<Change> changes = getJournal(db, ticketId);
if (ArrayUtils.isEmpty(changes)) {
log.warn("Empty journal for {}:{}", repository, ticketId);
return null;
}
TicketModel ticket = TicketModel.buildTicket(changes);
if (ticket != null) {
ticket.project = repository.projectPath;
ticket.repository = repository.name;
ticket.number = ticketId;
}
return ticket;
} finally {
db.close();
}
}
/**
* Returns the journal for the specified ticket.
*
* @param db
* @param ticketId
* @return a list of changes
*/
private List<Change> getJournal(Repository db, long ticketId) {
if (ticketId <= 0L) {
return new ArrayList<Change>();
}
String journalPath = toTicketPath(ticketId) + "/" + JOURNAL;
File journal = new File(db.getDirectory(), journalPath);
if (!journal.exists()) {
return new ArrayList<Change>();
}
String json = null;
try {
json = new String(FileUtils.readContent(journal), Constants.ENCODING);
} catch (Exception e) {
log.error(null, e);
}
if (StringUtils.isEmpty(json)) {
return new ArrayList<Change>();
}
List<Change> list = TicketSerializer.deserializeJournal(json);
return list;
}
@Override
public boolean supportsAttachments() {
return true;
}
/**
* Retrieves the specified attachment from a ticket.
*
* @param repository
* @param ticketId
* @param filename
* @return an attachment, if found, null otherwise
*/
@Override
public Attachment getAttachment(RepositoryModel repository, long ticketId, String filename) {
if (ticketId <= 0L) {
return null;
}
// deserialize the ticket model so that we have the attachment metadata
TicketModel ticket = getTicket(repository, ticketId);
Attachment attachment = ticket.getAttachment(filename);
// attachment not found
if (attachment == null) {
return null;
}
// retrieve the attachment content
Repository db = repositoryManager.getRepository(repository.name);
try {
String attachmentPath = toAttachmentPath(ticketId, attachment.name);
File file = new File(db.getDirectory(), attachmentPath);
if (file.exists()) {
attachment.content = FileUtils.readContent(file);
attachment.size = attachment.content.length;
}
return attachment;
} finally {
db.close();
}
}
/**
* Deletes a ticket from the repository.
*
* @param ticket
* @return true if successful
*/
@Override
protected synchronized boolean deleteTicketImpl(RepositoryModel repository, TicketModel ticket, String deletedBy) {
if (ticket == null) {
throw new RuntimeException("must specify a ticket!");
}
boolean success = false;
Repository db = repositoryManager.getRepository(ticket.repository);
try {
String ticketPath = toTicketPath(ticket.number);
File dir = new File(db.getDirectory(), ticketPath);
if (dir.exists()) {
success = FileUtils.delete(dir);
}
success = true;
} finally {
db.close();
}
return success;
}
/**
* Commit a ticket change to the repository.
*
* @param repository
* @param ticketId
* @param change
* @return true, if the change was committed
*/
@Override
protected synchronized boolean commitChangeImpl(RepositoryModel repository, long ticketId, Change change) {
boolean success = false;
Repository db = repositoryManager.getRepository(repository.name);
try {
List<Change> changes = getJournal(db, ticketId);
changes.add(change);
String journal = TicketSerializer.serializeJournal(changes).trim();
String journalPath = toTicketPath(ticketId) + "/" + JOURNAL;
File file = new File(db.getDirectory(), journalPath);
file.getParentFile().mkdirs();
FileUtils.writeContent(file, journal);
success = true;
} catch (Throwable t) {
log.error(MessageFormat.format("Failed to commit ticket {0,number,0} to {1}",
ticketId, db.getDirectory()), t);
} finally {
db.close();
}
return success;
}
@Override
protected boolean deleteAllImpl(RepositoryModel repository) {
Repository db = repositoryManager.getRepository(repository.name);
try {
File dir = new File(db.getDirectory(), TICKETS_PATH);
return FileUtils.delete(dir);
} catch (Exception e) {
log.error(null, e);
} finally {
db.close();
}
return false;
}
@Override
protected boolean renameImpl(RepositoryModel oldRepository, RepositoryModel newRepository) {
return true;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| wellington-junio/gitblit | src/main/java/com/gitblit/tickets/FileTicketService.java | Java | apache-2.0 | 13,151 |
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.web.analytics.formatting;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.opengamma.analytics.financial.model.volatility.smile.fitting.sabr.SmileSurfaceDataBundle;
import com.opengamma.analytics.financial.model.volatility.surface.BlackVolatilitySurfaceMoneynessFcnBackedByGrid;
import com.opengamma.engine.value.ValueSpecification;
/* package */ class BlackVolatilitySurfaceMoneynessFcnBackedByGridFormatter
extends AbstractFormatter<BlackVolatilitySurfaceMoneynessFcnBackedByGrid> {
/* package */ BlackVolatilitySurfaceMoneynessFcnBackedByGridFormatter() {
super(BlackVolatilitySurfaceMoneynessFcnBackedByGrid.class);
addFormatter(new Formatter<BlackVolatilitySurfaceMoneynessFcnBackedByGrid>(Format.EXPANDED) {
@Override
Object format(BlackVolatilitySurfaceMoneynessFcnBackedByGrid value,
ValueSpecification valueSpec,
Object inlineKey) {
return formatExpanded(value);
}
});
}
@Override
public Object formatCell(BlackVolatilitySurfaceMoneynessFcnBackedByGrid value,
ValueSpecification valueSpec,
Object inlineKey) {
return SurfaceFormatterUtils.formatCell(value.getSurface());
}
private Object formatExpanded(BlackVolatilitySurfaceMoneynessFcnBackedByGrid value) {
SmileSurfaceDataBundle gridData = value.getGridData();
Set<Double> strikes = new TreeSet<Double>();
for (double[] outer : gridData.getStrikes()) {
for (double inner : outer) {
strikes.add(inner);
}
}
List<Double> vol = Lists.newArrayList();
// x values (outer loop of vol) strikes
// y values (inner loop of vol) expiries
List<Double> expiries = Lists.newArrayListWithCapacity(gridData.getExpiries().length);
for (double expiry : gridData.getExpiries()) {
expiries.add(expiry);
}
for (Double strike : strikes) {
for (Double expiry : expiries) {
vol.add(value.getVolatility(expiry, strike));
}
}
Map<String, Object> results = Maps.newHashMap();
results.put(SurfaceFormatterUtils.X_VALUES, expiries);
results.put(SurfaceFormatterUtils.X_LABELS, SurfaceFormatterUtils.getAxisLabels(expiries));
results.put(SurfaceFormatterUtils.X_TITLE, "Time to Expiry");
results.put(SurfaceFormatterUtils.Y_VALUES, strikes);
results.put(SurfaceFormatterUtils.Y_LABELS, SurfaceFormatterUtils.getAxisLabels(strikes));
results.put(SurfaceFormatterUtils.Y_TITLE, "Strike");
results.put(SurfaceFormatterUtils.VOL, vol);
return results;
}
@Override
public DataType getDataType() {
return DataType.SURFACE_DATA;
}
}
| DevStreet/FinanceAnalytics | projects/OG-Web/src/main/java/com/opengamma/web/analytics/formatting/BlackVolatilitySurfaceMoneynessFcnBackedByGridFormatter.java | Java | apache-2.0 | 2,954 |
/*
* Copyright 2008 biaoping.yin
*
* 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" bboss persistent,
* 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.
*/
package com.frameworkset.common.poolman.management;
import java.io.Serializable;
import java.net.URL;
import java.net.URLClassLoader;
/**
* Encountered Class linkage problems in somce ClassLoaders --
* such as the one used with the Swing and AWT views of JUnit (JUnit's
* text-based view was fine, since it doesn't use the same CL) and
* some versions of Tomcat -- that are compounded by extraneous
* loader context switching in the JMX RI. This ClassLoader does
* nothing other than insist that MBeans are loaded by a specific
* loader in order to avoid linkage problems between contexts.
*/
public class JMXClassLoader extends URLClassLoader implements JMXClassLoaderMBean , Serializable{
private ClassLoader parent;
public JMXClassLoader(ClassLoader parent) {
super(new URL[0], parent);
this.parent = parent;
}
public Class loadClass(String name) throws ClassNotFoundException {
return parent.loadClass(name);
}
}
| besom/bbossgroups-mvn | bboss_persistent/src/main/java/com/frameworkset/common/poolman/management/JMXClassLoader.java | Java | apache-2.0 | 1,595 |
import Ember from 'ember';
export function addAction(action, selector) {
return function() {
if ( Ember.Component.detectInstance(this) )
{
this._super();
}
else
{
this.get('controller').send(action);
}
Ember.run.next(this, function() {
var matches = this.$(selector);
if ( matches )
{
var last = matches.last();
if ( last )
{
last.focus();
}
}
});
};
}
| nrvale0/ui | app/utils/add-view-action.js | JavaScript | apache-2.0 | 469 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.ComponentModel;
namespace Azure.ResourceManager.Sql.Models
{
/// <summary> The LongTermRetentionDatabaseState. </summary>
public readonly partial struct LongTermRetentionDatabaseState : IEquatable<LongTermRetentionDatabaseState>
{
private readonly string _value;
/// <summary> Determines if two <see cref="LongTermRetentionDatabaseState"/> values are the same. </summary>
/// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
public LongTermRetentionDatabaseState(string value)
{
_value = value ?? throw new ArgumentNullException(nameof(value));
}
private const string AllValue = "All";
private const string LiveValue = "Live";
private const string DeletedValue = "Deleted";
/// <summary> All. </summary>
public static LongTermRetentionDatabaseState All { get; } = new LongTermRetentionDatabaseState(AllValue);
/// <summary> Live. </summary>
public static LongTermRetentionDatabaseState Live { get; } = new LongTermRetentionDatabaseState(LiveValue);
/// <summary> Deleted. </summary>
public static LongTermRetentionDatabaseState Deleted { get; } = new LongTermRetentionDatabaseState(DeletedValue);
/// <summary> Determines if two <see cref="LongTermRetentionDatabaseState"/> values are the same. </summary>
public static bool operator ==(LongTermRetentionDatabaseState left, LongTermRetentionDatabaseState right) => left.Equals(right);
/// <summary> Determines if two <see cref="LongTermRetentionDatabaseState"/> values are not the same. </summary>
public static bool operator !=(LongTermRetentionDatabaseState left, LongTermRetentionDatabaseState right) => !left.Equals(right);
/// <summary> Converts a string to a <see cref="LongTermRetentionDatabaseState"/>. </summary>
public static implicit operator LongTermRetentionDatabaseState(string value) => new LongTermRetentionDatabaseState(value);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => obj is LongTermRetentionDatabaseState other && Equals(other);
/// <inheritdoc />
public bool Equals(LongTermRetentionDatabaseState other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);
/// <inheritdoc />
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => _value?.GetHashCode() ?? 0;
/// <inheritdoc />
public override string ToString() => _value;
}
}
| yugangw-msft/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/LongTermRetentionDatabaseState.cs | C# | apache-2.0 | 2,810 |
/* ----------------------------------------------------------------------- *//**
*
* @file SymmetricPositiveDefiniteEigenDecomposition_impl.hpp
*
*//* ----------------------------------------------------------------------- */
#ifndef MADLIB_DBAL_EIGEN_INTEGRATION_SPDEIGENDECOMPOSITION_IMPL_HPP
#define MADLIB_DBAL_EIGEN_INTEGRATION_SPDEIGENDECOMPOSITION_IMPL_HPP
namespace madlib {
namespace dbal {
namespace eigen_integration {
/**
* @brief Constructor that invokes the computation
*
* @param inMatrix Matrix to operate on. Note that the type is
* <tt>const MatrixType&</tt>, meaning that a temporary object will be
* created if the actual parameter is not of a subclass type. This means
* that memory will be copied -- on the positive side, this ensures memory
* will be aligned!
* @param inOptions A combination of DecompositionOptions
* @param inExtras A combination of SPDDecompositionExtras
*/
template <class MatrixType>
inline
SymmetricPositiveDefiniteEigenDecomposition<MatrixType>
::SymmetricPositiveDefiniteEigenDecomposition(
const MatrixType &inMatrix, int inOptions, int inExtras)
: Base(inMatrix, inOptions) {
computeExtras(inMatrix, inExtras);
}
/**
* @brief Return the condition number of the matrix
*
* In general, the condition number of a matrix is the absolute value of the
* largest singular value divided by the smallest singular value. When a matrix
* is symmetric positive semi-definite, all eigenvalues are also singular
* values. Moreover, all eigenvalues are non-negative.
*/
template <class MatrixType>
inline
double
SymmetricPositiveDefiniteEigenDecomposition<MatrixType>::conditionNo()
const {
const RealVectorType& ev = eigenvalues();
double numerator = ev(ev.size() - 1);
double denominator = ev(0);
// All eigenvalues of a positive semi-definite matrix are
// non-negative, so in theory no need to take absolute values.
// Unfortunately, numerical instabilities can cause eigenvalues to
// be slightly negative. We should interprete that as 0.
if (denominator < 0)
denominator = 0;
return numerator <= 0 ? std::numeric_limits<double>::infinity()
: numerator / denominator;
}
/**
* @brief Return the pseudo inverse previously computed using computeExtras().
*
* The result of this function is undefined if computeExtras() has not been
* called or the pseudo-inverse was not set to be computed.
*/
template <class MatrixType>
inline
const MatrixType&
SymmetricPositiveDefiniteEigenDecomposition<MatrixType>::pseudoInverse() const {
return mPinv;
}
/**
* @brief Perform extra computations after the decomposition
*
* If the matrix has a condition number of less than 1e20 (currently
* this is hard-coded), it necessarily has full rank and is invertible.
* The Moore-Penrose pseudo-inverse coincides with the inverse and we
* compute it directly, using a \f$ L D L^T \f$ Cholesky decomposition.
*
* If the matrix has a condition number of more than 1e20, we are on the
* safe side and use the eigen decomposition for computing the
* pseudo-inverse.
*
* Since the eigenvectors of a symmtric positive semi-definite matrix
* are orthogonal, and Eigen moreover scales them to have norm 1 (i.e.,
* the eigenvectors returned by Eigen are orthonormal), the Eigen
* decomposition
*
* \f$ M = V * D * V^T \f$
*
* is also a singular value decomposition (where M is the
* original symmetric positive semi-definite matrix, D is the
* diagonal matrix with eigenvectors, and V is the unitary
* matrix containing normalized eigenvectors). In particular,
* V is unitary, so the inverse can be computed as
*
* \f$ M^{-1} = V * D^{-1} * V^T \f$.
*
* Only the <b>lower triangular part</b> of the input matrix
* is referenced.
*/
template <class MatrixType>
inline
void
SymmetricPositiveDefiniteEigenDecomposition<MatrixType>::computeExtras(
const MatrixType &inMatrix, int inExtras) {
if (inExtras & ComputePseudoInverse) {
mPinv.resize(inMatrix.rows(), inMatrix.cols());
// FIXME: No hard-coded constant here
if (conditionNo() < 1e20) {
// We are doing a Cholesky decomposition of a matrix with
// pivoting. This is faster than the PartialPivLU that
// Eigen's inverse() method would use
mPinv = inMatrix.template selfadjointView<Eigen::Lower>().ldlt()
.solve(MatrixType::Identity(inMatrix.rows(), inMatrix.cols()));
} else {
if (!Base::m_eigenvectorsOk)
Base::compute(inMatrix, Eigen::ComputeEigenvectors);
const RealVectorType& ev = eigenvalues();
// The eigenvalue are sorted in increasing order
Scalar epsilon = static_cast<double>(inMatrix.rows())
* ev(ev.size() - 1)
* std::numeric_limits<Scalar>::epsilon();
RealVectorType eigenvectorsInverted(ev.size());
for (Index i = 0; i < static_cast<Index>(ev.size()); ++i) {
eigenvectorsInverted(i) = ev(i) < epsilon
? Scalar(0)
: Scalar(1) / ev(i);
}
mPinv = Base::eigenvectors()
* eigenvectorsInverted.asDiagonal()
* Base::eigenvectors().transpose();
}
}
}
} // namespace eigen_integration
} // namespace dbal
} // namespace madlib
#endif // defined(MADLIB_DBAL_EIGEN_INTEGRATION_SPDEIGENDECOMPOSITION_IMPL_HPP)
| lmatthieu/incubator-madlib | src/dbal/EigenIntegration/SymmetricPositiveDefiniteEigenDecomposition_impl.hpp | C++ | apache-2.0 | 5,582 |
/*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.
*/
package org.kie.remote.services.ws.sei.process;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
import org.kie.remote.services.ws.common.KieRemoteWebServiceException;
import org.kie.remote.services.ws.sei.ServicesVersion;
/**
* Only used for initial WSDL generation
*/
@WebService(name = "ProcessService", targetNamespace = ProcessWebService.NAMESPACE)
public interface ProcessWebService {
static final String NAMESPACE = "http://services.remote.kie.org/" + ServicesVersion.VERSION + "/process";
@WebMethod(action = "urn:ManageProcess")
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "manageProcess", targetNamespace = ProcessWebService.NAMESPACE, className = "org.kie.remote.services.ws.wsdl.generated.WrapperManageProcessInstanceRequest")
@ResponseWrapper(localName = "manageProcessResponse", targetNamespace = ProcessWebService.NAMESPACE, className = "org.kie.remote.services.ws.wsdl.generated.WrapperProcessInstanceResponse")
public ProcessInstanceResponse manageProcess(@WebParam(name = "request", targetNamespace = "") ManageProcessInstanceRequest processInstanceRequest) throws KieRemoteWebServiceException;
@WebMethod(action = "urn:ManageWorkItem")
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "manageWorkItem", targetNamespace = ProcessWebService.NAMESPACE, className = "org.kie.remote.services.ws.wsdl.generated.WrapperManageWorkItem")
@ResponseWrapper(localName = "manageWorkItemResponse", targetNamespace = ProcessWebService.NAMESPACE, className = "org.kie.remote.services.ws.wsdl.generated.WrapperVoidResponse")
public void manageWorkItem(@WebParam(name = "request", targetNamespace = "") ManageWorkItemRequest workItemRequest) throws KieRemoteWebServiceException;
@WebMethod(action = "urn:QueryProcess")
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "queryProcess", targetNamespace = ProcessWebService.NAMESPACE, className = "org.kie.remote.services.ws.wsdl.generated.WrapperQueryProcessRequest")
@ResponseWrapper(localName = "queryProcessResponse", targetNamespace = ProcessWebService.NAMESPACE, className = "org.kie.remote.services.ws.wsdl.generated.WrapperProcessInstanceResponse")
public Jaxb query(@WebParam(name = "request", targetNamespace = "") QueryProcessRequest processQueryRequest) throws KieRemoteWebServiceException;
}
| BeatCoding/droolsjbpm-integration | kie-remote/kie-remote-ws/kie-remote-ws-gen-wsdl/src/main/java/org/kie/remote/services/ws/sei/process/ProcessWebService.java | Java | apache-2.0 | 3,060 |
/** @file
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 "HttpHeader.h"
#include "slice.h"
#include <cinttypes>
#include <cstdlib>
#include <cstring>
TSHttpType
HttpHeader::type() const
{
if (isValid()) {
return TSHttpHdrTypeGet(m_buffer, m_lochdr);
} else {
return TS_HTTP_TYPE_UNKNOWN;
}
}
TSHttpStatus
HttpHeader::status() const
{
TSHttpStatus res = TS_HTTP_STATUS_NONE;
if (isValid()) {
res = TSHttpHdrStatusGet(m_buffer, m_lochdr);
}
return res;
}
bool
HttpHeader::setStatus(TSHttpStatus const newstatus)
{
if (!isValid()) {
return false;
}
return TS_SUCCESS == TSHttpHdrStatusSet(m_buffer, m_lochdr, newstatus);
}
char *
HttpHeader::urlString(int *const urllen) const
{
char *urlstr = nullptr;
TSAssert(nullptr != urllen);
TSMLoc locurl = nullptr;
TSReturnCode const rcode = TSHttpHdrUrlGet(m_buffer, m_lochdr, &locurl);
if (nullptr != locurl) {
if (TS_SUCCESS == rcode) {
urlstr = TSUrlStringGet(m_buffer, locurl, urllen);
} else {
*urllen = 0;
}
TSHandleMLocRelease(m_buffer, m_lochdr, locurl);
}
return urlstr;
}
bool
HttpHeader::setUrl(TSMBuffer const bufurl, TSMLoc const locurl)
{
if (!isValid()) {
return false;
}
TSMLoc locurlout = nullptr;
TSReturnCode rcode = TSHttpHdrUrlGet(m_buffer, m_lochdr, &locurlout);
if (TS_SUCCESS != rcode) {
return false;
}
// copy the url
rcode = TSUrlCopy(m_buffer, locurlout, bufurl, locurl);
// set url active
if (TS_SUCCESS == rcode) {
rcode = TSHttpHdrUrlSet(m_buffer, m_lochdr, locurlout);
}
TSHandleMLocRelease(m_buffer, m_lochdr, locurlout);
return TS_SUCCESS == rcode;
}
bool
HttpHeader::setReason(char const *const valstr, int const vallen)
{
if (isValid()) {
return TS_SUCCESS == TSHttpHdrReasonSet(m_buffer, m_lochdr, valstr, vallen);
} else {
return false;
}
}
char const *
HttpHeader::getCharPtr(CharPtrGetFunc func, int *const len) const
{
char const *res = nullptr;
if (isValid()) {
int reslen = 0;
res = func(m_buffer, m_lochdr, &reslen);
if (nullptr != len) {
*len = reslen;
}
}
if (nullptr == res && nullptr != len) {
*len = 0;
}
return res;
}
bool
HttpHeader::hasKey(char const *const key, int const keylen) const
{
if (!isValid()) {
return false;
}
TSMLoc const locfield(TSMimeHdrFieldFind(m_buffer, m_lochdr, key, keylen));
if (nullptr != locfield) {
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
return true;
}
return false;
}
bool
HttpHeader::removeKey(char const *const keystr, int const keylen)
{
if (!isValid()) {
return false;
}
bool status = true;
TSMLoc const locfield = TSMimeHdrFieldFind(m_buffer, m_lochdr, keystr, keylen);
if (nullptr != locfield) {
int const rcode = TSMimeHdrFieldRemove(m_buffer, m_lochdr, locfield);
status = (TS_SUCCESS == rcode);
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
}
return status;
}
bool
HttpHeader::valueForKey(char const *const keystr, int const keylen, char *const valstr, int *const vallen, int const index) const
{
if (!isValid()) {
*vallen = 0;
return false;
}
bool status = false;
TSMLoc const locfield = TSMimeHdrFieldFind(m_buffer, m_lochdr, keystr, keylen);
if (nullptr != locfield) {
int getlen = 0;
char const *const getstr = TSMimeHdrFieldValueStringGet(m_buffer, m_lochdr, locfield, index, &getlen);
int const valcap = *vallen;
if (nullptr != getstr && 0 < getlen && getlen < (valcap - 1)) {
char *const endp = stpncpy(valstr, getstr, getlen);
*vallen = endp - valstr;
status = (*vallen < valcap);
if (status) {
*endp = '\0';
}
}
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
} else {
*vallen = 0;
}
return status;
}
bool
HttpHeader::setKeyVal(char const *const keystr, int const keylen, char const *const valstr, int const vallen, int const index)
{
if (!isValid()) {
return false;
}
bool status(false);
TSMLoc locfield(TSMimeHdrFieldFind(m_buffer, m_lochdr, keystr, keylen));
if (nullptr != locfield) {
status = TS_SUCCESS == TSMimeHdrFieldValueStringSet(m_buffer, m_lochdr, locfield, index, valstr, vallen);
} else {
int rcode = TSMimeHdrFieldCreateNamed(m_buffer, m_lochdr, keystr, keylen, &locfield);
if (TS_SUCCESS == rcode) {
rcode = TSMimeHdrFieldValueStringSet(m_buffer, m_lochdr, locfield, index, valstr, vallen);
if (TS_SUCCESS == rcode) {
rcode = TSMimeHdrFieldAppend(m_buffer, m_lochdr, locfield);
status = (TS_SUCCESS == rcode);
}
}
}
if (nullptr != locfield) {
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
}
return status;
}
bool
HttpHeader::timeForKey(char const *const keystr, int const keylen, time_t *const timeval) const
{
TSAssert(nullptr != timeval);
if (!isValid()) {
*timeval = 0;
return false;
}
bool status = false;
TSMLoc const locfield = TSMimeHdrFieldFind(m_buffer, m_lochdr, keystr, keylen);
if (nullptr != locfield) {
*timeval = TSMimeHdrFieldValueDateGet(m_buffer, m_lochdr, locfield);
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
} else {
*timeval = 0;
}
return status;
}
bool
HttpHeader::setKeyTime(char const *const keystr, int const keylen, time_t const timeval)
{
if (!isValid()) {
return false;
}
bool status(false);
TSMLoc locfield(TSMimeHdrFieldFind(m_buffer, m_lochdr, keystr, keylen));
if (nullptr == locfield) {
DEBUG_LOG("Creating header %.*s", keylen, keystr);
TSMimeHdrFieldCreateNamed(m_buffer, m_lochdr, keystr, keylen, &locfield);
}
if (nullptr != locfield) {
if (TS_SUCCESS == TSMimeHdrFieldValueDateSet(m_buffer, m_lochdr, locfield, timeval)) {
if (TS_SUCCESS == TSMimeHdrFieldAppend(m_buffer, m_lochdr, locfield)) {
status = true;
DEBUG_LOG("Set header %.*s to %jd", keylen, keystr, static_cast<intmax_t>(timeval));
}
}
TSHandleMLocRelease(m_buffer, m_lochdr, locfield);
}
return status;
}
std::string
HttpHeader::toString() const
{
std::string res;
if (isValid()) {
TSIOBuffer const iobufp = TSIOBufferCreate();
TSHttpHdrPrint(m_buffer, m_lochdr, iobufp);
TSIOBufferReader const reader = TSIOBufferReaderAlloc(iobufp);
if (nullptr != reader) {
TSIOBufferBlock block = TSIOBufferReaderStart(reader);
bool done = false;
while (!done && nullptr != block) {
int64_t avail = 0;
char const *blockptr = TSIOBufferBlockReadStart(block, reader, &avail);
if (0 < avail) {
res.append(blockptr, avail);
}
block = TSIOBufferBlockNext(block);
}
TSIOBufferReaderFree(reader);
}
TSIOBufferDestroy(iobufp);
}
if (res.empty()) {
res = "<null>";
}
return res;
}
/////// HdrMgr
TSParseResult
HdrMgr::populateFrom(TSHttpParser const http_parser, TSIOBufferReader const reader, HeaderParseFunc const parsefunc,
int64_t *const bytes)
{
TSParseResult parse_res = TS_PARSE_CONT;
if (nullptr == m_buffer) {
m_buffer = TSMBufferCreate();
}
if (nullptr == m_lochdr) {
m_lochdr = TSHttpHdrCreate(m_buffer);
}
int64_t avail = TSIOBufferReaderAvail(reader);
if (0 < avail) {
TSIOBufferBlock block = TSIOBufferReaderStart(reader);
int64_t consumed = 0;
parse_res = TS_PARSE_CONT;
while (nullptr != block && 0 < avail) {
int64_t blockbytes = 0;
char const *const bstart = TSIOBufferBlockReadStart(block, reader, &blockbytes);
char const *ptr = bstart;
char const *endptr = ptr + blockbytes;
parse_res = parsefunc(http_parser, m_buffer, m_lochdr, &ptr, endptr);
int64_t const bytes_parsed(ptr - bstart);
consumed += bytes_parsed;
avail -= bytes_parsed;
if (TS_PARSE_CONT == parse_res) {
block = TSIOBufferBlockNext(block);
} else {
break;
}
}
TSIOBufferReaderConsume(reader, consumed);
if (nullptr != bytes) {
*bytes = consumed;
}
} else if (nullptr != bytes) {
*bytes = 0;
}
return parse_res;
}
| duke8253/trafficserver | plugins/experimental/slice/HttpHeader.cc | C++ | apache-2.0 | 8,961 |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics.CodeAnalysis
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Describes anonymous type/delegate in terms of fields/parameters
''' </summary>
Friend Structure AnonymousTypeDescriptor
Implements IEquatable(Of AnonymousTypeDescriptor)
Public Shared ReadOnly SubReturnParameterName As String = "Sub"
Public Shared ReadOnly FunctionReturnParameterName As String = "Function"
Friend Shared Function GetReturnParameterName(isFunction As Boolean) As String
Return If(isFunction, FunctionReturnParameterName, SubReturnParameterName)
End Function
''' <summary> Anonymous type/delegate location </summary>
Public ReadOnly Location As Location
''' <summary> Anonymous type fields </summary>
Public ReadOnly Fields As ImmutableArray(Of AnonymousTypeField)
''' <summary>
''' Anonymous type descriptor Key
'''
''' The key is being used to separate anonymous type templates, for example in an anonymous type
''' symbol cache. The type descriptors with the same keys are supposed to map to 'the same' anonymous
''' type template in terms of the same generic type being used for their implementation.
''' </summary>
Public ReadOnly Key As String
''' <summary> Anonymous type is implicitly declared </summary>
Public ReadOnly IsImplicitlyDeclared As Boolean
''' <summary> Anonymous delegate parameters, including one for return type </summary>
Public ReadOnly Property Parameters As ImmutableArray(Of AnonymousTypeField)
Get
Return Fields
End Get
End Property
Public Sub New(fields As ImmutableArray(Of AnonymousTypeField), _location As Location, _isImplicitlyDeclared As Boolean)
Me.Fields = fields
Me.Location = _location
Me.IsImplicitlyDeclared = _isImplicitlyDeclared
Me.Key = ComputeKey(fields, Function(f) f.Name, Function(f) f.IsKey)
End Sub
Friend Shared Function ComputeKey(Of T)(fields As ImmutableArray(Of T), getName As Func(Of T, String), getIsKey As Func(Of T, Boolean)) As String
Dim pooledBuilder = PooledStringBuilder.GetInstance()
Dim builder = pooledBuilder.Builder
For Each field In fields
builder.Append("|"c)
builder.Append(getName(field))
builder.Append(If(getIsKey(field), "+"c, "-"c))
Next
IdentifierComparison.ToLower(builder)
Return pooledBuilder.ToStringAndFree()
End Function
''' <summary>
''' This is ONLY used for debugging purpose
''' </summary>
<Conditional("DEBUG")>
Friend Sub AssertGood()
' Fields exist
Debug.Assert(Not Fields.IsEmpty)
' All fields are good
For Each field In Fields
field.AssertGood()
Next
End Sub
Public Overloads Function Equals(other As AnonymousTypeDescriptor) As Boolean Implements IEquatable(Of AnonymousTypeDescriptor).Equals
' Comparing keys ensures field count, field names and keyness are equal
If Not Me.Key.Equals(other.Key) Then
Return False
End If
' Compare field types
Dim myFields As ImmutableArray(Of AnonymousTypeField) = Me.Fields
Dim count As Integer = myFields.Length
Dim otherFields As ImmutableArray(Of AnonymousTypeField) = other.Fields
For i = 0 To count - 1
If Not myFields(i).Type.Equals(otherFields(i).Type) Then
Return False
End If
Next
Return True
End Function
Public Overloads Overrides Function Equals(obj As Object) As Boolean
Return TypeOf obj Is AnonymousTypeDescriptor AndAlso Equals(DirectCast(obj, AnonymousTypeDescriptor))
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.Key.GetHashCode()
End Function
''' <summary>
''' Performs internal substitution of types in anonymous type descriptor fields and returns True
''' if any of the fields was changed, in which case a new descriptor is returned in newDescriptor
''' </summary>
Public Function SubstituteTypeParametersIfNeeded(substitution As TypeSubstitution, <Out> ByRef newDescriptor As AnonymousTypeDescriptor) As Boolean
Dim fieldCount = Me.Fields.Length
Dim newFields(fieldCount - 1) As AnonymousTypeField
Dim anyChange As Boolean = False
For i = 0 To fieldCount - 1
Dim current As AnonymousTypeField = Me.Fields(i)
newFields(i) = New AnonymousTypeField(current.Name,
current.Type.InternalSubstituteTypeParameters(substitution),
current.Location,
current.IsKey)
If Not anyChange Then
anyChange = current.Type IsNot newFields(i).Type
End If
Next
If anyChange Then
newDescriptor = New AnonymousTypeDescriptor(newFields.AsImmutableOrNull(), Me.Location, Me.IsImplicitlyDeclared)
Else
newDescriptor = Nothing
End If
Return anyChange
End Function
End Structure
''' <summary>
''' Describes anonymous type field in terms of its name, type and other attributes.
''' Or describes anonymous delegate parameter, including "return" parameter, in terms
''' of its name, type and other attributes.
''' </summary>
Friend Structure AnonymousTypeField
''' <summary> Anonymous type field/parameter name, not nothing and not empty </summary>
Public ReadOnly Name As String
''' <summary>Location of the field</summary>
Public ReadOnly Location As Location
''' <summary> Anonymous type field/parameter type, must be not nothing when
''' the field is passed to anonymous type descriptor </summary>
Public ReadOnly Property Type As TypeSymbol
Get
Return Me._type
End Get
End Property
''' <summary>
''' Anonymous type field/parameter type, may be nothing when field descriptor is created,
''' must be assigned before passing the descriptor to anonymous type descriptor.
''' Once assigned, is considered to be 'sealed'.
''' </summary>
Private _type As TypeSymbol
''' <summary> Anonymous type field is declared as a 'Key' field </summary>
Public ReadOnly IsKey As Boolean
''' <summary>
''' Does this describe a ByRef parameter of an Anonymous Delegate type
''' </summary>
Public ReadOnly Property IsByRef As Boolean
Get
Return IsKey
End Get
End Property
Public Sub New(name As String, type As TypeSymbol, location As Location, Optional isKeyOrByRef As Boolean = False)
Me.Name = If(String.IsNullOrWhiteSpace(name), "<Empty Name>", name)
Me._type = type
Me.IsKey = isKeyOrByRef
Me.Location = location
End Sub
Public Sub New(name As String, location As Location, Optional isKey As Boolean = False)
Me.New(name, Nothing, location, isKey)
End Sub
''' <summary>
''' This is ONLY used for debugging purpose
''' </summary>
<Conditional("DEBUG")>
Friend Sub AssertGood()
Debug.Assert(Name IsNot Nothing AndAlso Me.Type IsNot Nothing AndAlso Me.Location IsNot Nothing)
End Sub
Friend Sub AssignFieldType(newType As TypeSymbol)
Debug.Assert(newType IsNot Nothing)
Debug.Assert(Me._type Is Nothing)
Me._type = newType
End Sub
End Structure
End Namespace
| DavidKarlas/roslyn | src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/AnonymousTypeDescriptor.vb | Visual Basic | apache-2.0 | 8,557 |
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Entitlement, GrantReason} from '../entitlement';
import {PlatformStore} from '../platform-store';
import {SubscriptionPlatform} from '../subscription-platform';
import {user} from '../../../../src/log';
describes.realWin('Platform store', {}, () => {
let platformStore;
const serviceIds = ['service1', 'service2'];
const entitlementsForService1 = new Entitlement({source: serviceIds[0],
raw: '', service: serviceIds[0], granted: true});
const entitlementsForService2 = new Entitlement({source: serviceIds[1],
raw: '', service: serviceIds[1], granted: false});
const fallbackEntitlement = new Entitlement({
source: 'local',
raw: 'raw',
service: 'local',
granted: true,
grantReason: GrantReason.SUBSCRIBER,
});
/**
* fake handler for getSupportedScoreFactor
* @param {string} factor
* @param {!Object} factorMap
* @return {number}
*/
function fakeGetSupportedScoreFactor(factor, factorMap) {
return factorMap[factor] || 0;
}
beforeEach(() => {
platformStore = new PlatformStore(serviceIds, {
supportsViewer: 9,
testFactor1: 10,
testFactor2: 10,
}, fallbackEntitlement);
});
it('should instantiate with the service ids', () => {
expect(platformStore.serviceIds_).to.be.equal(serviceIds);
});
it('should resolve entitlement', () => {
// Request entitlement promise even before it's resolved.
const p = platformStore.getEntitlementPromiseFor('service2');
// Resolve once.
const ent = new Entitlement({
service: 'service2',
granted: false,
});
platformStore.resolveEntitlement('service2', ent);
expect(platformStore.getResolvedEntitlementFor('service2')).to.equal(ent);
expect(platformStore.getEntitlementPromiseFor('service2')).to.equal(p);
// Additional resolution doesn't change anything without reset.
platformStore.resolveEntitlement('service2', new Entitlement({
service: 'service2',
granted: true,
}));
expect(platformStore.getEntitlementPromiseFor('service2')).to.equal(p);
return expect(p).to.eventually.equal(ent);
});
it('should call onChange callbacks on every resolve', () => {
const cb = sandbox.stub(platformStore.onEntitlementResolvedCallbacks_,
'fire');
platformStore.onChange(cb);
platformStore.resolveEntitlement('service2',
new Entitlement({
service: 'service2',
granted: false,
})
);
expect(cb).to.be.calledOnce;
});
describe('getGrantStatus', () => {
it('should resolve true on recieving a positive entitlement', done => {
platformStore.getGrantStatus()
.then(entitlements => {
if (entitlements === true) {
done();
} else {
throw new Error('Incorrect entitlement resolved');
}
});
platformStore.resolveEntitlement(serviceIds[1],
entitlementsForService2);
platformStore.resolveEntitlement(serviceIds[0],
entitlementsForService1);
});
it('should resolve true for existing positive entitlement', done => {
platformStore.entitlements_[serviceIds[0]] = entitlementsForService1;
platformStore.entitlements_[serviceIds[1]] = entitlementsForService2;
platformStore.getGrantStatus()
.then(entitlements => {
if (entitlements === true) {
done();
} else {
throw new Error('Incorrect entitlement resolved');
}
});
});
it('should resolve false for negative entitlement', done => {
const negativeEntitlements = new Entitlement({source: serviceIds[0],
raw: '',
service: serviceIds[0],
});
platformStore.entitlements_[serviceIds[0]] = negativeEntitlements;
platformStore.entitlements_[serviceIds[1]] = entitlementsForService2;
platformStore.getGrantStatus()
.then(entitlements => {
if (entitlements === false) {
done();
} else {
throw new Error('Incorrect entitlement resolved');
}
});
});
it('should resolve false if all future entitlement '
+ 'are also negative ', done => {
const negativeEntitlements = new Entitlement({source: serviceIds[0],
raw: '',
service: serviceIds[0],
});
platformStore.entitlements_[serviceIds[0]] = negativeEntitlements;
platformStore.getGrantStatus()
.then(entitlements => {
if (entitlements === false) {
done();
} else {
throw new Error('Incorrect entitlement resolved');
}
});
platformStore.resolveEntitlement(serviceIds[1],
entitlementsForService2);
});
});
describe('areAllPlatformsResolved_', () => {
it('should return true if all entitlements are present', () => {
platformStore.resolveEntitlement(serviceIds[1],
entitlementsForService2);
expect(platformStore.areAllPlatformsResolved_()).to.be.equal(false);
platformStore.resolveEntitlement(serviceIds[0],
entitlementsForService1);
expect(platformStore.areAllPlatformsResolved_()).to.be.equal(true);
});
});
describe('getAvailablePlatformsEntitlements_', () => {
it('should return all available entitlements', () => {
platformStore.resolveEntitlement(serviceIds[1],
entitlementsForService2);
expect(platformStore.getAvailablePlatformsEntitlements_())
.to.deep.equal([entitlementsForService2]);
platformStore.resolveEntitlement(serviceIds[0],
entitlementsForService1);
expect(platformStore.getAvailablePlatformsEntitlements_())
.to.deep.equal([entitlementsForService2, entitlementsForService1]);
});
});
describe('getAllPlatformWeights_', () => {
let localPlatform;
let anotherPlatform;
const localPlatformBaseScore = 0;
const anotherPlatformBaseScore = 0;
beforeEach(() => {
localPlatform = new SubscriptionPlatform();
sandbox.stub(localPlatform, 'getServiceId').callsFake(() => 'local');
sandbox.stub(localPlatform, 'getBaseScore')
.callsFake(() => localPlatformBaseScore);
anotherPlatform = new SubscriptionPlatform();
sandbox.stub(anotherPlatform, 'getServiceId').callsFake(() => 'another');
sandbox.stub(anotherPlatform, 'getBaseScore')
.callsFake(() => anotherPlatformBaseScore);
platformStore.resolvePlatform('another', localPlatform);
platformStore.resolvePlatform('local', anotherPlatform);
});
it('should return sorted array of platforms and weights', () => {
sandbox.stub(localPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor, {}));
sandbox.stub(anotherPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor, {}));
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local', raw: '', service: 'local'}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another', raw: '', service: 'another'}));
expect(platformStore.getAllPlatformWeights_())
.to.deep.equal(
[{platform: localPlatform, weight: 0},
{platform: anotherPlatform, weight: 0}]);
});
});
describe('selectPlatform', () => {
it('should call selectApplicablePlatform_ if areAllPlatformsResolved_ '
+ 'is true', () => {
const fakeResult = [entitlementsForService1, entitlementsForService2];
const getAllPlatformsStub = sandbox.stub(platformStore,
'getAllPlatformsEntitlements_').callsFake(
() => Promise.resolve(fakeResult));
const selectApplicablePlatformStub = sandbox.stub(platformStore,
'selectApplicablePlatform_').callsFake(() => Promise.resolve());
return platformStore.selectPlatform(true).then(() => {
expect(getAllPlatformsStub).to.be.calledOnce;
expect(selectApplicablePlatformStub).to.be.calledOnce;
});
});
});
describe('selectApplicablePlatform_', () => {
let localPlatform;
let anotherPlatform;
let localPlatformBaseScore = 0;
let anotherPlatformBaseScore = 0;
beforeEach(() => {
localPlatform = new SubscriptionPlatform();
sandbox.stub(localPlatform, 'getServiceId').callsFake(() => 'local');
sandbox.stub(localPlatform, 'getBaseScore')
.callsFake(() => localPlatformBaseScore);
anotherPlatform = new SubscriptionPlatform();
sandbox.stub(anotherPlatform, 'getServiceId').callsFake(() => 'another');
sandbox.stub(anotherPlatform, 'getBaseScore')
.callsFake(() => anotherPlatformBaseScore);
platformStore.resolvePlatform('local', localPlatform);
platformStore.resolvePlatform('another', anotherPlatform);
});
it('should choose a platform based on subscription', () => {
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local',
raw: '',
service: 'local',
granted: true,
grantReason: GrantReason.SUBSCRIBER,
}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another',
raw: '',
service: 'another',
}));
expect(platformStore.selectApplicablePlatform_().getServiceId())
.to.equal(localPlatform.getServiceId());
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local',
raw: '',
service: 'local',
}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another',
raw: '',
service: 'another',
granted: true,
grantReason: GrantReason.SUBSCRIBER,
}));
expect(platformStore.selectApplicablePlatform_().getServiceId())
.to.equal(anotherPlatform.getServiceId());
});
it('should choose local platform if all other conditions are same', () => {
sandbox.stub(localPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor, {}));
sandbox.stub(anotherPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor, {}));
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local', raw: '', service: 'local'}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another', raw: '', service: 'another'}));
expect(platformStore.selectApplicablePlatform_().getServiceId())
.to.equal(localPlatform.getServiceId());
});
it('should chose platform based on score weight', () => {
sandbox.stub(localPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor, {}));
// +9
sandbox.stub(anotherPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor,
{'supportsViewer': 1}));
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local', raw: '', service: 'local'}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another', raw: '', service: 'another'}));
expect(platformStore.selectApplicablePlatform_().getServiceId())
.to.equal(anotherPlatform.getServiceId());
});
it('should chose platform based on multiple factors', () => {
// +10
sandbox.stub(localPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor,
{'testFactor1': 1}));
// +9
sandbox.stub(anotherPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor,
{'supportsViewer': 1}));
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local', raw: '', service: 'local'}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another', raw: '', service: 'another'}));
expect(platformStore.selectApplicablePlatform_().getServiceId())
.to.equal(localPlatform.getServiceId());
});
it('should chose platform specified factors', () => {
// +10
sandbox.stub(localPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor,
{'testFactor1': 1}));
// +9
sandbox.stub(anotherPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor,
{'supportsViewer': 1}));
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local', raw: '', service: 'local'}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another', raw: '', service: 'another'}));
expect(platformStore.selectApplicablePlatform_('supporsViewer')
.getServiceId())
.to.equal(localPlatform.getServiceId());
});
it('should chose platform handle negative factor values', () => {
// +10, -10
sandbox.stub(localPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor,
{testFactor1: 1, testFactor2: -1}));
// +9
sandbox.stub(anotherPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor,
{'supportsViewer': 1}));
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local', raw: '', service: 'local'}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another', raw: '', service: 'another'}));
expect(platformStore.selectApplicablePlatform_().getServiceId())
.to.equal(anotherPlatform.getServiceId());
});
it('should use baseScore', () => {
sandbox.stub(localPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor, {}));
sandbox.stub(anotherPlatform, 'getSupportedScoreFactor')
.callsFake(factor => fakeGetSupportedScoreFactor(factor, {}));
localPlatformBaseScore = 1;
anotherPlatformBaseScore = 10;
platformStore.resolveEntitlement('local', new Entitlement({
source: 'local', raw: '', service: 'local'}));
platformStore.resolveEntitlement('another', new Entitlement({
source: 'another', raw: '', service: 'another'}));
expect(platformStore.selectApplicablePlatform_()
.getServiceId()).to.equal(anotherPlatform.getServiceId());
});
});
describe('selectPlatformForLogin', () => {
let localPlatform, localFactors;
let anotherPlatform, anotherFactors;
beforeEach(() => {
localFactors = {};
localPlatform = new SubscriptionPlatform();
sandbox.stub(localPlatform, 'getServiceId').callsFake(() => 'local');
// Base score does not matter.
sandbox.stub(localPlatform, 'getBaseScore')
.callsFake(() => 10000);
sandbox.stub(localPlatform, 'getSupportedScoreFactor')
.callsFake(factor => localFactors[factor]);
anotherFactors = {};
anotherPlatform = new SubscriptionPlatform();
sandbox.stub(anotherPlatform, 'getServiceId').callsFake(() => 'another');
sandbox.stub(anotherPlatform, 'getBaseScore')
.callsFake(() => 0);
sandbox.stub(anotherPlatform, 'getSupportedScoreFactor')
.callsFake(factor => anotherFactors[factor]);
// Local is ordered last in this case intentionally.
platformStore.resolvePlatform('another', anotherPlatform);
platformStore.resolvePlatform('local', localPlatform);
});
it('should chose local platform by default', () => {
expect(platformStore.selectPlatformForLogin())
.to.equal(localPlatform);
});
it('should chose platform based on the viewer factor', () => {
anotherFactors['supportsViewer'] = 1;
expect(platformStore.selectPlatformForLogin())
.to.equal(anotherPlatform);
});
it('should tie-break to local', () => {
localFactors['supportsViewer'] = 1;
anotherFactors['supportsViewer'] = 1;
expect(platformStore.selectPlatformForLogin())
.to.equal(localPlatform);
});
it('should rank factors as numbers', () => {
localFactors['supportsViewer'] = 0.99999;
anotherFactors['supportsViewer'] = 1;
expect(platformStore.selectPlatformForLogin())
.to.equal(anotherPlatform);
});
});
describe('reportPlatformFailureAndFallback', () => {
let errorSpy;
beforeEach(() => {
errorSpy = sandbox.spy(user(), 'warn');
});
it('should report warning if all platforms fail and resolve '
+ 'local with fallbackEntitlement', () => {
const platform = new SubscriptionPlatform();
sandbox.stub(platform, 'getServiceId').callsFake(() => 'local');
sandbox.stub(platformStore, 'getLocalPlatform').callsFake(() => platform);
platformStore.reportPlatformFailureAndFallback('service1');
expect(errorSpy).to.not.be.called;
platformStore.reportPlatformFailureAndFallback('local');
expect(errorSpy).to.be.calledOnce;
expect(platformStore.entitlements_['local'].json())
.to.deep.equal(fallbackEntitlement.json());
});
it('should not interfere with selectPlatform flow if using fallback, '
+ 'when reason is SUBSCRIBER', () => {
const platform = new SubscriptionPlatform();
const anotherPlatform = new SubscriptionPlatform();
sandbox.stub(platform, 'getServiceId').callsFake(() => 'local');
sandbox.stub(platformStore, 'getLocalPlatform').callsFake(() => platform);
sandbox.stub(anotherPlatform, 'getServiceId').callsFake(
() => serviceIds[0]);
sandbox.stub(anotherPlatform, 'getBaseScore')
.callsFake(() => 10);
platformStore.resolvePlatform(serviceIds[0], anotherPlatform);
platformStore.resolvePlatform('local', platform);
platformStore.reportPlatformFailureAndFallback('local');
platformStore.resolveEntitlement(serviceIds[0], entitlementsForService1);
return platformStore.selectPlatform().then(platform => {
expect(platformStore.entitlements_['local']).deep.equals(
fallbackEntitlement);
// falbackEntitlement has Reason as SUBSCRIBER so it should win
expect(platform.getServiceId()).to.equal('local');
});
});
it('should not interfere with selectPlatform flow if using fallback, '
+ 'when reason is not SUBSCRIBER', () => {
const platform = new SubscriptionPlatform();
const anotherPlatform = new SubscriptionPlatform();
sandbox.stub(platform, 'getServiceId').callsFake(() => 'local');
sandbox.stub(platformStore, 'getLocalPlatform').callsFake(() => platform);
sandbox.stub(anotherPlatform, 'getServiceId').callsFake(
() => serviceIds[0]);
sandbox.stub(anotherPlatform, 'getBaseScore')
.callsFake(() => 10);
platformStore.resolvePlatform(serviceIds[0], anotherPlatform);
platformStore.resolvePlatform('local', platform);
fallbackEntitlement.grantReason = GrantReason.METERING;
platformStore.reportPlatformFailureAndFallback('local');
platformStore.resolveEntitlement(serviceIds[0], entitlementsForService1);
return platformStore.selectPlatform().then(platform => {
expect(platformStore.entitlements_['local']).deep.equals(
fallbackEntitlement);
// falbackEntitlement has Reason as SUBSCRIBER so it should win
expect(platform.getServiceId()).to.equal(serviceIds[0]);
});
});
});
describe('getPlatform', () => {
it('should return the platform for the serviceId', () => {
const platform = new SubscriptionPlatform();
platform.getServiceId = () => 'test';
platformStore.subscriptionPlatforms_['test'] = platform;
expect(platformStore.getPlatform('test').getServiceId())
.to.be.equal('test');
});
});
describe('getGrantEntitlement', () => {
const subscribedEntitlement = new Entitlement({
source: 'local',
service: 'local',
granted: true,
grantReason: GrantReason.SUBSCRIBER,
});
const meteringEntitlement = new Entitlement({
source: 'local',
service: 'local',
granted: true,
grantReason: GrantReason.METERING,
});
const noEntitlement = new Entitlement({
source: 'local',
service: 'local',
granted: false,
});
it('should resolve with existing entitlement with subscriptions', () => {
platformStore.grantStatusEntitlement_ = subscribedEntitlement;
return platformStore.getGrantEntitlement().then(entitlement => {
expect(entitlement).to.equal(subscribedEntitlement);
});
});
it('should resolve with first entitlement with subscriptions', () => {
platformStore.resolveEntitlement('service1', subscribedEntitlement);
return platformStore.getGrantEntitlement().then(entitlement => {
expect(entitlement).to.equal(subscribedEntitlement);
});
});
it('should resolve with metered entitlement when no '
+ 'platform is subscribed', () => {
platformStore.resolveEntitlement('service1', noEntitlement);
platformStore.resolveEntitlement('service2', meteringEntitlement);
return platformStore.getGrantEntitlement().then(entitlement => {
expect(entitlement).to.equal(meteringEntitlement);
});
});
it('should override metering with subscription', () => {
platformStore.resolveEntitlement('service1', meteringEntitlement);
platformStore.resolveEntitlement('service2', subscribedEntitlement);
return platformStore.getGrantEntitlement().then(entitlement => {
expect(entitlement).to.equal(subscribedEntitlement);
});
});
it('should resolve to null if nothing matched', () => {
platformStore.resolveEntitlement('service1', noEntitlement);
platformStore.resolveEntitlement('service2', noEntitlement);
return platformStore.getGrantEntitlement().then(entitlement => {
expect(entitlement).to.be.null;
});
});
});
describe('saveGrantEntitlement_', () => {
it('should save first entitlement to grant', () => {
const entitlementData = {
source: 'local',
service: 'local',
granted: false,
grantReason: GrantReason.METERING,
};
const entitlement = new Entitlement(entitlementData);
platformStore.saveGrantEntitlement_(entitlement);
expect(platformStore.grantStatusEntitlement_).to.be.equal(null);
const anotherEntitlement = new Entitlement(
Object.assign({}, entitlementData, {granted: true}));
platformStore.saveGrantEntitlement_(anotherEntitlement);
expect(platformStore.grantStatusEntitlement_.json())
.to.deep.equal(anotherEntitlement.json());
});
it('should save further entitlement if new one has subscription '
+ 'and last one had metering', () => {
const entitlementData = {
source: 'local',
service: 'local',
granted: true,
};
const entitlement = new Entitlement(entitlementData);
const nextMeteredEntitlement = new Entitlement(
Object.assign({}, entitlementData, {
grantReason: GrantReason.METERING,
})
);
const subscribedMeteredEntitlement = new Entitlement(
Object.assign({}, entitlementData, {
grantReason: GrantReason.SUBSCRIBER,
})
);
platformStore.saveGrantEntitlement_(entitlement);
expect(platformStore.grantStatusEntitlement_.json())
.to.deep.equal(entitlement.json());
platformStore.saveGrantEntitlement_(nextMeteredEntitlement);
expect(platformStore.grantStatusEntitlement_.json())
.to.deep.equal(entitlement.json());
platformStore.saveGrantEntitlement_(subscribedMeteredEntitlement);
expect(platformStore.grantStatusEntitlement_.json())
.to.deep.equal(subscribedMeteredEntitlement.json());
});
});
describe('onPlatformResolves', () => {
let localPlatform;
beforeEach(() => {
localPlatform = new SubscriptionPlatform();
sandbox.stub(localPlatform, 'getServiceId').callsFake(() => 'local');
});
it('should return a promise resolving the requested platform '
+ 'if it is already registered', () => {
platformStore.resolvePlatform('local', localPlatform);
platformStore.onPlatformResolves('local', platform => {
expect(platform.getServiceId()).to.be.equal('local');
});
});
it('should return a promise resolving when the requested platform '
+ 'gets registered', done => {
platformStore.onPlatformResolves('local', platform => {
expect(platform.getServiceId()).to.be.equal('local');
done();
});
platformStore.resolvePlatform('local', localPlatform);
});
});
});
| techhtml/amphtml | extensions/amp-subscriptions/0.1/test/test-platform-store.js | JavaScript | apache-2.0 | 25,782 |
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.
******************************************************************************/
package com.badlogic.gdx.backends.gwt;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.ObjectMap;
public class GwtPreferences implements Preferences {
final String prefix;
ObjectMap<String, Object> values = new ObjectMap<String, Object>();
GwtPreferences (String prefix) {
this.prefix = prefix + ":";
int prefixLength = this.prefix.length();
try {
for (int i = 0; i < GwtFiles.LocalStorage.getLength(); i++) {
String key = GwtFiles.LocalStorage.key(i);
if (key.startsWith(prefix)) {
String value = GwtFiles.LocalStorage.getItem(key);
values.put(key.substring(prefixLength, key.length() - 1), toObject(key, value));
}
}
} catch (Exception e) {
values.clear();
}
}
private Object toObject (String key, String value) {
if (key.endsWith("b")) return new Boolean(Boolean.parseBoolean(value));
if (key.endsWith("i")) return new Integer(Integer.parseInt(value));
if (key.endsWith("l")) return new Long(Long.parseLong(value));
if (key.endsWith("f")) return new Float(Float.parseFloat(value));
return value;
}
private String toStorageKey (String key, Object value) {
if (value instanceof Boolean) return prefix + key + "b";
if (value instanceof Integer) return prefix + key + "i";
if (value instanceof Long) return prefix + key + "l";
if (value instanceof Float) return prefix + key + "f";
return prefix + key + "s";
}
@Override
public void flush () {
try {
// remove all old values
for (int i = 0; i < GwtFiles.LocalStorage.getLength(); i++) {
String key = GwtFiles.LocalStorage.key(i);
if (key.startsWith(prefix)) GwtFiles.LocalStorage.removeItem(key);
}
// push new values to LocalStorage
for (String key : values.keys()) {
String storageKey = toStorageKey(key, values.get(key));
String storageValue = "" + values.get(key).toString();
GwtFiles.LocalStorage.setItem(storageKey, storageValue);
}
} catch (Exception e) {
throw new GdxRuntimeException("Couldn't flush preferences");
}
}
@Override
public void putBoolean (String key, boolean val) {
values.put(key, val);
}
@Override
public void putInteger (String key, int val) {
values.put(key, val);
}
@Override
public void putLong (String key, long val) {
values.put(key, val);
}
@Override
public void putFloat (String key, float val) {
values.put(key, val);
}
@Override
public void putString (String key, String val) {
values.put(key, val);
}
@Override
public void put (Map<String, ?> vals) {
for (String key : vals.keySet()) {
values.put(key, vals.get(key));
}
}
@Override
public boolean getBoolean (String key) {
Boolean v = (Boolean)values.get(key);
return v == null ? false : v;
}
@Override
public int getInteger (String key) {
Integer v = (Integer)values.get(key);
return v == null ? 0 : v;
}
@Override
public long getLong (String key) {
Long v = (Long)values.get(key);
return v == null ? 0 : v;
}
@Override
public float getFloat (String key) {
Float v = (Float)values.get(key);
return v == null ? 0 : v;
}
@Override
public String getString (String key) {
String v = (String)values.get(key);
return v == null ? "" : v;
}
@Override
public boolean getBoolean (String key, boolean defValue) {
Boolean res = (Boolean)values.get(key);
return res == null ? defValue : res;
}
@Override
public int getInteger (String key, int defValue) {
Integer res = (Integer)values.get(key);
return res == null ? defValue : res;
}
@Override
public long getLong (String key, long defValue) {
Long res = (Long)values.get(key);
return res == null ? defValue : res;
}
@Override
public float getFloat (String key, float defValue) {
Float res = (Float)values.get(key);
return res == null ? defValue : res;
}
@Override
public String getString (String key, String defValue) {
String res = (String)values.get(key);
return res == null ? defValue : res;
}
@Override
public Map<String, ?> get () {
HashMap<String, Object> map = new HashMap<String, Object>();
for (String key : values.keys()) {
map.put(key, values.get(key));
}
return map;
}
@Override
public boolean contains (String key) {
return values.containsKey(key);
}
@Override
public void clear () {
values.clear();
}
@Override
public void remove (String key) {
values.remove(key);
}
}
| MathieuDuponchelle/gdx | backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtPreferences.java | Java | apache-2.0 | 5,413 |
@font-face {
font-family: 'socicon';
src: url('font/socicon-webfont.eot');
src: url('font/socicon-webfont.eot?#iefix') format('embedded-opentype'),
url('font/socicon-webfont.woff') format('woff'),
url('font/socicon-webfont.woff2') format('woff2'),
url('font/socicon-webfont.ttf') format('truetype'),
url('font/socicon-webfont.svg#sociconregular') format('svg');
font-weight: normal;
font-style: normal;
text-transform: initial;
} | nucleos-io/web | tools/socicon/socicon.css | CSS | apache-2.0 | 489 |
// Copyright 2012 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/x64/codegen-x64.h"
#if V8_TARGET_ARCH_X64
#include "src/codegen.h"
#include "src/macro-assembler.h"
namespace v8 {
namespace internal {
// -------------------------------------------------------------------------
// Platform-specific RuntimeCallHelper functions.
void StubRuntimeCallHelper::BeforeCall(MacroAssembler* masm) const {
masm->EnterFrame(StackFrame::INTERNAL);
DCHECK(!masm->has_frame());
masm->set_has_frame(true);
}
void StubRuntimeCallHelper::AfterCall(MacroAssembler* masm) const {
masm->LeaveFrame(StackFrame::INTERNAL);
DCHECK(masm->has_frame());
masm->set_has_frame(false);
}
#define __ masm.
UnaryMathFunctionWithIsolate CreateSqrtFunction(Isolate* isolate) {
size_t actual_size;
// Allocate buffer in executable space.
byte* buffer =
static_cast<byte*>(base::OS::Allocate(1 * KB, &actual_size, true));
if (buffer == nullptr) return nullptr;
MacroAssembler masm(isolate, buffer, static_cast<int>(actual_size),
CodeObjectRequired::kNo);
// xmm0: raw double input.
// Move double input into registers.
__ Sqrtsd(xmm0, xmm0);
__ Ret();
CodeDesc desc;
masm.GetCode(&desc);
DCHECK(!RelocInfo::RequiresRelocation(desc));
Assembler::FlushICache(isolate, buffer, actual_size);
base::OS::ProtectCode(buffer, actual_size);
return FUNCTION_CAST<UnaryMathFunctionWithIsolate>(buffer);
}
#undef __
// -------------------------------------------------------------------------
// Code generators
#define __ ACCESS_MASM(masm)
void StringCharLoadGenerator::Generate(MacroAssembler* masm,
Register string,
Register index,
Register result,
Label* call_runtime) {
// Fetch the instance type of the receiver into result register.
__ movp(result, FieldOperand(string, HeapObject::kMapOffset));
__ movzxbl(result, FieldOperand(result, Map::kInstanceTypeOffset));
// We need special handling for indirect strings.
Label check_sequential;
__ testb(result, Immediate(kIsIndirectStringMask));
__ j(zero, &check_sequential, Label::kNear);
// Dispatch on the indirect string shape: slice or cons.
Label cons_string;
__ testb(result, Immediate(kSlicedNotConsMask));
__ j(zero, &cons_string, Label::kNear);
// Handle slices.
Label indirect_string_loaded;
__ SmiToInteger32(result, FieldOperand(string, SlicedString::kOffsetOffset));
__ addp(index, result);
__ movp(string, FieldOperand(string, SlicedString::kParentOffset));
__ jmp(&indirect_string_loaded, Label::kNear);
// Handle cons strings.
// Check whether the right hand side is the empty string (i.e. if
// this is really a flat string in a cons string). If that is not
// the case we would rather go to the runtime system now to flatten
// the string.
__ bind(&cons_string);
__ CompareRoot(FieldOperand(string, ConsString::kSecondOffset),
Heap::kempty_stringRootIndex);
__ j(not_equal, call_runtime);
__ movp(string, FieldOperand(string, ConsString::kFirstOffset));
__ bind(&indirect_string_loaded);
__ movp(result, FieldOperand(string, HeapObject::kMapOffset));
__ movzxbl(result, FieldOperand(result, Map::kInstanceTypeOffset));
// Distinguish sequential and external strings. Only these two string
// representations can reach here (slices and flat cons strings have been
// reduced to the underlying sequential or external string).
Label seq_string;
__ bind(&check_sequential);
STATIC_ASSERT(kSeqStringTag == 0);
__ testb(result, Immediate(kStringRepresentationMask));
__ j(zero, &seq_string, Label::kNear);
// Handle external strings.
Label one_byte_external, done;
if (FLAG_debug_code) {
// Assert that we do not have a cons or slice (indirect strings) here.
// Sequential strings have already been ruled out.
__ testb(result, Immediate(kIsIndirectStringMask));
__ Assert(zero, kExternalStringExpectedButNotFound);
}
// Rule out short external strings.
STATIC_ASSERT(kShortExternalStringTag != 0);
__ testb(result, Immediate(kShortExternalStringTag));
__ j(not_zero, call_runtime);
// Check encoding.
STATIC_ASSERT(kTwoByteStringTag == 0);
__ testb(result, Immediate(kStringEncodingMask));
__ movp(result, FieldOperand(string, ExternalString::kResourceDataOffset));
__ j(not_equal, &one_byte_external, Label::kNear);
// Two-byte string.
__ movzxwl(result, Operand(result, index, times_2, 0));
__ jmp(&done, Label::kNear);
__ bind(&one_byte_external);
// One-byte string.
__ movzxbl(result, Operand(result, index, times_1, 0));
__ jmp(&done, Label::kNear);
// Dispatch on the encoding: one-byte or two-byte.
Label one_byte;
__ bind(&seq_string);
STATIC_ASSERT((kStringEncodingMask & kOneByteStringTag) != 0);
STATIC_ASSERT((kStringEncodingMask & kTwoByteStringTag) == 0);
__ testb(result, Immediate(kStringEncodingMask));
__ j(not_zero, &one_byte, Label::kNear);
// Two-byte string.
// Load the two-byte character code into the result register.
STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1);
__ movzxwl(result, FieldOperand(string,
index,
times_2,
SeqTwoByteString::kHeaderSize));
__ jmp(&done, Label::kNear);
// One-byte string.
// Load the byte into the result register.
__ bind(&one_byte);
__ movzxbl(result, FieldOperand(string,
index,
times_1,
SeqOneByteString::kHeaderSize));
__ bind(&done);
}
#undef __
CodeAgingHelper::CodeAgingHelper(Isolate* isolate) {
USE(isolate);
DCHECK(young_sequence_.length() == kNoCodeAgeSequenceLength);
// The sequence of instructions that is patched out for aging code is the
// following boilerplate stack-building prologue that is found both in
// FUNCTION and OPTIMIZED_FUNCTION code:
CodePatcher patcher(isolate, young_sequence_.start(),
young_sequence_.length());
patcher.masm()->pushq(rbp);
patcher.masm()->movp(rbp, rsp);
patcher.masm()->Push(rsi);
patcher.masm()->Push(rdi);
}
#ifdef DEBUG
bool CodeAgingHelper::IsOld(byte* candidate) const {
return *candidate == kCallOpcode;
}
#endif
bool Code::IsYoungSequence(Isolate* isolate, byte* sequence) {
bool result = isolate->code_aging_helper()->IsYoung(sequence);
DCHECK(result || isolate->code_aging_helper()->IsOld(sequence));
return result;
}
Code::Age Code::GetCodeAge(Isolate* isolate, byte* sequence) {
if (IsYoungSequence(isolate, sequence)) return kNoAgeCodeAge;
sequence++; // Skip the kCallOpcode byte
Address target_address = sequence + *reinterpret_cast<int*>(sequence) +
Assembler::kCallTargetAddressOffset;
Code* stub = GetCodeFromTargetAddress(target_address);
return GetAgeOfCodeAgeStub(stub);
}
void Code::PatchPlatformCodeAge(Isolate* isolate, byte* sequence,
Code::Age age) {
uint32_t young_length = isolate->code_aging_helper()->young_sequence_length();
if (age == kNoAgeCodeAge) {
isolate->code_aging_helper()->CopyYoungSequenceTo(sequence);
Assembler::FlushICache(isolate, sequence, young_length);
} else {
Code* stub = GetCodeAgeStub(isolate, age);
CodePatcher patcher(isolate, sequence, young_length);
patcher.masm()->call(stub->instruction_start());
patcher.masm()->Nop(
kNoCodeAgeSequenceLength - Assembler::kShortCallInstructionLength);
}
}
Operand StackArgumentsAccessor::GetArgumentOperand(int index) {
DCHECK(index >= 0);
int receiver = (receiver_mode_ == ARGUMENTS_CONTAIN_RECEIVER) ? 1 : 0;
int displacement_to_last_argument = base_reg_.is(rsp) ?
kPCOnStackSize : kFPOnStackSize + kPCOnStackSize;
displacement_to_last_argument += extra_displacement_to_last_argument_;
if (argument_count_reg_.is(no_reg)) {
// argument[0] is at base_reg_ + displacement_to_last_argument +
// (argument_count_immediate_ + receiver - 1) * kPointerSize.
DCHECK(argument_count_immediate_ + receiver > 0);
return Operand(base_reg_, displacement_to_last_argument +
(argument_count_immediate_ + receiver - 1 - index) * kPointerSize);
} else {
// argument[0] is at base_reg_ + displacement_to_last_argument +
// argument_count_reg_ * times_pointer_size + (receiver - 1) * kPointerSize.
return Operand(base_reg_, argument_count_reg_, times_pointer_size,
displacement_to_last_argument + (receiver - 1 - index) * kPointerSize);
}
}
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_X64
| weolar/miniblink49 | v8_5_7/src/x64/codegen-x64.cc | C++ | apache-2.0 | 8,916 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* If x is +0, Math.atan(x) is +0
*
* @path ch15/15.8/15.8.2/15.8.2.4/S15.8.2.4_A2.js
* @description Checking if Math.atan(+0) equals to +0
*/
// CHECK#1
var x = +0;
if (Math.atan(x) !== +0)
{
$ERROR("#1: 'var x = +0; Math.atan(x) !== +0'");
}
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.8/15.8.2/15.8.2.4/S15.8.2.4_A2.js | JavaScript | apache-2.0 | 388 |
/*
* Copyright 2017-present Facebook, Inc.
*
* 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.
*/
package com.facebook.buck.rules.macros;
import com.facebook.buck.core.util.immutables.BuckStyleTuple;
import org.immutables.value.Value;
@Value.Immutable
@BuckStyleTuple
abstract class AbstractClasspathAbiMacro extends BuildTargetMacro {}
| LegNeato/buck | src/com/facebook/buck/rules/macros/AbstractClasspathAbiMacro.java | Java | apache-2.0 | 848 |
class Foo {
constructor() {
this.a = 42;
this.b = 'hello';
this.emit('done');
}
}
| a1ph/puppeteer | utils/doclint/check_public_api/test/diff-properties/foo.js | JavaScript | apache-2.0 | 98 |
/*
* 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.
*/
package org.apache.lucene.analysis.cn.smart.hhmm;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.lucene.analysis.cn.smart.AnalyzerProfile;
import org.apache.lucene.analysis.cn.smart.Utility;
/**
* SmartChineseAnalyzer Word Dictionary
* @lucene.experimental
*/
class WordDictionary extends AbstractDictionary {
private WordDictionary() {
}
private static WordDictionary singleInstance;
/**
* Large prime number for hash function
*/
public static final int PRIME_INDEX_LENGTH = 12071;
/**
* wordIndexTable guarantees to hash all Chinese characters in Unicode into
* PRIME_INDEX_LENGTH array. There will be conflict, but in reality this
* program only handles the 6768 characters found in GB2312 plus some
* ASCII characters. Therefore in order to guarantee better precision, it is
* necessary to retain the original symbol in the charIndexTable.
*/
private short[] wordIndexTable;
private char[] charIndexTable;
/**
* To avoid taking too much space, the data structure needed to store the
* lexicon requires two multidimensional arrays to store word and frequency.
* Each word is placed in a char[]. Each char represents a Chinese char or
* other symbol. Each frequency is put into an int. These two arrays
* correspond to each other one-to-one. Therefore, one can use
* wordItem_charArrayTable[i][j] to look up word from lexicon, and
* wordItem_frequencyTable[i][j] to look up the corresponding frequency.
*/
private char[][][] wordItem_charArrayTable;
private int[][] wordItem_frequencyTable;
// static Logger log = Logger.getLogger(WordDictionary.class);
/**
* Get the singleton dictionary instance.
* @return singleton
*/
public synchronized static WordDictionary getInstance() {
if (singleInstance == null) {
singleInstance = new WordDictionary();
try {
singleInstance.load();
} catch (IOException e) {
String wordDictRoot = AnalyzerProfile.ANALYSIS_DATA_DIR;
singleInstance.load(wordDictRoot);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
return singleInstance;
}
/**
* Attempt to load dictionary from provided directory, first trying coredict.mem, failing back on coredict.dct
*
* @param dctFileRoot path to dictionary directory
*/
public void load(String dctFileRoot) {
String dctFilePath = dctFileRoot + "/coredict.dct";
Path serialObj = Paths.get(dctFileRoot + "/coredict.mem");
if (Files.exists(serialObj) && loadFromObj(serialObj)) {
} else {
try {
wordIndexTable = new short[PRIME_INDEX_LENGTH];
charIndexTable = new char[PRIME_INDEX_LENGTH];
for (int i = 0; i < PRIME_INDEX_LENGTH; i++) {
charIndexTable[i] = 0;
wordIndexTable[i] = -1;
}
wordItem_charArrayTable = new char[GB2312_CHAR_NUM][][];
wordItem_frequencyTable = new int[GB2312_CHAR_NUM][];
// int total =
loadMainDataFromFile(dctFilePath);
expandDelimiterData();
mergeSameWords();
sortEachItems();
// log.info("load dictionary: " + dctFilePath + " total:" + total);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
saveToObj(serialObj);
}
}
/**
* Load coredict.mem internally from the jar file.
*
* @throws IOException If there is a low-level I/O error.
*/
public void load() throws IOException, ClassNotFoundException {
InputStream input = this.getClass().getResourceAsStream("coredict.mem");
loadFromObjectInputStream(input);
}
private boolean loadFromObj(Path serialObj) {
try {
loadFromObjectInputStream(Files.newInputStream(serialObj));
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void loadFromObjectInputStream(InputStream serialObjectInputStream)
throws IOException, ClassNotFoundException {
ObjectInputStream input = new ObjectInputStream(serialObjectInputStream);
wordIndexTable = (short[]) input.readObject();
charIndexTable = (char[]) input.readObject();
wordItem_charArrayTable = (char[][][]) input.readObject();
wordItem_frequencyTable = (int[][]) input.readObject();
// log.info("load core dict from serialization.");
input.close();
}
private void saveToObj(Path serialObj) {
try {
ObjectOutputStream output = new ObjectOutputStream(Files.newOutputStream(
serialObj));
output.writeObject(wordIndexTable);
output.writeObject(charIndexTable);
output.writeObject(wordItem_charArrayTable);
output.writeObject(wordItem_frequencyTable);
output.close();
// log.info("serialize core dict.");
} catch (Exception e) {
// log.warn(e.getMessage());
}
}
/**
* Load the datafile into this WordDictionary
*
* @param dctFilePath path to word dictionary (coredict.dct)
* @return number of words read
* @throws IOException If there is a low-level I/O error.
*/
private int loadMainDataFromFile(String dctFilePath) throws IOException {
int i, cnt, length, total = 0;
// The file only counted 6763 Chinese characters plus 5 reserved slots 3756~3760.
// The 3756th is used (as a header) to store information.
int[] buffer = new int[3];
byte[] intBuffer = new byte[4];
String tmpword;
DataInputStream dctFile = new DataInputStream(Files.newInputStream(Paths.get(dctFilePath)));
// GB2312 characters 0 - 6768
for (i = GB2312_FIRST_CHAR; i < GB2312_FIRST_CHAR + CHAR_NUM_IN_FILE; i++) {
// if (i == 5231)
// System.out.println(i);
dctFile.read(intBuffer);
// the dictionary was developed for C, and byte order must be converted to work with Java
cnt = ByteBuffer.wrap(intBuffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
if (cnt <= 0) {
wordItem_charArrayTable[i] = null;
wordItem_frequencyTable[i] = null;
continue;
}
wordItem_charArrayTable[i] = new char[cnt][];
wordItem_frequencyTable[i] = new int[cnt];
total += cnt;
int j = 0;
while (j < cnt) {
// wordItemTable[i][j] = new WordItem();
dctFile.read(intBuffer);
buffer[0] = ByteBuffer.wrap(intBuffer).order(ByteOrder.LITTLE_ENDIAN)
.getInt();// frequency
dctFile.read(intBuffer);
buffer[1] = ByteBuffer.wrap(intBuffer).order(ByteOrder.LITTLE_ENDIAN)
.getInt();// length
dctFile.read(intBuffer);
buffer[2] = ByteBuffer.wrap(intBuffer).order(ByteOrder.LITTLE_ENDIAN)
.getInt();// handle
// wordItemTable[i][j].frequency = buffer[0];
wordItem_frequencyTable[i][j] = buffer[0];
length = buffer[1];
if (length > 0) {
byte[] lchBuffer = new byte[length];
dctFile.read(lchBuffer);
tmpword = new String(lchBuffer, "GB2312");
// indexTable[i].wordItems[j].word = tmpword;
// wordItemTable[i][j].charArray = tmpword.toCharArray();
wordItem_charArrayTable[i][j] = tmpword.toCharArray();
} else {
// wordItemTable[i][j].charArray = null;
wordItem_charArrayTable[i][j] = null;
}
// System.out.println(indexTable[i].wordItems[j]);
j++;
}
String str = getCCByGB2312Id(i);
setTableIndex(str.charAt(0), i);
}
dctFile.close();
return total;
}
/**
* The original lexicon puts all information with punctuation into a
* chart (from 1 to 3755). Here it then gets expanded, separately being
* placed into the chart that has the corresponding symbol.
*/
private void expandDelimiterData() {
int i;
int cnt;
// Punctuation then treating index 3755 as 1,
// distribute the original punctuation corresponding dictionary into
int delimiterIndex = 3755 + GB2312_FIRST_CHAR;
i = 0;
while (i < wordItem_charArrayTable[delimiterIndex].length) {
char c = wordItem_charArrayTable[delimiterIndex][i][0];
int j = getGB2312Id(c);// the id value of the punctuation
if (wordItem_charArrayTable[j] == null) {
int k = i;
// Starting from i, count the number of the following worditem symbol from j
while (k < wordItem_charArrayTable[delimiterIndex].length
&& wordItem_charArrayTable[delimiterIndex][k][0] == c) {
k++;
}
// c is the punctuation character, j is the id value of c
// k-1 represents the index of the last punctuation character
cnt = k - i;
if (cnt != 0) {
wordItem_charArrayTable[j] = new char[cnt][];
wordItem_frequencyTable[j] = new int[cnt];
}
// Assign value for each wordItem.
for (k = 0; k < cnt; k++, i++) {
// wordItemTable[j][k] = new WordItem();
wordItem_frequencyTable[j][k] = wordItem_frequencyTable[delimiterIndex][i];
wordItem_charArrayTable[j][k] = new char[wordItem_charArrayTable[delimiterIndex][i].length - 1];
System.arraycopy(wordItem_charArrayTable[delimiterIndex][i], 1,
wordItem_charArrayTable[j][k], 0,
wordItem_charArrayTable[j][k].length);
}
setTableIndex(c, j);
}
}
// Delete the original corresponding symbol array.
wordItem_charArrayTable[delimiterIndex] = null;
wordItem_frequencyTable[delimiterIndex] = null;
}
/*
* since we aren't doing POS-tagging, merge the frequencies for entries of the same word (with different POS)
*/
private void mergeSameWords() {
int i;
for (i = 0; i < GB2312_FIRST_CHAR + CHAR_NUM_IN_FILE; i++) {
if (wordItem_charArrayTable[i] == null)
continue;
int len = 1;
for (int j = 1; j < wordItem_charArrayTable[i].length; j++) {
if (Utility.compareArray(wordItem_charArrayTable[i][j], 0,
wordItem_charArrayTable[i][j - 1], 0) != 0)
len++;
}
if (len < wordItem_charArrayTable[i].length) {
char[][] tempArray = new char[len][];
int[] tempFreq = new int[len];
int k = 0;
tempArray[0] = wordItem_charArrayTable[i][0];
tempFreq[0] = wordItem_frequencyTable[i][0];
for (int j = 1; j < wordItem_charArrayTable[i].length; j++) {
if (Utility.compareArray(wordItem_charArrayTable[i][j], 0,
tempArray[k], 0) != 0) {
k++;
// temp[k] = wordItemTable[i][j];
tempArray[k] = wordItem_charArrayTable[i][j];
tempFreq[k] = wordItem_frequencyTable[i][j];
} else {
// temp[k].frequency += wordItemTable[i][j].frequency;
tempFreq[k] += wordItem_frequencyTable[i][j];
}
}
// wordItemTable[i] = temp;
wordItem_charArrayTable[i] = tempArray;
wordItem_frequencyTable[i] = tempFreq;
}
}
}
private void sortEachItems() {
char[] tmpArray;
int tmpFreq;
for (int i = 0; i < wordItem_charArrayTable.length; i++) {
if (wordItem_charArrayTable[i] != null
&& wordItem_charArrayTable[i].length > 1) {
for (int j = 0; j < wordItem_charArrayTable[i].length - 1; j++) {
for (int j2 = j + 1; j2 < wordItem_charArrayTable[i].length; j2++) {
if (Utility.compareArray(wordItem_charArrayTable[i][j], 0,
wordItem_charArrayTable[i][j2], 0) > 0) {
tmpArray = wordItem_charArrayTable[i][j];
tmpFreq = wordItem_frequencyTable[i][j];
wordItem_charArrayTable[i][j] = wordItem_charArrayTable[i][j2];
wordItem_frequencyTable[i][j] = wordItem_frequencyTable[i][j2];
wordItem_charArrayTable[i][j2] = tmpArray;
wordItem_frequencyTable[i][j2] = tmpFreq;
}
}
}
}
}
}
/*
* Calculate character c's position in hash table,
* then initialize the value of that position in the address table.
*/
private boolean setTableIndex(char c, int j) {
int index = getAvaliableTableIndex(c);
if (index != -1) {
charIndexTable[index] = c;
wordIndexTable[index] = (short) j;
return true;
} else
return false;
}
private short getAvaliableTableIndex(char c) {
int hash1 = (int) (hash1(c) % PRIME_INDEX_LENGTH);
int hash2 = hash2(c) % PRIME_INDEX_LENGTH;
if (hash1 < 0)
hash1 = PRIME_INDEX_LENGTH + hash1;
if (hash2 < 0)
hash2 = PRIME_INDEX_LENGTH + hash2;
int index = hash1;
int i = 1;
while (charIndexTable[index] != 0 && charIndexTable[index] != c
&& i < PRIME_INDEX_LENGTH) {
index = (hash1 + i * hash2) % PRIME_INDEX_LENGTH;
i++;
}
// System.out.println(i - 1);
if (i < PRIME_INDEX_LENGTH
&& (charIndexTable[index] == 0 || charIndexTable[index] == c)) {
return (short) index;
} else
return -1;
}
private short getWordItemTableIndex(char c) {
int hash1 = (int) (hash1(c) % PRIME_INDEX_LENGTH);
int hash2 = hash2(c) % PRIME_INDEX_LENGTH;
if (hash1 < 0)
hash1 = PRIME_INDEX_LENGTH + hash1;
if (hash2 < 0)
hash2 = PRIME_INDEX_LENGTH + hash2;
int index = hash1;
int i = 1;
while (charIndexTable[index] != 0 && charIndexTable[index] != c
&& i < PRIME_INDEX_LENGTH) {
index = (hash1 + i * hash2) % PRIME_INDEX_LENGTH;
i++;
}
if (i < PRIME_INDEX_LENGTH && charIndexTable[index] == c) {
return (short) index;
} else
return -1;
}
/**
* Look up the text string corresponding with the word char array,
* and return the position of the word list.
*
* @param knownHashIndex already figure out position of the first word
* symbol charArray[0] in hash table. If not calculated yet, can be
* replaced with function int findInTable(char[] charArray).
* @param charArray look up the char array corresponding with the word.
* @return word location in word array. If not found, then return -1.
*/
private int findInTable(short knownHashIndex, char[] charArray) {
if (charArray == null || charArray.length == 0)
return -1;
char[][] items = wordItem_charArrayTable[wordIndexTable[knownHashIndex]];
int start = 0, end = items.length - 1;
int mid = (start + end) / 2, cmpResult;
// Binary search for the index of idArray
while (start <= end) {
cmpResult = Utility.compareArray(items[mid], 0, charArray, 1);
if (cmpResult == 0)
return mid;// find it
else if (cmpResult < 0)
start = mid + 1;
else if (cmpResult > 0)
end = mid - 1;
mid = (start + end) / 2;
}
return -1;
}
/**
* Find the first word in the dictionary that starts with the supplied prefix
*
* @see #getPrefixMatch(char[], int)
* @param charArray input prefix
* @return index of word, or -1 if not found
*/
public int getPrefixMatch(char[] charArray) {
return getPrefixMatch(charArray, 0);
}
/**
* Find the nth word in the dictionary that starts with the supplied prefix
*
* @see #getPrefixMatch(char[])
* @param charArray input prefix
* @param knownStart relative position in the dictionary to start
* @return index of word, or -1 if not found
*/
public int getPrefixMatch(char[] charArray, int knownStart) {
short index = getWordItemTableIndex(charArray[0]);
if (index == -1)
return -1;
char[][] items = wordItem_charArrayTable[wordIndexTable[index]];
int start = knownStart, end = items.length - 1;
int mid = (start + end) / 2, cmpResult;
// Binary search for the index of idArray
while (start <= end) {
cmpResult = Utility.compareArrayByPrefix(charArray, 1, items[mid], 0);
if (cmpResult == 0) {
// Get the first item which match the current word
while (mid >= 0
&& Utility.compareArrayByPrefix(charArray, 1, items[mid], 0) == 0)
mid--;
mid++;
return mid;// Find the first word that uses charArray as prefix.
} else if (cmpResult < 0)
end = mid - 1;
else
start = mid + 1;
mid = (start + end) / 2;
}
return -1;
}
/**
* Get the frequency of a word from the dictionary
*
* @param charArray input word
* @return word frequency, or zero if the word is not found
*/
public int getFrequency(char[] charArray) {
short hashIndex = getWordItemTableIndex(charArray[0]);
if (hashIndex == -1)
return 0;
int itemIndex = findInTable(hashIndex, charArray);
if (itemIndex != -1)
return wordItem_frequencyTable[wordIndexTable[hashIndex]][itemIndex];
return 0;
}
/**
* Return true if the dictionary entry at itemIndex for table charArray[0] is charArray
*
* @param charArray input word
* @param itemIndex item index for table charArray[0]
* @return true if the entry exists
*/
public boolean isEqual(char[] charArray, int itemIndex) {
short hashIndex = getWordItemTableIndex(charArray[0]);
return Utility.compareArray(charArray, 1,
wordItem_charArrayTable[wordIndexTable[hashIndex]][itemIndex], 0) == 0;
}
}
| yida-lxw/solr-5.3.1 | lucene/analysis/smartcn/src/java/org/apache/lucene/analysis/cn/smart/hhmm/WordDictionary.java | Java | apache-2.0 | 18,324 |
/*
* Copyright 2012 JBoss Inc
*
* 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.
*/
package org.uberfire.java.nio.fs.jgit;
import static org.fest.assertions.api.Assertions.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jgit.util.FileUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class NewProviderDefineDirTest {
protected static final Map<String, Object> EMPTY_ENV = Collections.emptyMap();
private static final List<File> tempFiles = new ArrayList<File>();
protected static File createTempDirectory()
throws IOException {
final File temp = File.createTempFile("temp", Long.toString(System.nanoTime()));
if (!(temp.delete())) {
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
}
if (!(temp.mkdir())) {
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
}
tempFiles.add(temp);
return temp;
}
@AfterClass
@BeforeClass
public static void cleanup() {
for (final File tempFile : tempFiles) {
try {
FileUtils.delete(tempFile, FileUtils.RECURSIVE);
} catch (IOException e) {
}
}
}
@Test
@Ignore
public void testUsingProvidedPath() throws IOException {
final File dir = createTempDirectory();
Map<String, String> gitPrefs = new HashMap<String, String>();
gitPrefs.put( "org.uberfire.nio.git.dir", dir.toString() );
final JGitFileSystemProvider provider = new JGitFileSystemProvider( gitPrefs );
final URI newRepo = URI.create("git://repo-name");
provider.newFileSystem(newRepo, EMPTY_ENV);
final String[] names = dir.list();
assertThat(names).isNotEmpty().contains(".niogit");
final String[] repos = new File(dir, ".niogit").list();
assertThat(repos).isNotEmpty().contains("repo-name.git");
}
}
| Rikkola/uberfire | uberfire-nio2-backport/uberfire-nio2-impls/uberfire-nio2-jgit/src/test/java/org/uberfire/java/nio/fs/jgit/NewProviderDefineDirTest.java | Java | apache-2.0 | 2,722 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<link rel="Stylesheet" href="../css/analysis.css" />
<script type="text/javascript">
function init() {
if (window.location.hash) {
var parentDiv, nodes, i, helpId;
helpId = window.location.hash.substring(1);
parentDiv = document.getElementById("topics");
nodes = parentDiv.children;
for(i=0; i < nodes.length; i++) {
if(nodes[i].id !== helpId) {
nodes[i].style.display ="none";
}
}
}
}
</script>
</head>
<body onload="init()">
<div id="topics">
<div id="toolDescription" class="largesize">
<h2>Yhdistä karttatasot</h2><p/>
<h2><img src="../images/GUID-DACDAC49-3ECE-45A2-AC42-69016B3B8ADA-web.png" alt="Yhdistä karttatasot"></h2>
<hr/>
<p>Toiminto kopioi kahden eri tason kohteet uuteen tasoon. Yhdistettävien tasojen on sisällettävä samat kohdetyypit (pisteet, viivat tai alueet). Voit määrittää, miten lähtötason kentät yhdistetään ja kopioidaan. Esimerkki:
<ul>
<li>Haluan yhdistää tasot Englanti, Wales ja Skotlanti yhdeksi Iso-Britannia-nimiseksi tasoksi.
</li>
<li>Minulla on 12 tasoa, ja jokainen sisältää kaupunkien katkeamattomat kiinteistötiedot. Haluan yhdistää ne yhdeksi tasoksi ja säilyttää vain sellaiset tasot, joilla on sama nimi ja tyyppi 12 lähtötasossa.
</li>
</ul>
</p>
<p>Jos vaihtoehto <b>Käytä nykyistä karttalaajuutta</b> on valittuna, toiminto yhdistää vain nykyisessä kartassa näkyvissä olevat kohteet. Jos vaihtoehto ei ole valittuna, kummankin tason kaikki kohteet yhdistetään, vaikka ne eivät kuuluisi karttalaajuuteen.
</p>
</div>
<!--Parameter divs for each param-->
<div id="MergeLayer">
<div><h2>Valitse taso</h2></div>
<hr/>
<div>
<p>Valitse taso, joka yhdistetään analyysitasoon.
</p>
</div>
</div>
<div id="MergingAttributes">
<div><h2>Muokkaa yhdistämiskenttiä</h2></div>
<hr/>
<div>
<p>Oletusasetuksen mukaan tulosaineistoon siirtyvät kummankin lähtötason kaikki kentät. Kenttien siirtymistä tulosaineistoon voi muuttaa seuraavasti:
<ul>
<li> <b>Nimeä uudelleen</b>—Nimeää kentän uudelleen tulosaineistossa.
</li>
<li> <b>Poista</b>—Poistaa kentän tulosaineistosta.
</li>
<li> <b>Täsmää</b>—Muuttaa kenttien nimet samoiksi. Yhdistettävän tason kentän arvot kopioidaan täsmäytettyyn tuloskenttään.
</li>
</ul>
</p>
</div>
</div>
<div id="OutputName">
<div><h2>Tulostason nimi</h2></div>
<hr/>
<div>
<p>Sen tason nimi, joka luodaan kohtaan <b>Oma sisältö</b> ja joka lisätään karttaan. Oletusnimi perustuu analyysitason nimeen. Jos taso on jo olemassa, näyttöön tulee kehotus vahvistaa tason korvaus.
</p>
<p>Avattavan <b>Tallenna tulos kohteeseen</b> -valikon avulla voit määrittää sen <b>Oma sisältö</b> -kansion nimen, johon tulos tallennetaan.
</p>
</div>
</div>
</div>
</html>
| aconyteds/Esri-Ozone-Map-Widget | vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/esri/dijit/analysis/help/fi/MergeLayers.html | HTML | apache-2.0 | 3,869 |
/*
* 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.
*/
package org.apache.ignite.spi.discovery.tcp.ipfinder.multicast;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.IgniteInterruptedCheckedException;
import org.apache.ignite.internal.util.tostring.GridToStringExclude;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.LT;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.marshaller.jdk.JdkMarshaller;
import org.apache.ignite.resources.LoggerResource;
import org.apache.ignite.spi.IgniteSpiConfiguration;
import org.apache.ignite.spi.IgniteSpiContext;
import org.apache.ignite.spi.IgniteSpiException;
import org.apache.ignite.spi.IgniteSpiThread;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.jetbrains.annotations.Nullable;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_OVERRIDE_MCAST_GRP;
import static org.apache.ignite.spi.IgnitePortProtocol.UDP;
/**
* Multicast-based IP finder.
* <p>
* When TCP discovery starts this finder sends multicast request and waits
* for some time when others nodes reply to this request with messages containing
* their addresses (time IP finder waits for response and number of attempts to
* re-send multicast request in case if no replies are received can be configured,
* see {@link #setResponseWaitTime(int)} and {@link #setAddressRequestAttempts(int)}).
* <p>
* In addition to address received via multicast this finder can work with pre-configured
* list of addresses specified via {@link #setAddresses(Collection)} method.
* <h1 class="header">Configuration</h1>
* <h2 class="header">Mandatory</h2>
* There are no mandatory configuration parameters.
* <h2 class="header">Optional</h2>
* <ul>
* <li>Multicast IP address (see {@link #setMulticastGroup(String)}).</li>
* <li>Multicast port number (see {@link #setMulticastPort(int)}).</li>
* <li>Address response wait time (see {@link #setResponseWaitTime(int)}).</li>
* <li>Address request attempts (see {@link #setAddressRequestAttempts(int)}).</li>
* <li>Pre-configured addresses (see {@link #setAddresses(Collection)})</li>
* <li>Local address (see {@link #setLocalAddress(String)})</li>
* </ul>
*/
public class TcpDiscoveryMulticastIpFinder extends TcpDiscoveryVmIpFinder {
/** Default multicast IP address (value is {@code 228.1.2.4}). */
public static final String DFLT_MCAST_GROUP = "228.1.2.4";
/** Default multicast port number (value is {@code 47400}). */
public static final int DFLT_MCAST_PORT = 47400;
/** Default time IP finder waits for reply to multicast address request (value is {@code 500}). */
public static final int DFLT_RES_WAIT_TIME = 500;
/** Default number of attempts to send multicast address request (value is {@code 2}). */
public static final int DFLT_ADDR_REQ_ATTEMPTS = 2;
/** Address request message data. */
private static final byte[] MSG_ADDR_REQ_DATA = U.IGNITE_HEADER;
/** */
private static final Marshaller marsh = new JdkMarshaller();
/** Grid logger. */
@LoggerResource
private IgniteLogger log;
/** Multicast IP address as string. */
private String mcastGrp = DFLT_MCAST_GROUP;
/** Multicast port number. */
private int mcastPort = DFLT_MCAST_PORT;
/** Time IP finder waits for reply to multicast address request. */
private int resWaitTime = DFLT_RES_WAIT_TIME;
/** Number of attempts to send multicast address request. */
private int addrReqAttempts = DFLT_ADDR_REQ_ATTEMPTS;
/** Local address */
private String locAddr;
/** Time to live. */
private int ttl = -1;
/** */
@GridToStringExclude
private Collection<AddressSender> addrSnds;
/** */
@GridToStringExclude
private InetAddress mcastAddr;
/** Interfaces used to send requests. */
@GridToStringExclude
private Set<InetAddress> reqItfs;
/** */
private boolean firstReq;
/** */
private boolean mcastErr;
/** */
@GridToStringExclude
private Set<InetSocketAddress> locNodeAddrs;
/**
* Constructs new IP finder.
*/
public TcpDiscoveryMulticastIpFinder() {
setShared(true);
}
/**
* Sets IP address of multicast group.
* <p>
* If not provided, default value is {@link #DFLT_MCAST_GROUP}.
*
* @param mcastGrp Multicast IP address.
* @return {@code this} for chaining.
*/
@IgniteSpiConfiguration(optional = true)
public TcpDiscoveryMulticastIpFinder setMulticastGroup(String mcastGrp) {
this.mcastGrp = mcastGrp;
return this;
}
/**
* Gets IP address of multicast group.
*
* @return Multicast IP address.
*/
public String getMulticastGroup() {
return mcastGrp;
}
/**
* Sets port number which multicast messages are sent to.
* <p>
* If not provided, default value is {@link #DFLT_MCAST_PORT}.
*
* @param mcastPort Multicast port number.
* @return {@code this} for chaining.
*/
@IgniteSpiConfiguration(optional = true)
public TcpDiscoveryMulticastIpFinder setMulticastPort(int mcastPort) {
this.mcastPort = mcastPort;
return this;
}
/**
* Gets port number which multicast messages are sent to.
*
* @return Port number.
*/
public int getMulticastPort() {
return mcastPort;
}
/**
* Sets time in milliseconds IP finder waits for reply to
* multicast address request.
* <p>
* If not provided, default value is {@link #DFLT_RES_WAIT_TIME}.
*
* @param resWaitTime Time IP finder waits for reply to multicast address request.
* @return {@code this} for chaining.
*/
@IgniteSpiConfiguration(optional = true)
public TcpDiscoveryMulticastIpFinder setResponseWaitTime(int resWaitTime) {
this.resWaitTime = resWaitTime;
return this;
}
/**
* Gets time in milliseconds IP finder waits for reply to
* multicast address request.
*
* @return Time IP finder waits for reply to multicast address request.
*/
public int getResponseWaitTime() {
return resWaitTime;
}
/**
* Sets number of attempts to send multicast address request. IP finder re-sends
* request only in case if no reply for previous request is received.
* <p>
* If not provided, default value is {@link #DFLT_ADDR_REQ_ATTEMPTS}.
*
* @param addrReqAttempts Number of attempts to send multicast address request.
* @return {@code this} for chaining.
*/
@IgniteSpiConfiguration(optional = true)
public TcpDiscoveryMulticastIpFinder setAddressRequestAttempts(int addrReqAttempts) {
this.addrReqAttempts = addrReqAttempts;
return this;
}
/**
* Gets number of attempts to send multicast address request. IP finder re-sends
* request only in case if no reply for previous request is received.
*
* @return Number of attempts to send multicast address request.
*/
public int getAddressRequestAttempts() {
return addrReqAttempts;
}
/**
* Sets local host address used by this IP finder. If provided address is non-loopback then multicast
* socket is bound to this interface. If local address is not set or is any local address then IP finder
* creates multicast sockets for all found non-loopback addresses.
* <p>
* If not provided then this property is initialized by the local address set in
* {@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi} configuration.
*
* @param locAddr Local host address.
* @see org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi#setLocalAddress(String)
* @return {@code this} for chaining.
*/
@IgniteSpiConfiguration(optional = true)
public TcpDiscoveryMulticastIpFinder setLocalAddress(String locAddr) {
this.locAddr = locAddr;
return this;
}
/**
* Gets local address that multicast IP finder uses.
*
* @return Local address.
*/
public String getLocalAddress() {
return locAddr;
}
/**
* Set the default time-to-live for multicast packets sent out on this
* IP finder in order to control the scope of the multicast.
* <p>
* The TTL has to be in the range {@code 0 <= TTL <= 255}.
* <p>
* If TTL is {@code 0}, packets are not transmitted on the network,
* but may be delivered locally.
* <p>
* Default value is {@code -1} which corresponds to system default value.
*
* @param ttl Time to live.
* @return {@code this} for chaining.
*/
@IgniteSpiConfiguration(optional = true)
public TcpDiscoveryMulticastIpFinder setTimeToLive(int ttl) {
this.ttl = ttl;
return this;
}
/**
* Set the default time-to-live for multicast packets sent out on this
* IP finder.
*
* @return Time to live.
*/
public int getTimeToLive() {
return ttl;
}
/** {@inheritDoc} */
@Override public void initializeLocalAddresses(Collection<InetSocketAddress> addrs) throws IgniteSpiException {
if (F.isEmpty(super.getRegisteredAddresses()))
U.warn(log, "TcpDiscoveryMulticastIpFinder has no pre-configured addresses " +
"(it is recommended in production to specify at least one address in " +
"TcpDiscoveryMulticastIpFinder.getAddresses() configuration property)");
Collection<InetAddress> locAddrs = resolveLocalAddresses();
addrSnds = new ArrayList<>(locAddrs.size());
reqItfs = new HashSet<>(U.capacity(locAddrs.size())); // Interfaces used to send requests.
for (InetAddress addr : locAddrs) {
try {
addrSnds.add(new AddressSender(mcastAddr, addr, addrs));
reqItfs.add(addr);
}
catch (IOException e) {
if (log.isDebugEnabled())
log.debug("Failed to create multicast socket [mcastAddr=" + mcastAddr +
", mcastGrp=" + mcastGrp + ", mcastPort=" + mcastPort + ", locAddr=" + addr +
", err=" + e + ']');
}
}
locNodeAddrs = new HashSet<>(addrs);
if (addrSnds.isEmpty()) {
try {
// Create non-bound socket if local host is loopback or failed to create sockets explicitly
// bound to interfaces.
addrSnds.add(new AddressSender(mcastAddr, null, addrs));
}
catch (IOException e) {
if (log.isDebugEnabled())
log.debug("Failed to create multicast socket [mcastAddr=" + mcastAddr +
", mcastGrp=" + mcastGrp + ", mcastPort=" + mcastPort + ", err=" + e + ']');
}
if (addrSnds.isEmpty()) {
try {
addrSnds.add(new AddressSender(mcastAddr, mcastAddr, addrs));
reqItfs.add(mcastAddr);
}
catch (IOException e) {
if (log.isDebugEnabled())
log.debug("Failed to create multicast socket [mcastAddr=" + mcastAddr +
", mcastGrp=" + mcastGrp + ", mcastPort=" + mcastPort + ", locAddr=" + mcastAddr +
", err=" + e + ']');
}
}
}
if (!addrSnds.isEmpty()) {
for (AddressSender addrSnd : addrSnds)
addrSnd.start();
}
else
mcastErr = true;
}
/** {@inheritDoc} */
@Override public void onSpiContextInitialized(IgniteSpiContext spiCtx) throws IgniteSpiException {
super.onSpiContextInitialized(spiCtx);
spiCtx.registerPort(mcastPort, UDP);
}
/** {@inheritDoc} */
@Override public synchronized Collection<InetSocketAddress> getRegisteredAddresses() {
if (mcastAddr == null)
reqItfs = new HashSet<>(resolveLocalAddresses());
if (mcastAddr != null && reqItfs != null) {
Collection<InetSocketAddress> ret;
if (reqItfs.size() > 1)
ret = requestAddresses(reqItfs);
else {
T2<Collection<InetSocketAddress>, Boolean> res = requestAddresses(mcastAddr, F.first(reqItfs));
ret = res.get1();
mcastErr |= res.get2();
}
if (ret.isEmpty()) {
if (mcastErr && firstReq) {
if (super.getRegisteredAddresses().isEmpty()) {
InetSocketAddress addr = new InetSocketAddress("localhost", TcpDiscoverySpi.DFLT_PORT);
U.quietAndWarn(log, "TcpDiscoveryMulticastIpFinder failed to initialize multicast, " +
"will use default address: " + addr);
registerAddresses(Collections.singleton(addr));
}
else
U.quietAndWarn(log, "TcpDiscoveryMulticastIpFinder failed to initialize multicast, " +
"will use pre-configured addresses.");
}
}
else
registerAddresses(ret);
firstReq = false;
}
return super.getRegisteredAddresses();
}
/**
* Resolve local addresses.
*
* @return List of non-loopback addresses.
*/
private Collection<InetAddress> resolveLocalAddresses() {
// If IGNITE_OVERRIDE_MCAST_GRP system property is set, use its value to override multicast group from
// configuration. Used for testing purposes.
String overrideMcastGrp = System.getProperty(IGNITE_OVERRIDE_MCAST_GRP);
if (overrideMcastGrp != null)
mcastGrp = overrideMcastGrp;
if (F.isEmpty(mcastGrp))
throw new IgniteSpiException("Multicast IP address is not specified.");
if (mcastPort < 0 || mcastPort > 65535)
throw new IgniteSpiException("Invalid multicast port: " + mcastPort);
if (resWaitTime <= 0)
throw new IgniteSpiException("Invalid wait time, value greater than zero is expected: " + resWaitTime);
if (addrReqAttempts <= 0)
throw new IgniteSpiException("Invalid number of address request attempts, " +
"value greater than zero is expected: " + addrReqAttempts);
if (ttl != -1 && (ttl < 0 || ttl > 255))
throw new IgniteSpiException("Time-to-live value is out of 0 <= TTL <= 255 range: " + ttl);
try {
mcastAddr = InetAddress.getByName(mcastGrp);
}
catch (UnknownHostException e) {
throw new IgniteSpiException("Unknown multicast group: " + mcastGrp, e);
}
if (!mcastAddr.isMulticastAddress())
throw new IgniteSpiException("Invalid multicast group address: " + mcastAddr);
Collection<String> locAddrs;
try {
locAddrs = U.resolveLocalAddresses(U.resolveLocalHost(locAddr)).get1();
}
catch (IOException e) {
throw new IgniteSpiException("Failed to resolve local addresses [locAddr=" + locAddr + ']', e);
}
assert locAddrs != null;
List<InetAddress> inetAddrs = new ArrayList<>(locAddrs.size());
for (String locAddr : locAddrs) {
InetAddress addr;
try {
addr = InetAddress.getByName(locAddr);
}
catch (UnknownHostException e) {
if (log.isDebugEnabled())
log.debug("Failed to resolve local address [locAddr=" + locAddr + ", err=" + e + ']');
continue;
}
if (!addr.isLoopbackAddress())
inetAddrs.add(addr);
}
return inetAddrs;
}
/**
* @param reqItfs Interfaces used to send requests.
* @return Addresses.
*/
private Collection<InetSocketAddress> requestAddresses(Set<InetAddress> reqItfs) {
if (reqItfs.size() > 1) {
Collection<InetSocketAddress> ret = new HashSet<>();
Collection<AddressReceiver> rcvrs = new ArrayList<>();
for (InetAddress itf : reqItfs) {
AddressReceiver rcvr = new AddressReceiver(mcastAddr, itf);
rcvr.start();
rcvrs.add(rcvr);
}
for (AddressReceiver rcvr : rcvrs) {
try {
rcvr.join();
ret.addAll(rcvr.addresses());
}
catch (InterruptedException ignore) {
U.warn(log, "Got interrupted while receiving address request.");
Thread.currentThread().interrupt();
break;
}
}
return ret;
}
else {
T2<Collection<InetSocketAddress>, Boolean> res = requestAddresses(mcastAddr, F.first(reqItfs));
return res.get1();
}
}
/**
* Sends multicast address request message and waits for reply. Response wait time and number
* of request attempts are configured as properties {@link #setResponseWaitTime} and
* {@link #setAddressRequestAttempts}.
*
* @param mcastAddr Multicast address where to send request.
* @param sockItf Optional interface multicast socket should be bound to.
* @return Tuple where first value is collection of received addresses, second is boolean which is
* {@code true} if got error on send.
*/
private T2<Collection<InetSocketAddress>, Boolean> requestAddresses(InetAddress mcastAddr,
@Nullable InetAddress sockItf)
{
Collection<InetSocketAddress> rmtAddrs = new HashSet<>();
boolean sndErr = false;
try {
DatagramPacket reqPckt = new DatagramPacket(MSG_ADDR_REQ_DATA, MSG_ADDR_REQ_DATA.length,
mcastAddr, mcastPort);
byte[] resData = new byte[AddressResponse.MAX_DATA_LENGTH];
DatagramPacket resPckt = new DatagramPacket(resData, resData.length);
boolean sndError = false;
for (int i = 0; i < addrReqAttempts; i++) {
MulticastSocket sock = null;
try {
sock = new MulticastSocket(0);
// Use 'false' to enable support for more than one node on the same machine.
sock.setLoopbackMode(false);
if (sockItf != null)
sock.setInterface(sockItf);
sock.setSoTimeout(resWaitTime);
if (ttl != -1)
sock.setTimeToLive(ttl);
reqPckt.setData(MSG_ADDR_REQ_DATA);
try {
sock.send(reqPckt);
}
catch (IOException e) {
sndErr = true;
if (!handleNetworkError(e))
break;
if (i < addrReqAttempts - 1) {
if (log.isDebugEnabled())
log.debug("Failed to send multicast address request (will retry in 500 ms): " + e);
U.sleep(500);
}
else {
if (log.isDebugEnabled())
log.debug("Failed to send multicast address request: " + e);
}
sndError = true;
continue;
}
long rcvStartNanos = System.nanoTime();
try {
while (U.millisSinceNanos(rcvStartNanos) < resWaitTime) { // Try to receive multiple responses.
sock.receive(resPckt);
byte[] data = resPckt.getData();
if (!U.bytesEqual(U.IGNITE_HEADER, 0, data, 0, U.IGNITE_HEADER.length)) {
U.error(log, "Failed to verify message header.");
continue;
}
AddressResponse addrRes;
try {
addrRes = new AddressResponse(data);
}
catch (IgniteCheckedException e) {
LT.error(log, e, "Failed to deserialize multicast response.");
continue;
}
rmtAddrs.addAll(addrRes.addresses());
}
}
catch (SocketTimeoutException ignored) {
if (log.isDebugEnabled()) // DatagramSocket.receive timeout has expired.
log.debug("Address receive timeout.");
}
}
catch (IOException e) {
U.error(log, "Failed to request nodes addresses.", e);
}
finally {
U.close(sock);
}
if (i < addrReqAttempts - 1) // Wait some time before re-sending address request.
U.sleep(200);
}
if (log.isDebugEnabled())
log.debug("Received nodes addresses: " + rmtAddrs);
if (rmtAddrs.isEmpty() && sndError)
U.quietAndWarn(log, "Failed to send multicast message (is multicast enabled on this node?).");
return new T2<>(rmtAddrs, sndErr);
}
catch (IgniteInterruptedCheckedException ignored) {
U.warn(log, "Got interrupted while sending address request.");
Thread.currentThread().interrupt();
return new T2<>(rmtAddrs, sndErr);
}
}
/** {@inheritDoc} */
@Override public void close() {
if (addrSnds != null) {
for (AddressSender addrSnd : addrSnds)
U.interrupt(addrSnd);
for (AddressSender addrSnd : addrSnds)
U.join(addrSnd, log);
}
}
/**
* @param e Network error to handle.
* @return {@code True} if this error is recoverable and the operation can be retried.
*/
private boolean handleNetworkError(IOException e) {
if ("Network is unreachable".equals(e.getMessage()) && U.isMacOs()) {
U.warn(log, "Multicast does not work on Mac OS JVM loopback address (configure external IP address " +
"for 'localHost' configuration property)");
return false;
}
return true;
}
/** {@inheritDoc} */
@Override public TcpDiscoveryMulticastIpFinder setShared(boolean shared) {
super.setShared(shared);
return this;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(TcpDiscoveryMulticastIpFinder.class, this, "super", super.toString());
}
/**
* Response to multicast address request.
*/
private static class AddressResponse {
/** Maximum supported multicast message. */
public static final int MAX_DATA_LENGTH = 64 * 1024;
/** */
private byte[] data;
/** */
private Collection<InetSocketAddress> addrs;
/**
* @param addrs Addresses discovery SPI binds to.
* @throws IgniteCheckedException If marshalling failed.
*/
private AddressResponse(Collection<InetSocketAddress> addrs) throws IgniteCheckedException {
this.addrs = addrs;
byte[] addrsData = U.marshal(marsh, addrs);
data = new byte[U.IGNITE_HEADER.length + addrsData.length];
if (data.length > MAX_DATA_LENGTH)
throw new IgniteCheckedException("Too long data packet [size=" + data.length + ", max=" + MAX_DATA_LENGTH + "]");
System.arraycopy(U.IGNITE_HEADER, 0, data, 0, U.IGNITE_HEADER.length);
System.arraycopy(addrsData, 0, data, 4, addrsData.length);
}
/**
* @param data Message data.
* @throws IgniteCheckedException If unmarshalling failed.
*/
private AddressResponse(byte[] data) throws IgniteCheckedException {
assert U.bytesEqual(U.IGNITE_HEADER, 0, data, 0, U.IGNITE_HEADER.length);
this.data = data;
addrs = U.unmarshal(marsh, Arrays.copyOfRange(data, U.IGNITE_HEADER.length, data.length), null);
}
/**
* @return Message data.
*/
byte[] data() {
return data;
}
/**
* @return IP address discovery SPI binds to.
*/
public Collection<InetSocketAddress> addresses() {
return addrs;
}
}
/**
* Thread sends multicast address request message and waits for reply.
*/
private class AddressReceiver extends IgniteSpiThread {
/** */
private final InetAddress mcastAddr;
/** */
private final InetAddress sockAddr;
/** */
private Collection<InetSocketAddress> addrs;
/**
* @param mcastAddr Multicast address where to send request.
* @param sockAddr Optional address multicast socket should be bound to.
*/
private AddressReceiver(InetAddress mcastAddr, InetAddress sockAddr) {
super(null, "tcp-disco-multicast-addr-rcvr", log);
this.mcastAddr = mcastAddr;
this.sockAddr = sockAddr;
}
/** {@inheritDoc} */
@Override protected void body() throws InterruptedException {
addrs = requestAddresses(mcastAddr, sockAddr).get1();
}
/**
* @return Received addresses.
*/
Collection<InetSocketAddress> addresses() {
return addrs;
}
}
/**
* Thread listening for multicast address requests and sending response
* containing socket address this node's discovery SPI listens to.
*/
private class AddressSender extends IgniteSpiThread {
/** */
private MulticastSocket sock;
/** */
private final InetAddress mcastGrp;
/** */
private final Collection<InetSocketAddress> addrs;
/** */
private final InetAddress sockItf;
/**
* @param mcastGrp Multicast address.
* @param sockItf Optional interface multicast socket should be bound to.
* @param addrs Local node addresses.
* @throws IOException If fails to create multicast socket.
*/
private AddressSender(InetAddress mcastGrp, @Nullable InetAddress sockItf, Collection<InetSocketAddress> addrs)
throws IOException {
super(null, "tcp-disco-multicast-addr-sender", log);
this.mcastGrp = mcastGrp;
this.addrs = addrs;
this.sockItf = sockItf;
sock = createSocket();
}
/**
* Creates multicast socket and joins multicast group.
*
* @throws IOException If fails to create socket or join multicast group.
* @return Multicast socket.
*/
private MulticastSocket createSocket() throws IOException {
MulticastSocket sock = new MulticastSocket(mcastPort);
sock.setLoopbackMode(false); // Use 'false' to enable support for more than one node on the same machine.
if (sockItf != null)
sock.setInterface(sockItf);
if (sock.getLoopbackMode())
U.warn(log, "Loopback mode is disabled which prevents nodes on the same machine from discovering " +
"each other.");
sock.joinGroup(mcastGrp);
if (ttl != -1)
sock.setTimeToLive(ttl);
return sock;
}
/** {@inheritDoc} */
@Override protected void body() throws InterruptedException {
AddressResponse res;
try {
res = new AddressResponse(addrs);
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to prepare multicast message.", e);
return;
}
byte[] reqData = new byte[MSG_ADDR_REQ_DATA.length];
DatagramPacket pckt = new DatagramPacket(reqData, reqData.length);
while (!isInterrupted()) {
try {
MulticastSocket sock;
synchronized (this) {
if (isInterrupted())
return;
sock = this.sock;
if (sock == null)
sock = createSocket();
}
sock.receive(pckt);
if (!U.bytesEqual(U.IGNITE_HEADER, 0, reqData, 0, U.IGNITE_HEADER.length)) {
U.error(log, "Failed to verify message header.");
continue;
}
try {
sock.send(new DatagramPacket(res.data(), res.data().length, pckt.getAddress(), pckt.getPort()));
}
catch (IOException e) {
if (e.getMessage().contains("Operation not permitted")) {
if (log.isDebugEnabled())
log.debug("Got 'operation not permitted' error, ignoring: " + e);
}
else
throw e;
}
}
catch (IOException e) {
if (!isInterrupted()) {
LT.error(log, e, "Failed to send/receive address message (will try to reconnect).");
synchronized (this) {
U.close(sock);
sock = null;
}
}
}
}
}
/** {@inheritDoc} */
@Override public void interrupt() {
super.interrupt();
synchronized (this) {
U.close(sock);
sock = null;
}
}
/** {@inheritDoc} */
@Override protected void cleanup() {
synchronized (this) {
U.close(sock);
sock = null;
}
}
}
}
| ascherbakoff/ignite | modules/core/src/main/java/org/apache/ignite/spi/discovery/tcp/ipfinder/multicast/TcpDiscoveryMulticastIpFinder.java | Java | apache-2.0 | 32,246 |
//>>built
define("dojox/xmpp/UserService",["dijit","dojo","dojox"],function(h,e,c){e.provide("dojox.xmpp.UserService");e.declare("dojox.xmpp.UserService",null,{constructor:function(a){this.session=a},getPersonalProfile:function(){var a={id:this.session.getNextIqId(),type:"get"},d=new c.string.Builder(c.xmpp.util.createElement("iq",a,!1));d.append(c.xmpp.util.createElement("query",{xmlns:"jabber:iq:private"},!1));d.append(c.xmpp.util.createElement("sunmsgr",{xmlsns:"sun:xmpp:properties"},!0));d.append("\x3c/query\x3e\x3c/iq\x3e");
this.session.dispatchPacket(d.toString(),"iq",a.id).addCallback(this,"_onGetPersonalProfile")},setPersonalProfile:function(a){var d={id:this.session.getNextIqId(),type:"set"},b=new c.string.Builder(c.xmpp.util.createElement("iq",d,!1));b.append(c.xmpp.util.createElement("query",{xmlns:"jabber:iq:private"},!1));b.append(c.xmpp.util.createElement("sunmsgr",{xmlsns:"sun:xmpp:properties"},!1));for(var g in a)b.append(c.xmpp.util.createElement("property",{name:g},!1)),b.append(c.xmpp.util.createElement("value",
{},!1)),b.append(a[g]),b.append("\x3c/value\x3e\x3c/props\x3e");b.append("\x3c/sunmsgr\x3e\x3c/query\x3e\x3c/iq\x3e");this.session.dispatchPacket(b.toString(),"iq",d.id).addCallback(this,"_onSetPersonalProfile")},_onSetPersonalProfile:function(a){if("result"==a.getAttribute("type"))this.onSetPersonalProfile(a.getAttribute("id"));else"error"==a.getAttribute("type")&&(a=this.session.processXmppError(a),this.onSetPersonalProfileFailure(a))},onSetPersonalProfile:function(a){},onSetPersonalProfileFailure:function(a){},
_onGetPersonalProfile:function(a){if("result"==a.getAttribute("type")){var d={};if(a.hasChildNodes()){var b=a.firstChild;if("query"==b.nodeName&&"jabber:iq:private"==b.getAttribute("xmlns")&&(b=b.firstChild,"query"==b.nodeName&&"sun:xmpp:properties"==b.getAttributes("xmlns")))for(var c=0;c<b.childNodes.length;c++){var f=b.childNodes[c];if("property"==f.nodeName){var e=f.getAttribute("name");d[e]=f.firstChild||""}}this.onGetPersonalProfile(d)}}else"error"==a.getAttribute("type")&&(d=this.session.processXmppError(a),
this.onGetPersonalProfileFailure(d));return a},onGetPersonalProfile:function(a){},onGetPersonalProfileFailure:function(a){}})}); | aconyteds/Esri-Ozone-Map-Widget | vendor/js/esri/arcgis_js_api/library/3.12/3.12compact/dojox/xmpp/UserService.js | JavaScript | apache-2.0 | 2,217 |
/*
* 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.
*/
package org.apache.ignite.internal.visor.node;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.apache.ignite.DataStorageMetrics;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.visor.VisorDataTransferObject;
/**
* DTO object for {@link DataStorageMetrics}.
*/
public class VisorPersistenceMetrics extends VisorDataTransferObject {
/** */
private static final long serialVersionUID = 0L;
/** */
private float walLoggingRate;
/** */
private float walWritingRate;
/** */
private int walArchiveSegments;
/** */
private float walFsyncTimeAvg;
/** */
private long walBufPollSpinRate;
/** */
private long walSz;
/** */
private long walLastRollOverTm;
/** */
private long cpTotalTm;
/** */
private long lastCpDuration;
/** */
private long lastCpStart;
/** */
private long lastCpLockWaitDuration;
/** */
private long lastCpMmarkDuration;
/** */
private long lastCpPagesWriteDuration;
/** */
private long lastCpFsyncDuration;
/** */
private long lastCpTotalPages;
/** */
private long lastCpDataPages;
/** */
private long lastCpCowPages;
/** */
private long dirtyPages;
/** */
private long pagesRead;
/** */
private long pagesWritten;
/** */
private long pagesReplaced;
/** */
private long offHeapSz;
/** */
private long offheapUsedSz;
/** */
private long usedCpBufPages;
/** */
private long usedCpBufSz;
/** */
private long cpBufSz;
/** */
private long totalSz;
/** */
private long storageSize;
/** */
private long sparseStorageSize;
/**
* Default constructor.
*/
public VisorPersistenceMetrics() {
// No-op.
}
/**
* @param m Persistence metrics.
*/
public VisorPersistenceMetrics(DataStorageMetrics m) {
walLoggingRate = m.getWalLoggingRate();
walWritingRate = m.getWalWritingRate();
walArchiveSegments = m.getWalArchiveSegments();
walFsyncTimeAvg = m.getWalFsyncTimeAverage();
walBufPollSpinRate = m.getWalBuffPollSpinsRate();
walSz = m.getWalTotalSize();
walLastRollOverTm = m.getWalLastRollOverTime();
cpTotalTm = m.getCheckpointTotalTime();
lastCpDuration = m.getLastCheckpointDuration();
lastCpStart = m.getLastCheckpointStarted();
lastCpLockWaitDuration = m.getLastCheckpointLockWaitDuration();
lastCpMmarkDuration = m.getLastCheckpointMarkDuration();
lastCpPagesWriteDuration = m.getLastCheckpointPagesWriteDuration();
lastCpFsyncDuration = m.getLastCheckpointFsyncDuration();
lastCpTotalPages = m.getLastCheckpointTotalPagesNumber();
lastCpDataPages = m.getLastCheckpointDataPagesNumber();
lastCpCowPages = m.getLastCheckpointCopiedOnWritePagesNumber();
dirtyPages = m.getDirtyPages();
pagesRead = m.getPagesRead();
pagesWritten = m.getPagesWritten();
pagesReplaced = m.getPagesReplaced();
offHeapSz = m.getOffHeapSize();
offheapUsedSz = m.getOffheapUsedSize();
usedCpBufPages = m.getUsedCheckpointBufferPages();
usedCpBufSz = m.getUsedCheckpointBufferSize();
cpBufSz = m.getCheckpointBufferSize();
totalSz = m.getTotalAllocatedSize();
storageSize = m.getStorageSize();
sparseStorageSize = m.getSparseStorageSize();
}
/**
* @return Average number of WAL records per second written during the last time interval.
*/
public float getWalLoggingRate() {
return walLoggingRate;
}
/**
* @return Average number of bytes per second written during the last time interval.
*/
public float getWalWritingRate() {
return walWritingRate;
}
/**
* @return Current number of WAL segments in the WAL archive.
*/
public int getWalArchiveSegments() {
return walArchiveSegments;
}
/**
* @return Average WAL fsync duration in microseconds over the last time interval.
*/
public float getWalFsyncTimeAverage() {
return walFsyncTimeAvg;
}
/**
* @return WAL buffer poll spins number over the last time interval.
*/
public long getWalBuffPollSpinsRate() {
return walBufPollSpinRate;
}
/**
* @return Total size in bytes for storage WAL files.
*/
public long getWalTotalSize() {
return walSz;
}
/**
* @return Time of the last WAL segment rollover.
*/
public long getWalLastRollOverTime() {
return walLastRollOverTm;
}
/**
* @return Total checkpoint time from last restart.
*/
public long getCheckpointTotalTime() {
return cpTotalTm;
}
/**
* @return Total checkpoint duration in milliseconds.
*/
public long getLastCheckpointingDuration() {
return lastCpDuration;
}
/**
* Returns time when the last checkpoint was started.
*
* @return Time when the last checkpoint was started.
* */
public long getLastCheckpointStarted() {
return lastCpStart;
}
/**
* @return Checkpoint lock wait time in milliseconds.
*/
public long getLastCheckpointLockWaitDuration() {
return lastCpLockWaitDuration;
}
/**
* @return Checkpoint mark duration in milliseconds.
*/
public long getLastCheckpointMarkDuration() {
return lastCpMmarkDuration;
}
/**
* @return Checkpoint pages write phase in milliseconds.
*/
public long getLastCheckpointPagesWriteDuration() {
return lastCpPagesWriteDuration;
}
/**
* @return Checkpoint fsync time in milliseconds.
*/
public long getLastCheckpointFsyncDuration() {
return lastCpFsyncDuration;
}
/**
* @return Total number of pages written during the last checkpoint.
*/
public long getLastCheckpointTotalPagesNumber() {
return lastCpTotalPages;
}
/**
* @return Total number of data pages written during the last checkpoint.
*/
public long getLastCheckpointDataPagesNumber() {
return lastCpDataPages;
}
/**
* @return Total number of pages copied to a temporary checkpoint buffer during the last checkpoint.
*/
public long getLastCheckpointCopiedOnWritePagesNumber() {
return lastCpCowPages;
}
/**
* @return Total dirty pages for the next checkpoint.
*/
public long getDirtyPages() {
return dirtyPages;
}
/**
* @return The number of read pages from last restart.
*/
public long getPagesRead() {
return pagesRead;
}
/**
* @return The number of written pages from last restart.
*/
public long getPagesWritten() {
return pagesWritten;
}
/**
* @return The number of replaced pages from last restart.
*/
public long getPagesReplaced() {
return pagesReplaced;
}
/**
* @return Total offheap size in bytes.
*/
public long getOffHeapSize() {
return offHeapSz;
}
/**
* @return Total used offheap size in bytes.
*/
public long getOffheapUsedSize() {
return offheapUsedSz;
}
/**
* @return Checkpoint buffer size in pages.
*/
public long getUsedCheckpointBufferPages() {
return usedCpBufPages;
}
/**
* @return Checkpoint buffer size in bytes.
*/
public long getUsedCheckpointBufferSize() {
return usedCpBufSz;
}
/**
* @return Checkpoint buffer size in bytes.
*/
public long getCheckpointBufferSize() {
return cpBufSz;
}
/**
* @return Total size of memory allocated in bytes.
*/
public long getTotalAllocatedSize() {
return totalSz;
}
/**
* @return Storage space allocated in bytes.
*/
public long getStorageSize() {
return storageSize;
}
/**
* @return Storage space allocated adjusted for possible sparsity in bytes.
*/
public long getSparseStorageSize() {
return sparseStorageSize;
}
/** {@inheritDoc} */
@Override public byte getProtocolVersion() {
return V5;
}
/** {@inheritDoc} */
@Override protected void writeExternalData(ObjectOutput out) throws IOException {
out.writeFloat(walLoggingRate);
out.writeFloat(walWritingRate);
out.writeInt(walArchiveSegments);
out.writeFloat(walFsyncTimeAvg);
out.writeLong(lastCpDuration);
out.writeLong(lastCpLockWaitDuration);
out.writeLong(lastCpMmarkDuration);
out.writeLong(lastCpPagesWriteDuration);
out.writeLong(lastCpFsyncDuration);
out.writeLong(lastCpTotalPages);
out.writeLong(lastCpDataPages);
out.writeLong(lastCpCowPages);
// V2
out.writeLong(walBufPollSpinRate);
out.writeLong(walSz);
out.writeLong(walLastRollOverTm);
out.writeLong(cpTotalTm);
out.writeLong(dirtyPages);
out.writeLong(pagesRead);
out.writeLong(pagesWritten);
out.writeLong(pagesReplaced);
out.writeLong(offHeapSz);
out.writeLong(offheapUsedSz);
out.writeLong(usedCpBufPages);
out.writeLong(usedCpBufSz);
out.writeLong(cpBufSz);
out.writeLong(totalSz);
// V3
out.writeLong(storageSize);
out.writeLong(sparseStorageSize);
// V4
out.writeLong(lastCpStart);
}
/** {@inheritDoc} */
@Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
walLoggingRate = in.readFloat();
walWritingRate = in.readFloat();
walArchiveSegments = in.readInt();
walFsyncTimeAvg = in.readFloat();
lastCpDuration = in.readLong();
lastCpLockWaitDuration = in.readLong();
lastCpMmarkDuration = in.readLong();
lastCpPagesWriteDuration = in.readLong();
lastCpFsyncDuration = in.readLong();
lastCpTotalPages = in.readLong();
lastCpDataPages = in.readLong();
lastCpCowPages = in.readLong();
if (protoVer > V1) {
walBufPollSpinRate = in.readLong();
walSz = in.readLong();
walLastRollOverTm = in.readLong();
cpTotalTm = in.readLong();
dirtyPages = in.readLong();
pagesRead = in.readLong();
pagesWritten = in.readLong();
pagesReplaced = in.readLong();
offHeapSz = in.readLong();
offheapUsedSz = in.readLong();
usedCpBufPages = in.readLong();
usedCpBufSz = in.readLong();
cpBufSz = in.readLong();
totalSz = in.readLong();
}
if (protoVer > V2) {
storageSize = in.readLong();
sparseStorageSize = in.readLong();
}
if (protoVer > V3)
lastCpStart = in.readLong();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(VisorPersistenceMetrics.class, this);
}
}
| ascherbakoff/ignite | modules/core/src/main/java/org/apache/ignite/internal/visor/node/VisorPersistenceMetrics.java | Java | apache-2.0 | 12,132 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package source
import (
"context"
"fmt"
"go/ast"
"go/types"
"golang.org/x/tools/internal/span"
)
// ReferenceInfo holds information about reference to an identifier in Go source.
type ReferenceInfo struct {
Name string
Range span.Range
ident *ast.Ident
obj types.Object
}
// References returns a list of references for a given identifier within a package.
func (i *IdentifierInfo) References(ctx context.Context) ([]*ReferenceInfo, error) {
pkg := i.File.GetPackage(ctx)
if pkg == nil || pkg.IsIllTyped() {
return nil, fmt.Errorf("package for %s is ill typed", i.File.URI())
}
pkgInfo := pkg.GetTypesInfo()
if pkgInfo == nil {
return nil, fmt.Errorf("package %s has no types info", pkg.PkgPath())
}
// If the object declaration is nil, assume it is an import spec and do not look for references.
if i.decl.obj == nil {
return []*ReferenceInfo{}, nil
}
var references []*ReferenceInfo
if i.decl.wasImplicit {
// The definition is implicit, so we must add it separately.
// This occurs when the variable is declared in a type switch statement
// or is an implicit package name.
references = append(references, &ReferenceInfo{
Name: i.decl.obj.Name(),
Range: i.decl.rng,
obj: i.decl.obj,
})
}
for ident, obj := range pkgInfo.Defs {
if obj == nil || obj.Pos() != i.decl.obj.Pos() {
continue
}
references = append(references, &ReferenceInfo{
Name: ident.Name,
Range: span.NewRange(i.File.FileSet(), ident.Pos(), ident.End()),
ident: ident,
obj: obj,
})
}
for ident, obj := range pkgInfo.Uses {
if obj == nil || obj.Pos() != i.decl.obj.Pos() {
continue
}
references = append(references, &ReferenceInfo{
Name: ident.Name,
Range: span.NewRange(i.File.FileSet(), ident.Pos(), ident.End()),
ident: ident,
obj: obj,
})
}
return references, nil
}
| pweil-/origin | vendor/golang.org/x/tools/internal/lsp/source/references.go | GO | apache-2.0 | 2,014 |
//===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This header defines the BitstreamReader class. This class can be used to
// read an arbitrary bitstream, regardless of its contents.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_BITSTREAM_BITSTREAMREADER_H
#define LLVM_BITSTREAM_BITSTREAMREADER_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Bitstream/BitCodes.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace llvm {
/// This class maintains the abbreviations read from a block info block.
class BitstreamBlockInfo {
public:
/// This contains information emitted to BLOCKINFO_BLOCK blocks. These
/// describe abbreviations that all blocks of the specified ID inherit.
struct BlockInfo {
unsigned BlockID;
std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
std::string Name;
std::vector<std::pair<unsigned, std::string>> RecordNames;
};
private:
std::vector<BlockInfo> BlockInfoRecords;
public:
/// If there is block info for the specified ID, return it, otherwise return
/// null.
const BlockInfo *getBlockInfo(unsigned BlockID) const {
// Common case, the most recent entry matches BlockID.
if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
return &BlockInfoRecords.back();
for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
i != e; ++i)
if (BlockInfoRecords[i].BlockID == BlockID)
return &BlockInfoRecords[i];
return nullptr;
}
BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
if (const BlockInfo *BI = getBlockInfo(BlockID))
return *const_cast<BlockInfo*>(BI);
// Otherwise, add a new record.
BlockInfoRecords.emplace_back();
BlockInfoRecords.back().BlockID = BlockID;
return BlockInfoRecords.back();
}
};
/// This represents a position within a bitstream. There may be multiple
/// independent cursors reading within one bitstream, each maintaining their
/// own local state.
class SimpleBitstreamCursor {
ArrayRef<uint8_t> BitcodeBytes;
size_t NextChar = 0;
public:
/// This is the current data we have pulled from the stream but have not
/// returned to the client. This is specifically and intentionally defined to
/// follow the word size of the host machine for efficiency. We use word_t in
/// places that are aware of this to make it perfectly explicit what is going
/// on.
using word_t = size_t;
private:
word_t CurWord = 0;
/// This is the number of bits in CurWord that are valid. This is always from
/// [0...bits_of(size_t)-1] inclusive.
unsigned BitsInCurWord = 0;
public:
static const constexpr size_t MaxChunkSize = sizeof(word_t) * 8;
SimpleBitstreamCursor() = default;
explicit SimpleBitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
: BitcodeBytes(BitcodeBytes) {}
explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
: BitcodeBytes(arrayRefFromStringRef(BitcodeBytes)) {}
explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
: SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
bool canSkipToPos(size_t pos) const {
// pos can be skipped to if it is a valid address or one byte past the end.
return pos <= BitcodeBytes.size();
}
bool AtEndOfStream() {
return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
}
/// Return the bit # of the bit we are reading.
uint64_t GetCurrentBitNo() const {
return NextChar*CHAR_BIT - BitsInCurWord;
}
// Return the byte # of the current bit.
uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
ArrayRef<uint8_t> getBitcodeBytes() const { return BitcodeBytes; }
/// Reset the stream to the specified bit number.
Error JumpToBit(uint64_t BitNo) {
size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
assert(canSkipToPos(ByteNo) && "Invalid location");
// Move the cursor to the right word.
NextChar = ByteNo;
BitsInCurWord = 0;
// Skip over any bits that are already consumed.
if (WordBitNo) {
if (Expected<word_t> Res = Read(WordBitNo))
return Error::success();
else
return Res.takeError();
}
return Error::success();
}
/// Get a pointer into the bitstream at the specified byte offset.
const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
return BitcodeBytes.data() + ByteNo;
}
/// Get a pointer into the bitstream at the specified bit offset.
///
/// The bit offset must be on a byte boundary.
const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
assert(!(BitNo % 8) && "Expected bit on byte boundary");
return getPointerToByte(BitNo / 8, NumBytes);
}
Error fillCurWord() {
if (NextChar >= BitcodeBytes.size())
return createStringError(std::errc::io_error,
"Unexpected end of file reading %u of %u bytes",
NextChar, BitcodeBytes.size());
// Read the next word from the stream.
const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
unsigned BytesRead;
if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
BytesRead = sizeof(word_t);
CurWord =
support::endian::read<word_t, support::little, support::unaligned>(
NextCharPtr);
} else {
// Short read.
BytesRead = BitcodeBytes.size() - NextChar;
CurWord = 0;
for (unsigned B = 0; B != BytesRead; ++B)
CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
}
NextChar += BytesRead;
BitsInCurWord = BytesRead * 8;
return Error::success();
}
Expected<word_t> Read(unsigned NumBits) {
static const unsigned BitsInWord = MaxChunkSize;
assert(NumBits && NumBits <= BitsInWord &&
"Cannot return zero or more than BitsInWord bits!");
static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;
// If the field is fully contained by CurWord, return it quickly.
if (BitsInCurWord >= NumBits) {
word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
// Use a mask to avoid undefined behavior.
CurWord >>= (NumBits & Mask);
BitsInCurWord -= NumBits;
return R;
}
word_t R = BitsInCurWord ? CurWord : 0;
unsigned BitsLeft = NumBits - BitsInCurWord;
if (Error fillResult = fillCurWord())
return std::move(fillResult);
// If we run out of data, abort.
if (BitsLeft > BitsInCurWord)
return createStringError(std::errc::io_error,
"Unexpected end of file reading %u of %u bits",
BitsInCurWord, BitsLeft);
word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
// Use a mask to avoid undefined behavior.
CurWord >>= (BitsLeft & Mask);
BitsInCurWord -= BitsLeft;
R |= R2 << (NumBits - BitsLeft);
return R;
}
Expected<uint32_t> ReadVBR(unsigned NumBits) {
Expected<unsigned> MaybeRead = Read(NumBits);
if (!MaybeRead)
return MaybeRead;
uint32_t Piece = MaybeRead.get();
if ((Piece & (1U << (NumBits-1))) == 0)
return Piece;
uint32_t Result = 0;
unsigned NextBit = 0;
while (true) {
Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
if ((Piece & (1U << (NumBits-1))) == 0)
return Result;
NextBit += NumBits-1;
MaybeRead = Read(NumBits);
if (!MaybeRead)
return MaybeRead;
Piece = MaybeRead.get();
}
}
// Read a VBR that may have a value up to 64-bits in size. The chunk size of
// the VBR must still be <= 32 bits though.
Expected<uint64_t> ReadVBR64(unsigned NumBits) {
Expected<uint64_t> MaybeRead = Read(NumBits);
if (!MaybeRead)
return MaybeRead;
uint32_t Piece = MaybeRead.get();
if ((Piece & (1U << (NumBits-1))) == 0)
return uint64_t(Piece);
uint64_t Result = 0;
unsigned NextBit = 0;
while (true) {
Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
if ((Piece & (1U << (NumBits-1))) == 0)
return Result;
NextBit += NumBits-1;
MaybeRead = Read(NumBits);
if (!MaybeRead)
return MaybeRead;
Piece = MaybeRead.get();
}
}
void SkipToFourByteBoundary() {
// If word_t is 64-bits and if we've read less than 32 bits, just dump
// the bits we have up to the next 32-bit boundary.
if (sizeof(word_t) > 4 &&
BitsInCurWord >= 32) {
CurWord >>= BitsInCurWord-32;
BitsInCurWord = 32;
return;
}
BitsInCurWord = 0;
}
/// Return the size of the stream in bytes.
size_t SizeInBytes() const { return BitcodeBytes.size(); }
/// Skip to the end of the file.
void skipToEnd() { NextChar = BitcodeBytes.size(); }
};
/// When advancing through a bitstream cursor, each advance can discover a few
/// different kinds of entries:
struct BitstreamEntry {
enum {
Error, // Malformed bitcode was found.
EndBlock, // We've reached the end of the current block, (or the end of the
// file, which is treated like a series of EndBlock records.
SubBlock, // This is the start of a new subblock of a specific ID.
Record // This is a record with a specific AbbrevID.
} Kind;
unsigned ID;
static BitstreamEntry getError() {
BitstreamEntry E; E.Kind = Error; return E;
}
static BitstreamEntry getEndBlock() {
BitstreamEntry E; E.Kind = EndBlock; return E;
}
static BitstreamEntry getSubBlock(unsigned ID) {
BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
}
static BitstreamEntry getRecord(unsigned AbbrevID) {
BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
}
};
/// This represents a position within a bitcode file, implemented on top of a
/// SimpleBitstreamCursor.
///
/// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
/// be passed by value.
class BitstreamCursor : SimpleBitstreamCursor {
// This is the declared size of code values used for the current block, in
// bits.
unsigned CurCodeSize = 2;
/// Abbrevs installed at in this block.
std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
struct Block {
unsigned PrevCodeSize;
std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
};
/// This tracks the codesize of parent blocks.
SmallVector<Block, 8> BlockScope;
BitstreamBlockInfo *BlockInfo = nullptr;
public:
static const size_t MaxChunkSize = sizeof(word_t) * 8;
BitstreamCursor() = default;
explicit BitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
: SimpleBitstreamCursor(BitcodeBytes) {}
explicit BitstreamCursor(StringRef BitcodeBytes)
: SimpleBitstreamCursor(BitcodeBytes) {}
explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
: SimpleBitstreamCursor(BitcodeBytes) {}
using SimpleBitstreamCursor::AtEndOfStream;
using SimpleBitstreamCursor::canSkipToPos;
using SimpleBitstreamCursor::fillCurWord;
using SimpleBitstreamCursor::getBitcodeBytes;
using SimpleBitstreamCursor::GetCurrentBitNo;
using SimpleBitstreamCursor::getCurrentByteNo;
using SimpleBitstreamCursor::getPointerToByte;
using SimpleBitstreamCursor::JumpToBit;
using SimpleBitstreamCursor::Read;
using SimpleBitstreamCursor::ReadVBR;
using SimpleBitstreamCursor::ReadVBR64;
using SimpleBitstreamCursor::SizeInBytes;
using SimpleBitstreamCursor::skipToEnd;
/// Return the number of bits used to encode an abbrev #.
unsigned getAbbrevIDWidth() const { return CurCodeSize; }
/// Flags that modify the behavior of advance().
enum {
/// If this flag is used, the advance() method does not automatically pop
/// the block scope when the end of a block is reached.
AF_DontPopBlockAtEnd = 1,
/// If this flag is used, abbrev entries are returned just like normal
/// records.
AF_DontAutoprocessAbbrevs = 2
};
/// Advance the current bitstream, returning the next entry in the stream.
Expected<BitstreamEntry> advance(unsigned Flags = 0) {
while (true) {
if (AtEndOfStream())
return BitstreamEntry::getError();
Expected<unsigned> MaybeCode = ReadCode();
if (!MaybeCode)
return MaybeCode.takeError();
unsigned Code = MaybeCode.get();
if (Code == bitc::END_BLOCK) {
// Pop the end of the block unless Flags tells us not to.
if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
return BitstreamEntry::getError();
return BitstreamEntry::getEndBlock();
}
if (Code == bitc::ENTER_SUBBLOCK) {
if (Expected<unsigned> MaybeSubBlock = ReadSubBlockID())
return BitstreamEntry::getSubBlock(MaybeSubBlock.get());
else
return MaybeSubBlock.takeError();
}
if (Code == bitc::DEFINE_ABBREV &&
!(Flags & AF_DontAutoprocessAbbrevs)) {
// We read and accumulate abbrev's, the client can't do anything with
// them anyway.
if (Error Err = ReadAbbrevRecord())
return std::move(Err);
continue;
}
return BitstreamEntry::getRecord(Code);
}
}
/// This is a convenience function for clients that don't expect any
/// subblocks. This just skips over them automatically.
Expected<BitstreamEntry> advanceSkippingSubblocks(unsigned Flags = 0) {
while (true) {
// If we found a normal entry, return it.
Expected<BitstreamEntry> MaybeEntry = advance(Flags);
if (!MaybeEntry)
return MaybeEntry;
BitstreamEntry Entry = MaybeEntry.get();
if (Entry.Kind != BitstreamEntry::SubBlock)
return Entry;
// If we found a sub-block, just skip over it and check the next entry.
if (Error Err = SkipBlock())
return std::move(Err);
}
}
Expected<unsigned> ReadCode() { return Read(CurCodeSize); }
// Block header:
// [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
/// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
Expected<unsigned> ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); }
/// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
/// of this block.
Error SkipBlock() {
// Read and ignore the codelen value.
if (Expected<uint32_t> Res = ReadVBR(bitc::CodeLenWidth))
; // Since we are skipping this block, we don't care what code widths are
// used inside of it.
else
return Res.takeError();
SkipToFourByteBoundary();
Expected<unsigned> MaybeNum = Read(bitc::BlockSizeWidth);
if (!MaybeNum)
return MaybeNum.takeError();
size_t NumFourBytes = MaybeNum.get();
// Check that the block wasn't partially defined, and that the offset isn't
// bogus.
size_t SkipTo = GetCurrentBitNo() + NumFourBytes * 4 * 8;
if (AtEndOfStream())
return createStringError(std::errc::illegal_byte_sequence,
"can't skip block: already at end of stream");
if (!canSkipToPos(SkipTo / 8))
return createStringError(std::errc::illegal_byte_sequence,
"can't skip to bit %zu from %" PRIu64, SkipTo,
GetCurrentBitNo());
if (Error Res = JumpToBit(SkipTo))
return Res;
return Error::success();
}
/// Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
bool ReadBlockEnd() {
if (BlockScope.empty()) return true;
// Block tail:
// [END_BLOCK, <align4bytes>]
SkipToFourByteBoundary();
popBlockScope();
return false;
}
private:
void popBlockScope() {
CurCodeSize = BlockScope.back().PrevCodeSize;
CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
BlockScope.pop_back();
}
//===--------------------------------------------------------------------===//
// Record Processing
//===--------------------------------------------------------------------===//
public:
/// Return the abbreviation for the specified AbbrevId.
const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
if (AbbrevNo >= CurAbbrevs.size())
report_fatal_error("Invalid abbrev number");
return CurAbbrevs[AbbrevNo].get();
}
/// Read the current record and discard it, returning the code for the record.
Expected<unsigned> skipRecord(unsigned AbbrevID);
Expected<unsigned> readRecord(unsigned AbbrevID,
SmallVectorImpl<uint64_t> &Vals,
StringRef *Blob = nullptr);
//===--------------------------------------------------------------------===//
// Abbrev Processing
//===--------------------------------------------------------------------===//
Error ReadAbbrevRecord();
/// Read and return a block info block from the bitstream. If an error was
/// encountered, return None.
///
/// \param ReadBlockInfoNames Whether to read block/record name information in
/// the BlockInfo block. Only llvm-bcanalyzer uses this.
Expected<Optional<BitstreamBlockInfo>>
ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
/// Set the block info to be used by this BitstreamCursor to interpret
/// abbreviated records.
void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
};
} // end llvm namespace
#endif // LLVM_BITSTREAM_BITSTREAMREADER_H
| GPUOpen-Drivers/llvm | include/llvm/Bitstream/BitstreamReader.h | C | apache-2.0 | 18,205 |
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.
*/
package org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.associations;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.bpmn2.Association;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.bpmn.backend.converters.TypedFactoryManager;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.BpmnEdge;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.BpmnNode;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.AssociationPropertyReader;
import org.kie.workbench.common.stunner.bpmn.backend.converters.tostunner.properties.PropertyReaderFactory;
import org.kie.workbench.common.stunner.bpmn.definition.DirectionalAssociation;
import org.kie.workbench.common.stunner.bpmn.definition.NonDirectionalAssociation;
import org.kie.workbench.common.stunner.bpmn.definition.property.general.BPMNGeneralSet;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.view.Connection;
import org.kie.workbench.common.stunner.core.graph.content.view.Point2D;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class AssociationConverterTest {
private static final String ASSOCIATION_ID = "ASSOCIATION_ID";
private static final String ASSOCIATION_DOCUMENTATION = "ASSOCIATION_DOCUMENTATION";
private static final String SOURCE_ID = "SOURCE_ID";
private static final String TARGET_ID = "TARGET_ID";
@Mock
private PropertyReaderFactory propertyReaderFactory;
@Mock
private TypedFactoryManager factoryManager;
@Mock
private Edge<View<org.kie.workbench.common.stunner.bpmn.definition.Association>, Node> edge;
@Mock
private View<org.kie.workbench.common.stunner.bpmn.definition.Association> content;
@Mock
private org.kie.workbench.common.stunner.bpmn.definition.Association definition;
@Captor
private ArgumentCaptor<BPMNGeneralSet> generalSetCaptor;
@Mock
private Association association;
@Mock
private AssociationPropertyReader associationReader;
private AssociationConverter associationConverter;
private Map<String, BpmnNode> nodes;
@Mock
private BpmnNode sourceNode;
@Mock
private BpmnNode targetNode;
@Mock
private Connection sourceConnection;
@Mock
private Connection targetConnection;
@Mock
private List<Point2D> controlPoints;
@Mock
private Edge<View<NonDirectionalAssociation>, Node> edgeNonDirectional;
@Mock
private View<NonDirectionalAssociation> contentNonDirectional;
@Mock
private NonDirectionalAssociation definitionNonDirectional;
@Before
@SuppressWarnings("unchecked")
public void setUp() {
when(association.getId()).thenReturn(ASSOCIATION_ID);
when(edge.getContent()).thenReturn(content);
when(content.getDefinition()).thenReturn(definition);
when(factoryManager.newEdge(ASSOCIATION_ID, DirectionalAssociation.class)).thenReturn((Edge) edge);
when(propertyReaderFactory.of(association)).thenReturn(associationReader);
when(associationReader.getAssociationByDirection()).thenAnswer(a -> DirectionalAssociation.class);
when(associationReader.getDocumentation()).thenReturn(ASSOCIATION_DOCUMENTATION);
when(associationReader.getSourceId()).thenReturn(SOURCE_ID);
when(associationReader.getTargetId()).thenReturn(TARGET_ID);
when(associationReader.getSourceConnection()).thenReturn(sourceConnection);
when(associationReader.getTargetConnection()).thenReturn(targetConnection);
when(associationReader.getControlPoints()).thenReturn(controlPoints);
associationConverter = new AssociationConverter(factoryManager, propertyReaderFactory);
nodes = new HashMap<>();
nodes.put(SOURCE_ID, sourceNode);
nodes.put(TARGET_ID, targetNode);
}
@Test
public void testConvertEdge() {
associationConverter.convertEdge(association, nodes);
verify(definition).setGeneral(generalSetCaptor.capture());
assertEquals(ASSOCIATION_DOCUMENTATION, generalSetCaptor.getValue().getDocumentation().getValue());
assertEdgeWithConnections();
}
private void assertEdgeWithConnections() {
BpmnEdge.Simple result = (BpmnEdge.Simple) associationConverter.convertEdge(association, nodes).value();
assertEquals(sourceNode, result.getSource());
assertEquals(targetNode, result.getTarget());
assertEquals(sourceConnection, result.getSourceConnection());
assertEquals(targetConnection, result.getTargetConnection());
assertEquals(controlPoints, result.getControlPoints());
assertEquals(edge, result.getEdge());
}
@Test
public void testConvertEdgeNonDirectional() {
when(factoryManager.newEdge(ASSOCIATION_ID, NonDirectionalAssociation.class)).thenReturn((Edge) edgeNonDirectional);
when(associationReader.getAssociationByDirection()).thenAnswer(a -> NonDirectionalAssociation.class);
when(edgeNonDirectional.getContent()).thenReturn(contentNonDirectional);
when(contentNonDirectional.getDefinition()).thenReturn(definitionNonDirectional);
BpmnEdge.Simple result = (BpmnEdge.Simple) associationConverter.convertEdge(association, nodes).value();
assertEquals(edgeNonDirectional, result.getEdge());
}
@Test
public void testConvertIgnoredEdge() {
//assert connections
assertEdgeWithConnections();
//now remove the source node
nodes.remove(SOURCE_ID);
BpmnEdge.Simple result = (BpmnEdge.Simple) associationConverter.convertEdge(association, nodes).value();
assertNull(result);
//add source node and remove target
nodes.put(SOURCE_ID, sourceNode);
nodes.remove(TARGET_ID);
result = (BpmnEdge.Simple) associationConverter.convertEdge(association, nodes).value();
assertNull(result);
//adding both again
nodes.put(SOURCE_ID, sourceNode);
nodes.put(TARGET_ID, targetNode);
assertEdgeWithConnections();
}
}
| jomarko/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-backend/src/test/java/org/kie/workbench/common/stunner/bpmn/backend/converters/tostunner/associations/AssociationConverterTest.java | Java | apache-2.0 | 7,294 |
//===----------------------------------------------------------------------===//
//
// Peloton
//
// stats_storage_test.cpp
//
// Identification: test/optimizer/stats_storage_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/harness.h"
#define private public
#define protected public
#include "optimizer/stats/stats_storage.h"
#include "optimizer/stats/column_stats.h"
#include "optimizer/stats/table_stats.h"
#include "storage/data_table.h"
#include "storage/database.h"
#include "storage/tile.h"
#include "catalog/schema.h"
#include "catalog/catalog.h"
#include "catalog/column_stats_catalog.h"
#include "executor/testing_executor_util.h"
#include "concurrency/transaction_manager_factory.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Binding Tests
//===--------------------------------------------------------------------===//
using namespace optimizer;
class StatsStorageTests : public PelotonTest {};
const int tuple_count = 100;
const int tuple_per_tilegroup = 100;
std::unique_ptr<storage::DataTable> InitializeTestTable() {
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
std::unique_ptr<storage::DataTable> data_table(
TestingExecutorUtil::CreateTable(tuple_per_tilegroup, false));
TestingExecutorUtil::PopulateTable(data_table.get(), tuple_count, false,
false, true, txn);
txn_manager.CommitTransaction(txn);
return data_table;
}
storage::DataTable *CreateTestDBAndTable() {
const std::string test_db_name = "test_db";
auto database = TestingExecutorUtil::InitializeDatabase(test_db_name);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
storage::DataTable *data_table =
TestingExecutorUtil::CreateTable(tuple_per_tilegroup, false);
TestingExecutorUtil::PopulateTable(data_table, tuple_count, false, false,
true, txn);
database->AddTable(data_table);
txn_manager.CommitTransaction(txn);
return data_table;
}
/**
* VerifyAndPrintColumnStats - Verify whether the stats of the test table are
* correctly stored in catalog and print them out.
*
* The column stats are retrieved by calling the
* StatsStorage::GetColumnStatsByID function.
* TODO:
* 1. Verify the number of tuples in column_stats_catalog.
* 2. Compare the column stats values with the ground truth.
*/
void VerifyAndPrintColumnStats(storage::DataTable *data_table,
int expect_tuple_count) {
// Check the tuple count in the 'pg_column_stats' catalog.
StatsStorage *stats_storage = StatsStorage::GetInstance();
// Print out all four column stats.
for (int column_id = 0; column_id < expect_tuple_count; ++column_id) {
auto column_stats = stats_storage->GetColumnStatsByID(
data_table->GetDatabaseOid(), data_table->GetOid(), column_id);
LOG_TRACE("num_rows: %lu", column_stats->num_rows);
LOG_TRACE("cardinality: %lf", column_stats->cardinality);
LOG_TRACE("frac_null: %lf", column_stats->frac_null);
auto most_common_vals = column_stats->most_common_vals;
auto most_common_freqs = column_stats->most_common_freqs;
auto hist_bounds = column_stats->histogram_bounds;
}
}
TEST_F(StatsStorageTests, InsertAndGetTableStatsTest) {
auto data_table = InitializeTestTable();
// Collect stats.
std::unique_ptr<optimizer::TableStatsCollector> table_stats_collector(
new TableStatsCollector(data_table.get()));
table_stats_collector->CollectColumnStats();
// Insert stats.
auto catalog = catalog::Catalog::GetInstance();
(void)catalog;
StatsStorage *stats_storage = StatsStorage::GetInstance();
stats_storage->InsertOrUpdateTableStats(data_table.get(),
table_stats_collector.get());
VerifyAndPrintColumnStats(data_table.get(), 4);
}
TEST_F(StatsStorageTests, InsertAndGetColumnStatsTest) {
auto catalog = catalog::Catalog::GetInstance();
(void)catalog;
StatsStorage *stats_storage = StatsStorage::GetInstance();
oid_t database_id = 1;
oid_t table_id = 2;
oid_t column_id = 3;
int num_rows = 10;
double cardinality = 8;
double frac_null = 0.56;
std::string most_common_vals = "12";
std::string most_common_freqs = "3";
std::string histogram_bounds = "1,5,7";
std::string column_name = "random";
stats_storage->InsertOrUpdateColumnStats(
database_id, table_id, column_id, num_rows, cardinality, frac_null,
most_common_vals, most_common_freqs, histogram_bounds, column_name);
auto column_stats_ptr =
stats_storage->GetColumnStatsByID(database_id, table_id, column_id);
// Check the result
EXPECT_NE(column_stats_ptr, nullptr);
EXPECT_EQ(column_stats_ptr->num_rows, num_rows);
EXPECT_EQ(column_stats_ptr->cardinality, cardinality);
EXPECT_EQ(column_stats_ptr->frac_null, frac_null);
EXPECT_EQ(column_stats_ptr->column_name, column_name);
// Should return nullptr
auto column_stats_ptr2 =
stats_storage->GetColumnStatsByID(database_id, table_id, column_id + 1);
EXPECT_EQ(column_stats_ptr2, nullptr);
}
TEST_F(StatsStorageTests, UpdateColumnStatsTest) {
auto catalog = catalog::Catalog::GetInstance();
(void)catalog;
StatsStorage *stats_storage = StatsStorage::GetInstance();
oid_t database_id = 1;
oid_t table_id = 2;
oid_t column_id = 3;
int num_row_0 = 10;
double cardinality_0 = 8;
double frac_null_0 = 0.56;
std::string most_common_vals_0 = "12";
std::string most_common_freqs_0 = "3";
std::string histogram_bounds_0 = "1,5,7";
std::string column_name_0 = "random0";
int num_row_1 = 20;
double cardinality_1 = 16;
double frac_null_1 = 1.56;
std::string most_common_vals_1 = "24";
std::string most_common_freqs_1 = "6";
std::string histogram_bounds_1 = "2,10,14";
std::string column_name_1 = "random1";
stats_storage->InsertOrUpdateColumnStats(
database_id, table_id, column_id, num_row_0, cardinality_0, frac_null_0,
most_common_vals_0, most_common_freqs_0, histogram_bounds_0,
column_name_0);
stats_storage->InsertOrUpdateColumnStats(
database_id, table_id, column_id, num_row_1, cardinality_1, frac_null_1,
most_common_vals_1, most_common_freqs_1, histogram_bounds_1,
column_name_1);
auto column_stats_ptr =
stats_storage->GetColumnStatsByID(database_id, table_id, column_id);
// Check the result
EXPECT_NE(column_stats_ptr, nullptr);
EXPECT_EQ(column_stats_ptr->num_rows, num_row_1);
EXPECT_EQ(column_stats_ptr->cardinality, cardinality_1);
EXPECT_EQ(column_stats_ptr->frac_null, frac_null_1);
EXPECT_EQ(column_stats_ptr->column_name, column_name_1);
}
TEST_F(StatsStorageTests, AnalyzeStatsForTableTest) {
auto data_table = InitializeTestTable();
// Analyze table.
StatsStorage *stats_storage = StatsStorage::GetInstance();
// Must pass in the transaction.
ResultType result = stats_storage->AnalyzeStatsForTable(data_table.get());
EXPECT_EQ(result, ResultType::FAILURE);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
result = stats_storage->AnalyzeStatsForTable(data_table.get(), txn);
EXPECT_EQ(result, ResultType::SUCCESS);
txn_manager.CommitTransaction(txn);
// Check the correctness of the stats.
VerifyAndPrintColumnStats(data_table.get(), 4);
}
// TODO: Add more tables.
TEST_F(StatsStorageTests, AnalyzeStatsForAllTablesTest) {
auto data_table = CreateTestDBAndTable();
StatsStorage *stats_storage = StatsStorage::GetInstance();
// Must pass in the transaction.
ResultType result = stats_storage->AnalyzeStatsForAllTables();
EXPECT_EQ(result, ResultType::FAILURE);
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
result = stats_storage->AnalyzeStatsForAllTables(txn);
EXPECT_EQ(result, ResultType::SUCCESS);
txn_manager.CommitTransaction(txn);
// Check the correctness of the stats.
VerifyAndPrintColumnStats(data_table, 4);
}
TEST_F(StatsStorageTests, GetTableStatsTest) {
auto data_table = InitializeTestTable();
StatsStorage *stats_storage = StatsStorage::GetInstance();
auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();
auto txn = txn_manager.BeginTransaction();
stats_storage->AnalyzeStatsForAllTables(txn);
txn_manager.CommitTransaction(txn);
std::shared_ptr<TableStats> table_stats = stats_storage->GetTableStats(
data_table->GetDatabaseOid(), data_table->GetOid());
EXPECT_EQ(table_stats->num_rows, tuple_count);
}
} // namespace test
} // namespace peloton
| AllisonWang/peloton | test/optimizer/stats_storage_test.cpp | C++ | apache-2.0 | 9,196 |
// Copyright 2010 The Walk Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
package walk
import (
"syscall"
)
import (
"github.com/lxn/win"
)
const groupBoxWindowClass = `\o/ Walk_GroupBox_Class \o/`
func init() {
MustRegisterWindowClass(groupBoxWindowClass)
}
type GroupBox struct {
WidgetBase
hWndGroupBox win.HWND
checkBox *CheckBox
composite *Composite
titleChangedPublisher EventPublisher
}
func NewGroupBox(parent Container) (*GroupBox, error) {
gb := new(GroupBox)
if err := InitWidget(
gb,
parent,
groupBoxWindowClass,
win.WS_VISIBLE,
win.WS_EX_CONTROLPARENT); err != nil {
return nil, err
}
succeeded := false
defer func() {
if !succeeded {
gb.Dispose()
}
}()
gb.hWndGroupBox = win.CreateWindowEx(
0, syscall.StringToUTF16Ptr("BUTTON"), nil,
win.WS_CHILD|win.WS_VISIBLE|win.BS_GROUPBOX,
0, 0, 80, 24, gb.hWnd, 0, 0, nil)
if gb.hWndGroupBox == 0 {
return nil, lastError("CreateWindowEx(BUTTON)")
}
setWindowFont(gb.hWndGroupBox, gb.Font())
var err error
gb.checkBox, err = NewCheckBox(gb)
if err != nil {
return nil, err
}
gb.SetCheckable(false)
gb.checkBox.SetChecked(true)
gb.checkBox.CheckedChanged().Attach(func() {
gb.applyEnabledFromCheckBox(gb.checkBox.Checked())
})
setWindowVisible(gb.checkBox.hWnd, false)
gb.composite, err = NewComposite(gb)
if err != nil {
return nil, err
}
win.SetWindowPos(gb.checkBox.hWnd, win.HWND_TOP, 0, 0, 0, 0, win.SWP_NOMOVE|win.SWP_NOSIZE)
gb.MustRegisterProperty("Title", NewProperty(
func() interface{} {
return gb.Title()
},
func(v interface{}) error {
return gb.SetTitle(v.(string))
},
gb.titleChangedPublisher.Event()))
gb.MustRegisterProperty("Checked", NewBoolProperty(
func() bool {
return gb.Checked()
},
func(v bool) error {
gb.SetChecked(v)
return nil
},
gb.CheckedChanged()))
succeeded = true
return gb, nil
}
func (gb *GroupBox) AsContainerBase() *ContainerBase {
return gb.composite.AsContainerBase()
}
func (gb *GroupBox) LayoutFlags() LayoutFlags {
if gb.composite == nil {
return 0
}
return gb.composite.LayoutFlags()
}
func (gb *GroupBox) MinSizeHint() Size {
if gb.composite == nil {
return Size{100, 100}
}
cmsh := gb.composite.MinSizeHint()
if gb.Checkable() {
s := gb.checkBox.SizeHint()
cmsh.Width = maxi(cmsh.Width, s.Width)
cmsh.Height += s.Height
}
return Size{cmsh.Width + 2, cmsh.Height + 14}
}
func (gb *GroupBox) SizeHint() Size {
return gb.MinSizeHint()
}
func (gb *GroupBox) ClientBounds() Rectangle {
cb := windowClientBounds(gb.hWndGroupBox)
if gb.Layout() == nil {
return cb
}
if gb.Checkable() {
s := gb.checkBox.SizeHint()
cb.Y += s.Height
cb.Height -= s.Height
}
// FIXME: Use appropriate margins
return Rectangle{cb.X + 1, cb.Y + 14, cb.Width - 2, cb.Height - 14}
}
func (gb *GroupBox) applyEnabled(enabled bool) {
gb.WidgetBase.applyEnabled(enabled)
if gb.hWndGroupBox != 0 {
setWindowEnabled(gb.hWndGroupBox, enabled)
}
if gb.checkBox != nil {
gb.checkBox.applyEnabled(enabled)
}
if gb.composite != nil {
gb.composite.applyEnabled(enabled)
}
}
func (gb *GroupBox) applyEnabledFromCheckBox(enabled bool) {
if gb.hWndGroupBox != 0 {
setWindowEnabled(gb.hWndGroupBox, enabled)
}
if gb.composite != nil {
gb.composite.applyEnabled(enabled)
}
}
func (gb *GroupBox) applyFont(font *Font) {
gb.WidgetBase.applyFont(font)
if gb.checkBox != nil {
gb.checkBox.applyFont(font)
}
if gb.hWndGroupBox != 0 {
setWindowFont(gb.hWndGroupBox, font)
}
if gb.composite != nil {
gb.composite.applyFont(font)
}
}
func (gb *GroupBox) SetSuspended(suspend bool) {
gb.composite.SetSuspended(suspend)
gb.WidgetBase.SetSuspended(suspend)
gb.Invalidate()
}
func (gb *GroupBox) DataBinder() *DataBinder {
return gb.composite.dataBinder
}
func (gb *GroupBox) SetDataBinder(dataBinder *DataBinder) {
gb.composite.SetDataBinder(dataBinder)
}
func (gb *GroupBox) Title() string {
if gb.Checkable() {
return gb.checkBox.Text()
}
return windowText(gb.hWndGroupBox)
}
func (gb *GroupBox) SetTitle(title string) error {
if gb.Checkable() {
if err := setWindowText(gb.hWndGroupBox, ""); err != nil {
return err
}
return gb.checkBox.SetText(title)
}
return setWindowText(gb.hWndGroupBox, title)
}
func (gb *GroupBox) Checkable() bool {
return gb.checkBox.visible
}
func (gb *GroupBox) SetCheckable(checkable bool) {
title := gb.Title()
gb.checkBox.SetVisible(checkable)
gb.SetTitle(title)
gb.updateParentLayout()
}
func (gb *GroupBox) Checked() bool {
return gb.checkBox.Checked()
}
func (gb *GroupBox) SetChecked(checked bool) {
gb.checkBox.SetChecked(checked)
}
func (gb *GroupBox) CheckedChanged() *Event {
return gb.checkBox.CheckedChanged()
}
func (gb *GroupBox) Children() *WidgetList {
if gb.composite == nil {
// Without this we would get into trouble in NewComposite.
return nil
}
return gb.composite.Children()
}
func (gb *GroupBox) Layout() Layout {
if gb.composite == nil {
// Without this we would get into trouble through the call to
// SetCheckable in NewGroupBox.
return nil
}
return gb.composite.Layout()
}
func (gb *GroupBox) SetLayout(value Layout) error {
return gb.composite.SetLayout(value)
}
func (gb *GroupBox) MouseDown() *MouseEvent {
return gb.composite.MouseDown()
}
func (gb *GroupBox) MouseMove() *MouseEvent {
return gb.composite.MouseMove()
}
func (gb *GroupBox) MouseUp() *MouseEvent {
return gb.composite.MouseUp()
}
func (gb *GroupBox) WndProc(hwnd win.HWND, msg uint32, wParam, lParam uintptr) uintptr {
if gb.composite != nil {
switch msg {
case win.WM_COMMAND, win.WM_NOTIFY:
gb.composite.WndProc(hwnd, msg, wParam, lParam)
case win.WM_SETTEXT:
gb.titleChangedPublisher.Publish()
case win.WM_PAINT:
win.UpdateWindow(gb.checkBox.hWnd)
case win.WM_SIZE, win.WM_SIZING:
wbcb := gb.WidgetBase.ClientBounds()
if !win.MoveWindow(
gb.hWndGroupBox,
int32(wbcb.X),
int32(wbcb.Y),
int32(wbcb.Width),
int32(wbcb.Height),
true) {
lastError("MoveWindow")
break
}
if gb.Checkable() {
s := gb.checkBox.SizeHint()
gb.checkBox.SetBounds(Rectangle{9, 14, s.Width, s.Height})
}
gbcb := gb.ClientBounds()
gb.composite.SetBounds(gbcb)
}
}
return gb.WidgetBase.WndProc(hwnd, msg, wParam, lParam)
}
| admpub/spider | vendor/github.com/lxn/walk/groupbox.go | GO | apache-2.0 | 6,487 |
package com.mapswithme.maps.gdpr;
import androidx.fragment.app.Fragment;
import com.mapswithme.maps.base.BaseToolbarActivity;
public class MwmOptOutActivity extends BaseToolbarActivity
{
@Override
protected Class<? extends Fragment> getFragmentClass()
{
return OptOutFragment.class;
}
}
| matsprea/omim | android/src/com/mapswithme/maps/gdpr/MwmOptOutActivity.java | Java | apache-2.0 | 302 |
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Thinktecture.IdentityManager;
namespace Core.Tests.Core
{
[TestClass]
public class IdentityManagerResult_Of_T_Tests
{
public class FooResult{}
IdentityManagerResult<FooResult> subject;
[TestMethod]
public void ctor_WithResult_HasResult()
{
var r = new FooResult();
subject = new IdentityManagerResult<FooResult>(r);
Assert.AreSame(r, subject.Result);
}
[TestMethod]
public void ctor_WithErrors_HasNoResult()
{
subject = new IdentityManagerResult<FooResult>("error");
Assert.IsNull(subject.Result);
}
}
}
| Ernesto99/IdentityManager | source/Core.Tests/Core/IdentityManagerResult`1Tests.cs | C# | apache-2.0 | 758 |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for ram_file_system.h."""
import numpy as np
from tensorflow.python.eager import def_function
from tensorflow.python.estimator.estimator import Estimator
from tensorflow.python.estimator.model_fn import EstimatorSpec
from tensorflow.python.estimator.run_config import RunConfig
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tensorflow.python.layers import core as core_layers
from tensorflow.python.lib.io import file_io
from tensorflow.python.module import module
from tensorflow.python.ops.losses import losses
from tensorflow.python.platform import gfile
from tensorflow.python.platform import test
from tensorflow.python.saved_model import saved_model
from tensorflow.python.training import adam
from tensorflow.python.training import training_util
class RamFilesystemTest(test_util.TensorFlowTestCase):
def test_create_and_delete_directory(self):
file_io.create_dir_v2('ram://testdirectory')
file_io.delete_recursively_v2('ram://testdirectory')
def test_create_and_delete_directory_tree_recursive(self):
file_io.create_dir_v2('ram://testdirectory')
file_io.create_dir_v2('ram://testdirectory/subdir1')
file_io.create_dir_v2('ram://testdirectory/subdir2')
file_io.create_dir_v2('ram://testdirectory/subdir1/subdir3')
with gfile.GFile('ram://testdirectory/subdir1/subdir3/a.txt', 'w') as f:
f.write('Hello, world.')
file_io.delete_recursively_v2('ram://testdirectory')
self.assertEqual(gfile.Glob('ram://testdirectory/*'), [])
def test_write_file(self):
with gfile.GFile('ram://a.txt', 'w') as f:
f.write('Hello, world.')
f.write('Hello, world.')
with gfile.GFile('ram://a.txt', 'r') as f:
self.assertEqual(f.read(), 'Hello, world.' * 2)
def test_append_file_with_seek(self):
with gfile.GFile('ram://c.txt', 'w') as f:
f.write('Hello, world.')
with gfile.GFile('ram://c.txt', 'w+') as f:
f.seek(offset=0, whence=2)
f.write('Hello, world.')
with gfile.GFile('ram://c.txt', 'r') as f:
self.assertEqual(f.read(), 'Hello, world.' * 2)
def test_list_dir(self):
for i in range(10):
with gfile.GFile('ram://a/b/%d.txt' % i, 'w') as f:
f.write('')
with gfile.GFile('ram://c/b/%d.txt' % i, 'w') as f:
f.write('')
matches = ['%d.txt' % i for i in range(10)]
self.assertEqual(gfile.ListDirectory('ram://a/b/'), matches)
def test_glob(self):
for i in range(10):
with gfile.GFile('ram://a/b/%d.txt' % i, 'w') as f:
f.write('')
with gfile.GFile('ram://c/b/%d.txt' % i, 'w') as f:
f.write('')
matches = ['ram://a/b/%d.txt' % i for i in range(10)]
self.assertEqual(gfile.Glob('ram://a/b/*'), matches)
matches = []
self.assertEqual(gfile.Glob('ram://b/b/*'), matches)
matches = ['ram://c/b/%d.txt' % i for i in range(10)]
self.assertEqual(gfile.Glob('ram://c/b/*'), matches)
def test_file_exists(self):
with gfile.GFile('ram://exists/a/b/c.txt', 'w') as f:
f.write('')
self.assertTrue(gfile.Exists('ram://exists/a'))
self.assertTrue(gfile.Exists('ram://exists/a/b'))
self.assertTrue(gfile.Exists('ram://exists/a/b/c.txt'))
self.assertFalse(gfile.Exists('ram://exists/b'))
self.assertFalse(gfile.Exists('ram://exists/a/c'))
self.assertFalse(gfile.Exists('ram://exists/a/b/k'))
def test_estimator(self):
def model_fn(features, labels, mode, params):
del params
x = core_layers.dense(features, 100)
x = core_layers.dense(x, 100)
x = core_layers.dense(x, 100)
x = core_layers.dense(x, 100)
y = core_layers.dense(x, 1)
loss = losses.mean_squared_error(labels, y)
opt = adam.AdamOptimizer(learning_rate=0.1)
train_op = opt.minimize(
loss, global_step=training_util.get_or_create_global_step())
return EstimatorSpec(mode=mode, loss=loss, train_op=train_op)
def input_fn():
batch_size = 128
return (constant_op.constant(np.random.randn(batch_size, 100),
dtype=dtypes.float32),
constant_op.constant(np.random.randn(batch_size, 1),
dtype=dtypes.float32))
config = RunConfig(
model_dir='ram://estimator-0/', save_checkpoints_steps=1)
estimator = Estimator(config=config, model_fn=model_fn)
estimator.train(input_fn=input_fn, steps=10)
estimator.train(input_fn=input_fn, steps=10)
estimator.train(input_fn=input_fn, steps=10)
estimator.train(input_fn=input_fn, steps=10)
def test_savedmodel(self):
class MyModule(module.Module):
@def_function.function(input_signature=[])
def foo(self):
return constant_op.constant([1])
saved_model.save(MyModule(), 'ram://my_module')
loaded = saved_model.load('ram://my_module')
self.assertAllEqual(loaded.foo(), [1])
if __name__ == '__main__':
test.main()
| tensorflow/tensorflow | tensorflow/core/platform/ram_file_system_test.py | Python | apache-2.0 | 5,699 |
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_PLATFORM_MEM_H_
#define TENSORFLOW_PLATFORM_MEM_H_
#include "tensorflow/core/platform/platform.h"
#include "tensorflow/core/platform/types.h"
// Include appropriate platform-dependent implementation of
// TF_ANNOTATE_MEMORY_IS_INITIALIZED.
#if defined(PLATFORM_GOOGLE)
#include "tensorflow/core/platform/google/build_config/dynamic_annotations.h"
#elif defined(PLATFORM_POSIX) || defined(PLATFORM_POSIX_ANDROID) || \
defined(PLATFORM_GOOGLE_ANDROID)
#include "tensorflow/core/platform/default/dynamic_annotations.h"
#else
#error Define the appropriate PLATFORM_<foo> macro for this platform
#endif
namespace tensorflow {
namespace port {
// Aligned allocation/deallocation
void* aligned_malloc(size_t size, int minimum_alignment);
void aligned_free(void* aligned_memory);
// Tries to release num_bytes of free memory back to the operating
// system for reuse. Use this routine with caution -- to get this
// memory back may require faulting pages back in by the OS, and
// that may be slow.
//
// Currently, if a malloc implementation does not support this
// routine, this routine is a no-op.
void MallocExtension_ReleaseToSystem(std::size_t num_bytes);
// Returns the actual number N of bytes reserved by the malloc for the
// pointer p. This number may be equal to or greater than the number
// of bytes requested when p was allocated.
//
// This routine is just useful for statistics collection. The
// client must *not* read or write from the extra bytes that are
// indicated by this call.
//
// Example, suppose the client gets memory by calling
// p = malloc(10)
// and GetAllocatedSize(p) may return 16. The client must only use the
// first 10 bytes p[0..9], and not attempt to read or write p[10..15].
//
// Currently, if a malloc implementation does not support this
// routine, this routine returns 0.
std::size_t MallocExtension_GetAllocatedSize(const void* p);
// Prefetching support
//
// Defined behavior on some of the uarchs:
// PREFETCH_HINT_T0:
// prefetch to all levels of the hierarchy (except on p4: prefetch to L2)
// PREFETCH_HINT_NTA:
// p4: fetch to L2, but limit to 1 way (out of the 8 ways)
// core: skip L2, go directly to L1
// k8 rev E and later: skip L2, can go to either of the 2-ways in L1
enum PrefetchHint {
PREFETCH_HINT_T0 = 3, // More temporal locality
PREFETCH_HINT_T1 = 2,
PREFETCH_HINT_T2 = 1, // Less temporal locality
PREFETCH_HINT_NTA = 0 // No temporal locality
};
template <PrefetchHint hint>
void prefetch(const void* x);
// ---------------------------------------------------------------------------
// Inline implementation
// ---------------------------------------------------------------------------
template <PrefetchHint hint>
inline void prefetch(const void* x) {
#if defined(__llvm__) || defined(COMPILER_GCC)
__builtin_prefetch(x, 0, hint);
#else
// You get no effect. Feel free to add more sections above.
#endif
}
} // namespace port
} // namespace tensorflow
#endif // TENSORFLOW_PLATFORM_MEM_H_
| HaebinShin/tensorflow | tensorflow/core/platform/mem.h | C | apache-2.0 | 3,694 |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.
*/
package org.elasticsearch.common.lucene.search;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.Bits;
import org.elasticsearch.common.lucene.docset.AndDocIdSet;
import org.elasticsearch.common.lucene.docset.DocIdSets;
import java.io.IOException;
import java.util.List;
/**
*
*/
public class AndFilter extends Filter {
private final List<? extends Filter> filters;
public AndFilter(List<? extends Filter> filters) {
this.filters = filters;
}
public List<? extends Filter> filters() {
return filters;
}
@Override
public DocIdSet getDocIdSet(AtomicReaderContext context, Bits acceptDocs) throws IOException {
if (filters.size() == 1) {
return filters.get(0).getDocIdSet(context, acceptDocs);
}
DocIdSet[] sets = new DocIdSet[filters.size()];
for (int i = 0; i < filters.size(); i++) {
DocIdSet set = filters.get(i).getDocIdSet(context, acceptDocs);
if (DocIdSets.isEmpty(set)) { // none matching for this filter, we AND, so return EMPTY
return null;
}
sets[i] = set;
}
return new AndDocIdSet(sets);
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (null == filters ? 0 : filters.hashCode());
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if ((obj == null) || (obj.getClass() != this.getClass()))
return false;
AndFilter other = (AndFilter) obj;
return equalFilters(filters, other.filters);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Filter filter : filters) {
if (builder.length() > 0) {
builder.append(' ');
}
builder.append('+');
builder.append(filter);
}
return builder.toString();
}
private boolean equalFilters(List<? extends Filter> filters1, List<? extends Filter> filters2) {
return (filters1 == filters2) || ((filters1 != null) && filters1.equals(filters2));
}
}
| andrewvc/elasticsearch | src/main/java/org/elasticsearch/common/lucene/search/AndFilter.java | Java | apache-2.0 | 3,118 |
/*
* 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.
*/
package org.apache.nifi.registry.client.impl;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.registry.bucket.BucketItem;
import org.apache.nifi.registry.bucket.BucketItemType;
import org.apache.nifi.registry.extension.bundle.Bundle;
import org.apache.nifi.registry.flow.VersionedFlow;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BucketItemDeserializer extends StdDeserializer<BucketItem[]> {
public BucketItemDeserializer() {
super(BucketItem[].class);
}
@Override
public BucketItem[] deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
final JsonNode arrayNode = jsonParser.getCodec().readTree(jsonParser);
final List<BucketItem> bucketItems = new ArrayList<>();
final Iterator<JsonNode> nodeIter = arrayNode.elements();
while (nodeIter.hasNext()) {
final JsonNode node = nodeIter.next();
final String type = node.get("type").asText();
if (StringUtils.isBlank(type)) {
throw new IllegalStateException("BucketItem type cannot be null or blank");
}
final BucketItemType bucketItemType;
try {
bucketItemType = BucketItemType.valueOf(type);
} catch (Exception e) {
throw new IllegalStateException("Unknown type for BucketItem: " + type, e);
}
switch (bucketItemType) {
case Flow:
final VersionedFlow versionedFlow = jsonParser.getCodec().treeToValue(node, VersionedFlow.class);
bucketItems.add(versionedFlow);
break;
case Bundle:
final Bundle bundle = jsonParser.getCodec().treeToValue(node, Bundle.class);
bucketItems.add(bundle);
break;
default:
throw new IllegalStateException("Unknown type for BucketItem: " + bucketItemType);
}
}
return bucketItems.toArray(new BucketItem[bucketItems.size()]);
}
}
| MikeThomsen/nifi | nifi-registry/nifi-registry-core/nifi-registry-client/src/main/java/org/apache/nifi/registry/client/impl/BucketItemDeserializer.java | Java | apache-2.0 | 3,299 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Since applying the "call" method to Function constructor themself leads to creating a new function instance, the second argument must be a valid function body
*
* @path ch15/15.3/S15.3_A2_T1.js
* @description Checking if executing "Function.call(this, "var x / = 1;")" fails
*/
//CHECK#
try{
Function.call(this, "var x / = 1;");
} catch(e){
if (!(e instanceof SyntaxError)) {
$ERROR('#1: function body must be valid');
}
}
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.3/S15.3_A2_T1.js | JavaScript | apache-2.0 | 583 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Management.Compute;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute
{
[Cmdlet(
VerbsCommon.Remove,
ProfileNouns.VirtualMachineCustomScriptExtension)]
public class RemoveAzureVMCustomScriptExtensionCommand : VirtualMachineExtensionBaseCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The virtual machine name.")]
[ValidateNotNullOrEmpty]
public string VMName { get; set; }
[Alias("ExtensionName")]
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The extension name.")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(HelpMessage = "To force the removal.")]
[ValidateNotNullOrEmpty]
public SwitchParameter Force { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
if (this.Force.IsPresent
|| this.ShouldContinue(Properties.Resources.VirtualMachineExtensionRemovalConfirmation, Properties.Resources.VirtualMachineExtensionRemovalCaption))
{
var op = this.VirtualMachineExtensionClient.Delete(this.ResourceGroupName, this.VMName, this.Name);
WriteObject(op);
}
}
}
}
| kagamsft/azure-powershell | src/ResourceManager/Compute/Commands.Compute/Extension/CustomScript/RemoveAzureVMCustomScriptExtensionCommand.cs | C# | apache-2.0 | 2,606 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to run the tests."""
from __future__ import print_function
import sys
import unittest
# Change PYTHONPATH to include dependencies.
sys.path.insert(0, '.')
import utils.dependencies # pylint: disable=wrong-import-position
if __name__ == '__main__':
print('Using Python version {0!s}'.format(sys.version))
fail_unless_has_test_file = '--fail-unless-has-test-file' in sys.argv
setattr(unittest, 'fail_unless_has_test_file', fail_unless_has_test_file)
if fail_unless_has_test_file:
# Remove --fail-unless-has-test-file otherwise it will conflict with
# the argparse tests.
sys.argv.remove('--fail-unless-has-test-file')
dependency_helper = utils.dependencies.DependencyHelper()
if not dependency_helper.CheckTestDependencies():
sys.exit(1)
test_suite = unittest.TestLoader().discover('tests', pattern='*.py')
test_results = unittest.TextTestRunner(verbosity=2).run(test_suite)
if not test_results.wasSuccessful():
sys.exit(1)
| log2timeline/dfwinreg | run_tests.py | Python | apache-2.0 | 1,027 |
/**
* (C) Copyright IBM Corp. 2010, 2015
*
* 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.
*
*/
package com.ibm.bi.dml.test.integration.functions.piggybacking;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Test;
import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM;
import com.ibm.bi.dml.runtime.matrix.data.MatrixValue.CellIndex;
import com.ibm.bi.dml.test.integration.AutomatedTestBase;
import com.ibm.bi.dml.test.integration.TestConfiguration;
import com.ibm.bi.dml.test.utils.TestUtils;
public class PiggybackingTest2 extends AutomatedTestBase
{
private final static String TEST_NAME = "Piggybacking_iqm";
private final static String TEST_DIR = "functions/piggybacking/";
@Override
public void setUp()
{
addTestConfiguration(
TEST_NAME,
new TestConfiguration(TEST_DIR, TEST_NAME,
new String[] { "x", "iqm.scalar" }) );
}
/**
* Tests for a piggybacking bug.
*
* Specific issue is that the combineunary lop gets piggybacked
* into GMR while it should only be piggybacked into SortMR job.
*/
@Test
public void testPiggybacking_iqm()
{
RUNTIME_PLATFORM rtold = rtplatform;
// bug can be reproduced only when exec mode is HADOOP
rtplatform = RUNTIME_PLATFORM.HADOOP;
TestConfiguration config = getTestConfiguration(TEST_NAME);
String HOME = SCRIPT_DIR + TEST_DIR;
fullDMLScriptName = HOME + TEST_NAME + ".dml";
programArgs = new String[]{"-args", HOME + OUTPUT_DIR + config.getOutputFiles()[0] };
loadTestConfiguration(config);
boolean exceptionExpected = false;
runTest(true, exceptionExpected, null, -1);
HashMap<CellIndex, Double> d = TestUtils.readDMLScalarFromHDFS(HOME + OUTPUT_DIR + config.getOutputFiles()[0]);
Assert.assertEquals(d.get(new CellIndex(1,1)), Double.valueOf(1.0), 1e-10);
rtplatform = rtold;
}
} | wjuncdl/systemml | system-ml/src/test/java/com/ibm/bi/dml/test/integration/functions/piggybacking/PiggybackingTest2.java | Java | apache-2.0 | 2,357 |
#!/bin/bash
# Copyright 2014 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# A library of helper functions that each provider hosting Kubernetes must implement to use cluster/kube-*.sh scripts.
KUBE_ROOT=$(dirname "${BASH_SOURCE}")/../..
source "${KUBE_ROOT}/cluster/vagrant/${KUBE_CONFIG_FILE-"config-default.sh"}"
source "${KUBE_ROOT}/cluster/common.sh"
function detect-master () {
KUBE_MASTER_IP=$MASTER_IP
echo "KUBE_MASTER_IP: ${KUBE_MASTER_IP}" 1>&2
}
# Get minion IP addresses and store in KUBE_MINION_IP_ADDRESSES[]
function detect-minions {
echo "Minions already detected" 1>&2
KUBE_MINION_IP_ADDRESSES=("${MINION_IPS[@]}")
}
# Verify prereqs on host machine Also sets exports USING_KUBE_SCRIPTS=true so
# that our Vagrantfile doesn't error out.
function verify-prereqs {
for x in vagrant; do
if ! which "$x" >/dev/null; then
echo "Can't find $x in PATH, please fix and retry."
exit 1
fi
done
local vagrant_plugins=$(vagrant plugin list | sed '-es% .*$%%' '-es% *% %g' | tr ' ' $'\n')
local providers=(
# Format is:
# provider_ctl_executable vagrant_provider_name vagrant_provider_plugin_re
# either provider_ctl_executable or vagrant_provider_plugin_re can
# be blank (i.e., '') if none is needed by Vagrant (see, e.g.,
# virtualbox entry)
vmrun vmware_fusion vagrant-vmware-fusion
vmrun vmware_workstation vagrant-vmware-workstation
prlctl parallels vagrant-parallels
VBoxManage virtualbox ''
)
local provider_found=''
local provider_bin
local provider_name
local provider_plugin_re
while [ "${#providers[@]}" -gt 0 ]; do
provider_bin=${providers[0]}
provider_name=${providers[1]}
provider_plugin_re=${providers[2]}
providers=("${providers[@]:3}")
# If the provider is explicitly set, look only for that provider
if [ -n "${VAGRANT_DEFAULT_PROVIDER:-}" ] \
&& [ "${VAGRANT_DEFAULT_PROVIDER}" != "${provider_name}" ]; then
continue
fi
if ([ -z "${provider_bin}" ] \
|| which "${provider_bin}" >/dev/null 2>&1) \
&& ([ -z "${provider_plugin_re}" ] \
|| [ -n "$(echo "${vagrant_plugins}" | grep -E "^${provider_plugin_re}$")" ]); then
provider_found="${provider_name}"
# Stop after finding the first viable provider
break
fi
done
if [ -z "${provider_found}" ]; then
if [ -n "${VAGRANT_DEFAULT_PROVIDER}" ]; then
echo "Can't find the necessary components for the ${VAGRANT_DEFAULT_PROVIDER} vagrant provider, please fix and retry."
else
echo "Can't find the necessary components for any viable vagrant providers (e.g., virtualbox), please fix and retry."
fi
exit 1
fi
# Set VAGRANT_CWD to KUBE_ROOT so that we find the right Vagrantfile no
# matter what directory the tools are called from.
export VAGRANT_CWD="${KUBE_ROOT}"
export USING_KUBE_SCRIPTS=true
}
# Create a temp dir that'll be deleted at the end of this bash session.
#
# Vars set:
# KUBE_TEMP
function ensure-temp-dir {
if [[ -z ${KUBE_TEMP-} ]]; then
export KUBE_TEMP=$(mktemp -d -t kubernetes.XXXXXX)
trap 'rm -rf "${KUBE_TEMP}"' EXIT
fi
}
# Create a set of provision scripts for the master and each of the minions
function create-provision-scripts {
ensure-temp-dir
(
echo "#! /bin/bash"
echo "KUBE_ROOT=/vagrant"
echo "INSTANCE_PREFIX='${INSTANCE_PREFIX}'"
echo "MASTER_NAME='${INSTANCE_PREFIX}-master'"
echo "MASTER_IP='${MASTER_IP}'"
echo "MINION_NAMES=(${MINION_NAMES[@]})"
echo "MINION_IPS=(${MINION_IPS[@]})"
echo "NODE_IP='${MASTER_IP}'"
echo "CONTAINER_SUBNET='${CONTAINER_SUBNET}'"
echo "CONTAINER_NETMASK='${MASTER_CONTAINER_NETMASK}'"
echo "MASTER_CONTAINER_SUBNET='${MASTER_CONTAINER_SUBNET}'"
echo "CONTAINER_ADDR='${MASTER_CONTAINER_ADDR}'"
echo "MINION_CONTAINER_NETMASKS='${MINION_CONTAINER_NETMASKS[@]}'"
echo "MINION_CONTAINER_SUBNETS=(${MINION_CONTAINER_SUBNETS[@]})"
echo "SERVICE_CLUSTER_IP_RANGE='${SERVICE_CLUSTER_IP_RANGE}'"
echo "MASTER_USER='${MASTER_USER}'"
echo "MASTER_PASSWD='${MASTER_PASSWD}'"
echo "ENABLE_NODE_MONITORING='${ENABLE_NODE_MONITORING:-false}'"
echo "ENABLE_NODE_LOGGING='${ENABLE_NODE_LOGGING:-false}'"
echo "LOGGING_DESTINATION='${LOGGING_DESTINATION:-}'"
echo "ENABLE_CLUSTER_DNS='${ENABLE_CLUSTER_DNS:-false}'"
echo "DNS_SERVER_IP='${DNS_SERVER_IP:-}'"
echo "DNS_DOMAIN='${DNS_DOMAIN:-}'"
echo "DNS_REPLICAS='${DNS_REPLICAS:-}'"
echo "RUNTIME_CONFIG='${RUNTIME_CONFIG:-}'"
echo "ADMISSION_CONTROL='${ADMISSION_CONTROL:-}'"
echo "DOCKER_OPTS='${EXTRA_DOCKER_OPTS-}'"
echo "VAGRANT_DEFAULT_PROVIDER='${VAGRANT_DEFAULT_PROVIDER:-}'"
awk '!/^#/' "${KUBE_ROOT}/cluster/vagrant/provision-network.sh"
awk '!/^#/' "${KUBE_ROOT}/cluster/vagrant/provision-master.sh"
) > "${KUBE_TEMP}/master-start.sh"
for (( i=0; i<${#MINION_NAMES[@]}; i++)); do
(
echo "#! /bin/bash"
echo "MASTER_NAME='${MASTER_NAME}'"
echo "MASTER_IP='${MASTER_IP}'"
echo "MINION_NAMES=(${MINION_NAMES[@]})"
echo "MINION_NAME=(${MINION_NAMES[$i]})"
echo "MINION_IPS=(${MINION_IPS[@]})"
echo "MINION_IP='${MINION_IPS[$i]}'"
echo "MINION_ID='$i'"
echo "NODE_IP='${MINION_IPS[$i]}'"
echo "MASTER_CONTAINER_SUBNET='${MASTER_CONTAINER_SUBNET}'"
echo "CONTAINER_ADDR='${MINION_CONTAINER_ADDRS[$i]}'"
echo "CONTAINER_NETMASK='${MINION_CONTAINER_NETMASKS[$i]}'"
echo "MINION_CONTAINER_SUBNETS=(${MINION_CONTAINER_SUBNETS[@]})"
echo "CONTAINER_SUBNET='${CONTAINER_SUBNET}'"
echo "DOCKER_OPTS='${EXTRA_DOCKER_OPTS-}'"
echo "VAGRANT_DEFAULT_PROVIDER='${VAGRANT_DEFAULT_PROVIDER:-}'"
awk '!/^#/' "${KUBE_ROOT}/cluster/vagrant/provision-network.sh"
awk '!/^#/' "${KUBE_ROOT}/cluster/vagrant/provision-minion.sh"
) > "${KUBE_TEMP}/minion-start-${i}.sh"
done
}
function verify-cluster {
# TODO: How does the user know the difference between "tak[ing] some
# time" and "loop[ing] forever"? Can we give more specific feedback on
# whether "an error" has occurred?
echo "Each machine instance has been created/updated."
echo " Now waiting for the Salt provisioning process to complete on each machine."
echo " This can take some time based on your network, disk, and cpu speed."
echo " It is possible for an error to occur during Salt provision of cluster and this could loop forever."
# verify master has all required daemons
echo "Validating master"
local machine="master"
local -a required_daemon=("salt-master" "salt-minion" "nginx" "kubelet")
local validated="1"
until [[ "$validated" == "0" ]]; do
validated="0"
local daemon
for daemon in "${required_daemon[@]}"; do
vagrant ssh "$machine" -c "which '${daemon}'" >/dev/null 2>&1 || {
printf "."
validated="1"
sleep 2
}
done
done
# verify each minion has all required daemons
local i
for (( i=0; i<${#MINION_NAMES[@]}; i++)); do
echo "Validating ${VAGRANT_MINION_NAMES[$i]}"
local machine=${VAGRANT_MINION_NAMES[$i]}
local -a required_daemon=("salt-minion" "kubelet" "docker")
local validated="1"
until [[ "$validated" == "0" ]]; do
validated="0"
local daemon
for daemon in "${required_daemon[@]}"; do
vagrant ssh "$machine" -c "which $daemon" >/dev/null 2>&1 || {
printf "."
validated="1"
sleep 2
}
done
done
done
echo
echo "Waiting for each minion to be registered with cloud provider"
for (( i=0; i<${#MINION_IPS[@]}; i++)); do
local machine="${MINION_IPS[$i]}"
local count="0"
until [[ "$count" == "1" ]]; do
local minions
minions=$("${KUBE_ROOT}/cluster/kubectl.sh" get nodes -o template -t '{{range.items}}{{.metadata.name}}:{{end}}' --api-version=v1beta3)
count=$(echo $minions | grep -c "${MINION_IPS[i]}") || {
printf "."
sleep 2
count="0"
}
done
done
# By this time, all kube api calls should work, so no need to loop and retry.
echo "Validating we can run kubectl commands."
vagrant ssh master --command "kubectl get pods" || {
echo "WARNING: kubectl to localhost failed. This could mean localhost is not bound to an IP"
}
(
echo
echo "Kubernetes cluster is running. The master is running at:"
echo
echo " https://${MASTER_IP}"
echo
echo "The user name and password to use is located in ~/.kubernetes_vagrant_auth."
echo
)
}
# Instantiate a kubernetes cluster
function kube-up {
get-password
create-provision-scripts
vagrant up
export KUBE_CERT="/tmp/$RANDOM-kubecfg.crt"
export KUBE_KEY="/tmp/$RANDOM-kubecfg.key"
export CA_CERT="/tmp/$RANDOM-kubernetes.ca.crt"
export CONTEXT="vagrant"
(
umask 077
vagrant ssh master -- sudo cat /srv/kubernetes/kubecfg.crt >"${KUBE_CERT}" 2>/dev/null
vagrant ssh master -- sudo cat /srv/kubernetes/kubecfg.key >"${KUBE_KEY}" 2>/dev/null
vagrant ssh master -- sudo cat /srv/kubernetes/ca.crt >"${CA_CERT}" 2>/dev/null
create-kubeconfig
)
verify-cluster
}
# Delete a kubernetes cluster
function kube-down {
vagrant destroy -f
}
# Update a kubernetes cluster with latest source
function kube-push {
get-password
create-provision-scripts
vagrant provision
}
# Execute prior to running tests to build a release if required for env
function test-build-release {
# Make a release
"${KUBE_ROOT}/build/release.sh"
}
# Execute prior to running tests to initialize required structure
function test-setup {
echo "Vagrant test setup complete" 1>&2
}
# Execute after running tests to perform any required clean-up
function test-teardown {
kube-down
}
# Set the {user} and {password} environment values required to interact with provider
function get-password {
export KUBE_USER=vagrant
export KUBE_PASSWORD=vagrant
echo "Using credentials: $KUBE_USER:$KUBE_PASSWORD" 1>&2
}
# Find the minion name based on the IP address
function find-vagrant-name-by-ip {
local ip="$1"
local ip_pattern="${MINION_IP_BASE}(.*)"
# This is subtle. We map 10.245.2.2 -> minion-1. We do this by matching a
# regexp and using the capture to construct the name.
[[ $ip =~ $ip_pattern ]] || {
return 1
}
echo "minion-$((${BASH_REMATCH[1]} - 1))"
}
# Find the vagrant machine name based on the host name of the minion
function find-vagrant-name-by-minion-name {
local ip="$1"
if [[ "$ip" == "${INSTANCE_PREFIX}-master" ]]; then
echo "master"
return $?
fi
local ip_pattern="${INSTANCE_PREFIX}-minion-(.*)"
[[ $ip =~ $ip_pattern ]] || {
return 1
}
echo "minion-${BASH_REMATCH[1]}"
}
# SSH to a node by name or IP ($1) and run a command ($2).
function ssh-to-node {
local node="$1"
local cmd="$2"
local machine
machine=$(find-vagrant-name-by-ip $node) || true
[[ -n ${machine-} ]] || machine=$(find-vagrant-name-by-minion-name $node) || true
[[ -n ${machine-} ]] || {
echo "Cannot find machine to ssh to: $1"
return 1
}
vagrant ssh "${machine}" -c "${cmd}"
}
# Restart the kube-proxy on a node ($1)
function restart-kube-proxy {
ssh-to-node "$1" "sudo systemctl restart kube-proxy"
}
# Restart the apiserver
function restart-apiserver {
ssh-to-node "$1" "sudo systemctl restart kube-apiserver"
}
# Perform preparations required to run e2e tests
function prepare-e2e() {
echo "Vagrant doesn't need special preparations for e2e tests" 1>&2
}
| leroy-chen/kubernetes | cluster/vagrant/util.sh | Shell | apache-2.0 | 12,100 |
package sign
import (
"testing"
"github.com/coredns/caddy"
)
func TestParse(t *testing.T) {
tests := []struct {
input string
shouldErr bool
exp *Signer
}{
{`sign testdata/db.miek.nl miek.nl {
key file testdata/Kmiek.nl.+013+59725
}`,
false,
&Signer{
keys: []Pair{},
origin: "miek.nl.",
dbfile: "testdata/db.miek.nl",
directory: "/var/lib/coredns",
signedfile: "db.miek.nl.signed",
},
},
{`sign testdata/db.miek.nl example.org {
key file testdata/Kmiek.nl.+013+59725
directory testdata
}`,
false,
&Signer{
keys: []Pair{},
origin: "example.org.",
dbfile: "testdata/db.miek.nl",
directory: "testdata",
signedfile: "db.example.org.signed",
},
},
// errors
{`sign db.example.org {
key file /etc/coredns/keys/Kexample.org
}`,
true,
nil,
},
}
for i, tc := range tests {
c := caddy.NewTestController("dns", tc.input)
sign, err := parse(c)
if err == nil && tc.shouldErr {
t.Fatalf("Test %d expected errors, but got no error", i)
}
if err != nil && !tc.shouldErr {
t.Fatalf("Test %d expected no errors, but got '%v'", i, err)
}
if tc.shouldErr {
continue
}
signer := sign.signers[0]
if x := signer.origin; x != tc.exp.origin {
t.Errorf("Test %d expected %s as origin, got %s", i, tc.exp.origin, x)
}
if x := signer.dbfile; x != tc.exp.dbfile {
t.Errorf("Test %d expected %s as dbfile, got %s", i, tc.exp.dbfile, x)
}
if x := signer.directory; x != tc.exp.directory {
t.Errorf("Test %d expected %s as directory, got %s", i, tc.exp.directory, x)
}
if x := signer.signedfile; x != tc.exp.signedfile {
t.Errorf("Test %d expected %s as signedfile, got %s", i, tc.exp.signedfile, x)
}
}
}
| miekg/coredns | plugin/sign/setup_test.go | GO | apache-2.0 | 1,784 |
/*
* 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.
*/
package org.apache.ode.scheduler.simple;
import javax.sql.DataSource;
import javax.transaction.TransactionManager;
import org.apache.geronimo.connector.outbound.GenericConnectionManager;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.LocalTransactions;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PoolingSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.SinglePool;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.TransactionSupport;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTracker;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTrackingCoordinator;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import org.apache.ode.utils.GUID;
import org.tranql.connector.jdbc.JDBCDriverMCF;
public class GeronimoDelegateSupport extends DelegateSupport {
private static final int CONNECTION_MAX_WAIT_MILLIS = 30000;
private static final int CONNECTION_MAX_IDLE_MINUTES = 5;
private GenericConnectionManager _connectionManager;
public GeronimoDelegateSupport(TransactionManager txm) throws Exception {
super(txm);
}
@Override
protected void initialize(TransactionManager txm) throws Exception {
_ds = createGeronimoDataSource(txm, "jdbc:hsqldb:mem:" + new GUID().toString(), "org.hsqldb.jdbcDriver", "sa", "");
setup();
_del = new JdbcDelegate(_ds);
}
private DataSource createGeronimoDataSource(TransactionManager txm, String url, String driverClass, String username,String password) {
TransactionSupport transactionSupport = LocalTransactions.INSTANCE;
ConnectionTracker connectionTracker = new ConnectionTrackingCoordinator();
PoolingSupport poolingSupport = new SinglePool(1, 1,
CONNECTION_MAX_WAIT_MILLIS,
CONNECTION_MAX_IDLE_MINUTES,
true, // match one
false, // match all
false); // select one assume match
_connectionManager = new GenericConnectionManager(
transactionSupport,
poolingSupport,
null,
connectionTracker,
(RecoverableTransactionManager) txm,
getClass().getName(),
getClass().getClassLoader());
JDBCDriverMCF mcf = new JDBCDriverMCF();
try {
mcf.setDriver(driverClass);
mcf.setConnectionURL(url);
if (username != null) {
mcf.setUserName(username);
}
if (password != null) {
mcf.setPassword(password);
}
_connectionManager.doStart();
return (DataSource) mcf.createConnectionFactory(_connectionManager);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
| firzhan/wso2-ode | scheduler-simple/src/test/java/org/apache/ode/scheduler/simple/GeronimoDelegateSupport.java | Java | apache-2.0 | 3,782 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
package org.elasticsearch.common.lucene.search.function;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.ToStringUtils;
import org.elasticsearch.common.lucene.docset.DocIdSets;
import java.io.IOException;
import java.util.*;
/**
* A query that allows for a pluggable boost function / filter. If it matches
* the filter, it will be boosted by the formula.
*/
public class FiltersFunctionScoreQuery extends Query {
public static class FilterFunction {
public final Filter filter;
public final ScoreFunction function;
public FilterFunction(Filter filter, ScoreFunction function) {
this.filter = filter;
this.function = function;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
FilterFunction that = (FilterFunction) o;
if (filter != null ? !filter.equals(that.filter) : that.filter != null)
return false;
if (function != null ? !function.equals(that.function) : that.function != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = filter != null ? filter.hashCode() : 0;
result = 31 * result + (function != null ? function.hashCode() : 0);
return result;
}
}
public static enum ScoreMode {
First, Avg, Max, Sum, Min, Multiply
}
Query subQuery;
final FilterFunction[] filterFunctions;
final ScoreMode scoreMode;
final float maxBoost;
protected CombineFunction combineFunction;
public FiltersFunctionScoreQuery(Query subQuery, ScoreMode scoreMode, FilterFunction[] filterFunctions, float maxBoost) {
this.subQuery = subQuery;
this.scoreMode = scoreMode;
this.filterFunctions = filterFunctions;
this.maxBoost = maxBoost;
combineFunction = CombineFunction.MULT;
}
public FiltersFunctionScoreQuery setCombineFunction(CombineFunction combineFunction) {
this.combineFunction = combineFunction;
return this;
}
public Query getSubQuery() {
return subQuery;
}
public FilterFunction[] getFilterFunctions() {
return filterFunctions;
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
Query newQ = subQuery.rewrite(reader);
if (newQ == subQuery)
return this;
FiltersFunctionScoreQuery bq = (FiltersFunctionScoreQuery) this.clone();
bq.subQuery = newQ;
return bq;
}
@Override
public void extractTerms(Set<Term> terms) {
subQuery.extractTerms(terms);
}
@Override
public Weight createWeight(IndexSearcher searcher) throws IOException {
Weight subQueryWeight = subQuery.createWeight(searcher);
return new CustomBoostFactorWeight(subQueryWeight, filterFunctions.length);
}
class CustomBoostFactorWeight extends Weight {
final Weight subQueryWeight;
final Bits[] docSets;
public CustomBoostFactorWeight(Weight subQueryWeight, int filterFunctionLength) throws IOException {
this.subQueryWeight = subQueryWeight;
this.docSets = new Bits[filterFunctionLength];
}
public Query getQuery() {
return FiltersFunctionScoreQuery.this;
}
@Override
public float getValueForNormalization() throws IOException {
float sum = subQueryWeight.getValueForNormalization();
sum *= getBoost() * getBoost();
return sum;
}
@Override
public void normalize(float norm, float topLevelBoost) {
subQueryWeight.normalize(norm, topLevelBoost * getBoost());
}
@Override
public Scorer scorer(AtomicReaderContext context, boolean scoreDocsInOrder, boolean topScorer, Bits acceptDocs) throws IOException {
// we ignore scoreDocsInOrder parameter, because we need to score in
// order if documents are scored with a script. The
// ShardLookup depends on in order scoring.
Scorer subQueryScorer = subQueryWeight.scorer(context, true, false, acceptDocs);
if (subQueryScorer == null) {
return null;
}
for (int i = 0; i < filterFunctions.length; i++) {
FilterFunction filterFunction = filterFunctions[i];
filterFunction.function.setNextReader(context);
docSets[i] = DocIdSets.toSafeBits(context.reader(), filterFunction.filter.getDocIdSet(context, acceptDocs));
}
return new CustomBoostFactorScorer(this, subQueryScorer, scoreMode, filterFunctions, maxBoost, docSets, combineFunction);
}
@Override
public Explanation explain(AtomicReaderContext context, int doc) throws IOException {
Explanation subQueryExpl = subQueryWeight.explain(context, doc);
if (!subQueryExpl.isMatch()) {
return subQueryExpl;
}
// First: Gather explanations for all filters
List<ComplexExplanation> filterExplanations = new ArrayList<ComplexExplanation>();
for (FilterFunction filterFunction : filterFunctions) {
Bits docSet = DocIdSets.toSafeBits(context.reader(),
filterFunction.filter.getDocIdSet(context, context.reader().getLiveDocs()));
if (docSet.get(doc)) {
filterFunction.function.setNextReader(context);
Explanation functionExplanation = filterFunction.function.explainScore(doc, subQueryExpl);
double factor = functionExplanation.getValue();
float sc = CombineFunction.toFloat(factor);
ComplexExplanation filterExplanation = new ComplexExplanation(true, sc, "function score, product of:");
filterExplanation.addDetail(new Explanation(1.0f, "match filter: " + filterFunction.filter.toString()));
filterExplanation.addDetail(functionExplanation);
filterExplanations.add(filterExplanation);
}
}
if (filterExplanations.size() == 0) {
float sc = getBoost() * subQueryExpl.getValue();
Explanation res = new ComplexExplanation(true, sc, "function score, no filter match, product of:");
res.addDetail(subQueryExpl);
res.addDetail(new Explanation(getBoost(), "queryBoost"));
return res;
}
// Second: Compute the factor that would have been computed by the
// filters
double factor = 1.0;
switch (scoreMode) {
case First:
factor = filterExplanations.get(0).getValue();
break;
case Max:
factor = Double.NEGATIVE_INFINITY;
for (int i = 0; i < filterExplanations.size(); i++) {
factor = Math.max(filterExplanations.get(i).getValue(), factor);
}
break;
case Min:
factor = Double.POSITIVE_INFINITY;
for (int i = 0; i < filterExplanations.size(); i++) {
factor = Math.min(filterExplanations.get(i).getValue(), factor);
}
break;
case Multiply:
for (int i = 0; i < filterExplanations.size(); i++) {
factor *= filterExplanations.get(i).getValue();
}
break;
default: // Avg / Total
double totalFactor = 0.0f;
int count = 0;
for (int i = 0; i < filterExplanations.size(); i++) {
totalFactor += filterExplanations.get(i).getValue();
count++;
}
if (count != 0) {
factor = totalFactor;
if (scoreMode == ScoreMode.Avg) {
factor /= count;
}
}
}
ComplexExplanation factorExplanaition = new ComplexExplanation(true, CombineFunction.toFloat(factor),
"function score, score mode [" + scoreMode.toString().toLowerCase(Locale.ROOT) + "]");
for (int i = 0; i < filterExplanations.size(); i++) {
factorExplanaition.addDetail(filterExplanations.get(i));
}
return combineFunction.explain(getBoost(), subQueryExpl, factorExplanaition, maxBoost);
}
}
static class CustomBoostFactorScorer extends Scorer {
private final float subQueryBoost;
private final Scorer scorer;
private final FilterFunction[] filterFunctions;
private final ScoreMode scoreMode;
private final float maxBoost;
private final Bits[] docSets;
private final CombineFunction scoreCombiner;
private CustomBoostFactorScorer(CustomBoostFactorWeight w, Scorer scorer, ScoreMode scoreMode, FilterFunction[] filterFunctions,
float maxBoost, Bits[] docSets, CombineFunction scoreCombiner) throws IOException {
super(w);
this.subQueryBoost = w.getQuery().getBoost();
this.scorer = scorer;
this.scoreMode = scoreMode;
this.filterFunctions = filterFunctions;
this.maxBoost = maxBoost;
this.docSets = docSets;
this.scoreCombiner = scoreCombiner;
}
@Override
public int docID() {
return scorer.docID();
}
@Override
public int advance(int target) throws IOException {
return scorer.advance(target);
}
@Override
public int nextDoc() throws IOException {
return scorer.nextDoc();
}
@Override
public float score() throws IOException {
int docId = scorer.docID();
double factor = 1.0f;
float subQueryScore = scorer.score();
if (scoreMode == ScoreMode.First) {
for (int i = 0; i < filterFunctions.length; i++) {
if (docSets[i].get(docId)) {
factor = filterFunctions[i].function.score(docId, subQueryScore);
break;
}
}
} else if (scoreMode == ScoreMode.Max) {
double maxFactor = Double.NEGATIVE_INFINITY;
for (int i = 0; i < filterFunctions.length; i++) {
if (docSets[i].get(docId)) {
maxFactor = Math.max(filterFunctions[i].function.score(docId, subQueryScore), maxFactor);
}
}
if (maxFactor != Float.NEGATIVE_INFINITY) {
factor = maxFactor;
}
} else if (scoreMode == ScoreMode.Min) {
double minFactor = Double.POSITIVE_INFINITY;
for (int i = 0; i < filterFunctions.length; i++) {
if (docSets[i].get(docId)) {
minFactor = Math.min(filterFunctions[i].function.score(docId, subQueryScore), minFactor);
}
}
if (minFactor != Float.POSITIVE_INFINITY) {
factor = minFactor;
}
} else if (scoreMode == ScoreMode.Multiply) {
for (int i = 0; i < filterFunctions.length; i++) {
if (docSets[i].get(docId)) {
factor *= filterFunctions[i].function.score(docId, subQueryScore);
}
}
} else { // Avg / Total
double totalFactor = 0.0f;
int count = 0;
for (int i = 0; i < filterFunctions.length; i++) {
if (docSets[i].get(docId)) {
totalFactor += filterFunctions[i].function.score(docId, subQueryScore);
count++;
}
}
if (count != 0) {
factor = totalFactor;
if (scoreMode == ScoreMode.Avg) {
factor /= count;
}
}
}
return scoreCombiner.combine(subQueryBoost, subQueryScore, factor, maxBoost);
}
@Override
public int freq() throws IOException {
return scorer.freq();
}
@Override
public long cost() {
return scorer.cost();
}
}
public String toString(String field) {
StringBuilder sb = new StringBuilder();
sb.append("function score (").append(subQuery.toString(field)).append(", functions: [");
for (FilterFunction filterFunction : filterFunctions) {
sb.append("{filter(").append(filterFunction.filter).append("), function [").append(filterFunction.function).append("]}");
}
sb.append("])");
sb.append(ToStringUtils.boost(getBoost()));
return sb.toString();
}
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass())
return false;
FiltersFunctionScoreQuery other = (FiltersFunctionScoreQuery) o;
if (this.getBoost() != other.getBoost())
return false;
if (!this.subQuery.equals(other.subQuery)) {
return false;
}
return Arrays.equals(this.filterFunctions, other.filterFunctions);
}
public int hashCode() {
return subQuery.hashCode() + 31 * Arrays.hashCode(filterFunctions) ^ Float.floatToIntBits(getBoost());
}
}
| alexksikes/elasticsearch | src/main/java/org/elasticsearch/common/lucene/search/function/FiltersFunctionScoreQuery.java | Java | apache-2.0 | 14,891 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.versioning;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.cluster.coordination.LinearizabilityChecker;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.discovery.AbstractDisruptionTestCase;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.disruption.ServiceDisruptionScheme;
import org.elasticsearch.threadpool.Scheduler;
import org.elasticsearch.threadpool.ThreadPool;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
/**
* This test stress tests CAS updates using sequence number based versioning (ifPrimaryTerm/ifSeqNo).
*
* <p>The following is a summary of the expected CAS write behaviour of the system:</p>
*
* <ul>
* <li>acknowledged CAS writes are guaranteed to have taken place between invocation and response and cannot be lost. It is
* guaranteed that the previous value had the specified primaryTerm and seqNo</li>
* <li>CAS writes resulting in a VersionConflictEngineException might or might not have taken place or may take place in the future
* provided the primaryTerm and seqNo still matches. The reason we cannot assume it will not take place after receiving the failure
* is that a request can fork into two because of retries on disconnect, and now race against itself. The retry might complete (and do a
* dirty or stale read) before the forked off request gets to execute, and that one might still subsequently succeed.
*
* Such writes are not necessarily fully replicated and can be lost. There is no
* guarantee that the previous value did not have the specified primaryTerm and seqNo</li>
* <li>CAS writes with other exceptions might or might not have taken place. If they have taken place, then after invocation but not
* necessarily before response. Such writes are not necessarily fully replicated and can be lost.
* </li>
* </ul>
*
* A deeper technical explanation of the behaviour is given here:
*
* <ul>
* <li>A CAS can fail on its own write in at least two ways. In both cases, the write might have taken place even though we get a
* version conflict response. Even though we might observe the write (by reading (not done in this test) or another CAS write), the
* write could be lost since it is not fully replicated. Details:
* <ul>
* <li>A write is successfully stored on primary and one replica (r1). Replication to second replica fails, primary is demoted
* and r1 is promoted to primary. The request is repeated on r1, but this time the request fails due to its own write.</li>
* <li>A coordinator sends write to primary, which stores write successfully (and replicates it). Connection is lost before
* response is sent back. Once connection is back, coordinator will retry against either same or new primary, but this time the
* request will fail due to its own write.
* </li>
* </ul>
* </li>
* <li>A CAS can fail on stale reads. A CAS failure is only checked on the supposedly primary node. However, the primary might not be
* the newest primary (could be isolated or just not have been told yet). So a CAS check is suspect to stale reads (like any
* read) and can thus fail due to reading stale data. Notice that a CAS success is fully replicated and thus guaranteed to not
* suffer from stale (or dirty) reads.
* </li>
* <li>A CAS can fail on a dirty read, i.e., a non-replicated write that ends up being discarded.</li>
* <li>For any other failure, we do not know if the write will succeed after the failure. However, we do know that if we
* subsequently get back a CAS success with seqNo s, any previous failures with ifSeqNo < s will not be able to succeed (but could
* produce dirty writes on a stale primary).
* </li>
* <li>A CAS failure or any other failure can eventually succeed after receiving the failure response due to reroute and retries,
* see above.</li>
* <li>A CAS failure throws a VersionConflictEngineException which does not directly contain the current seqno/primary-term to use for
* the next request. It is contained in the message (and we parse it out in the test), but notice that the numbers given here could be
* stale or dirty, i.e., come from a stale primary or belong to a write that ends up being discarded.</li>
* </ul>
*/
@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, minNumDataNodes = 4, maxNumDataNodes = 6)
public class ConcurrentSeqNoVersioningIT extends AbstractDisruptionTestCase {
private static final Pattern EXTRACT_VERSION = Pattern.compile("current document has seqNo \\[(\\d+)\\] and primary term \\[(\\d+)\\]");
// Test info: disrupt network for up to 8s in a number of rounds and check that we only get true positive CAS results when running
// multiple threads doing CAS updates.
// Wait up to 1 minute (+10s in thread to ensure it does not time out) for threads to complete previous round before initiating next
// round.
public void testSeqNoCASLinearizability() {
final int disruptTimeSeconds = scaledRandomIntBetween(1, 8);
assertAcked(
prepareCreate("test").setSettings(
Settings.builder()
.put(indexSettings())
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1 + randomInt(2))
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, randomInt(3))
)
);
ensureGreen();
int numberOfKeys = randomIntBetween(1, 10);
logger.info("--> Indexing initial doc for {} keys", numberOfKeys);
List<Partition> partitions = IntStream.range(0, numberOfKeys)
.mapToObj(i -> client().prepareIndex("test").setId("ID:" + i).setSource("value", -1).get())
.map(response -> new Partition(response.getId(), new Version(response.getPrimaryTerm(), response.getSeqNo())))
.collect(Collectors.toList());
int threadCount = randomIntBetween(3, 20);
CyclicBarrier roundBarrier = new CyclicBarrier(threadCount + 1); // +1 for main thread.
List<CASUpdateThread> threads = IntStream.range(0, threadCount)
.mapToObj(i -> new CASUpdateThread(i, roundBarrier, partitions, disruptTimeSeconds + 1))
.collect(Collectors.toList());
logger.info("--> Starting {} threads", threadCount);
threads.forEach(Thread::start);
try {
int rounds = randomIntBetween(2, 5);
logger.info("--> Running {} rounds", rounds);
for (int i = 0; i < rounds; ++i) {
ServiceDisruptionScheme disruptionScheme = addRandomDisruptionScheme();
roundBarrier.await(1, TimeUnit.MINUTES);
disruptionScheme.startDisrupting();
logger.info("--> round {}", i);
try {
roundBarrier.await(disruptTimeSeconds, TimeUnit.SECONDS);
} catch (TimeoutException e) {
roundBarrier.reset();
}
internalCluster().clearDisruptionScheme(false);
// heal cluster faster to reduce test time.
ensureFullyConnectedCluster();
}
} catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
logger.error("Timed out, dumping stack traces of all threads:");
threads.forEach(thread -> logger.info(thread.toString() + ":\n" + ExceptionsHelper.formatStackTrace(thread.getStackTrace())));
throw new RuntimeException(e);
} finally {
logger.info("--> terminating test");
threads.forEach(CASUpdateThread::terminate);
threads.forEach(CASUpdateThread::await);
threads.stream().filter(Thread::isAlive).forEach(t -> fail("Thread still alive: " + t));
}
partitions.forEach(Partition::assertLinearizable);
}
private class CASUpdateThread extends Thread {
private final CyclicBarrier roundBarrier;
private final List<Partition> partitions;
private final int timeout;
private volatile boolean stop;
private final Random random = new Random(randomLong());
private CASUpdateThread(int threadNum, CyclicBarrier roundBarrier, List<Partition> partitions, int timeout) {
super("CAS-Update-" + threadNum);
this.roundBarrier = roundBarrier;
this.partitions = partitions;
this.timeout = timeout;
setDaemon(true);
}
public void run() {
while (stop == false) {
try {
roundBarrier.await(70, TimeUnit.SECONDS);
int numberOfUpdates = randomIntBetween(3, 13) * partitions.size();
for (int i = 0; i < numberOfUpdates; ++i) {
final int keyIndex = random.nextInt(partitions.size());
final Partition partition = partitions.get(keyIndex);
final int seqNoChangePct = random.nextInt(100);
// we use either the latest observed or the latest successful version, to increase chance of getting successful
// CAS'es and races. If we were to use only the latest successful version, any CAS fail on own write would mean that
// all future CAS'es would fail unless we guess the seqno/term below. On the other hand, using latest observed
// version exclusively we risk a single CAS fail on a dirty read to cause the same. Doing both randomly and adding
// variance to seqno/term should ensure we progress fine in most runs.
Version version = random.nextBoolean() ? partition.latestObservedVersion() : partition.latestSuccessfulVersion();
if (seqNoChangePct < 10) {
version = version.nextSeqNo(random.nextInt(4) + 1);
} else if (seqNoChangePct < 15) {
version = version.previousSeqNo(random.nextInt(4) + 1);
}
final int termChangePct = random.nextInt(100);
if (termChangePct < 5) {
version = version.nextTerm();
} else if (termChangePct < 10) {
version = version.previousTerm();
}
IndexRequest indexRequest = new IndexRequest("test").id(partition.id)
.source("value", random.nextInt())
.setIfPrimaryTerm(version.primaryTerm)
.setIfSeqNo(version.seqNo);
Consumer<HistoryOutput> historyResponse = partition.invoke(version);
try {
// we should be able to remove timeout or fail hard on timeouts
IndexResponse indexResponse = client().index(indexRequest).actionGet(timeout, TimeUnit.SECONDS);
IndexResponseHistoryOutput historyOutput = new IndexResponseHistoryOutput(indexResponse);
historyResponse.accept(historyOutput);
// validate version and seqNo strictly increasing for successful CAS to avoid that overhead during
// linearizability checking.
assertThat(historyOutput.outputVersion, greaterThan(version));
assertThat(historyOutput.outputVersion.seqNo, greaterThan(version.seqNo));
} catch (VersionConflictEngineException e) {
// if we supplied an input version <= latest successful version, we can safely assume that any failed
// operation will no longer be able to complete after the next successful write and we can therefore terminate
// the operation wrt. linearizability.
// todo: collect the failed responses and terminate when CAS with higher output version is successful, since
// this is the guarantee we offer.
if (version.compareTo(partition.latestSuccessfulVersion()) <= 0) {
historyResponse.accept(new CASFailureHistoryOutput(e));
}
} catch (RuntimeException e) {
// if we supplied an input version <= to latest successful version, we can safely assume that any failed
// operation will no longer be able to complete after the next successful write and we can therefore terminate
// the operation wrt. linearizability.
// todo: collect the failed responses and terminate when CAS with higher output version is successful, since
// this is the guarantee we offer.
if (version.compareTo(partition.latestSuccessfulVersion()) <= 0) {
historyResponse.accept(new FailureHistoryOutput());
}
logger.info(
new ParameterizedMessage("Received failure for request [{}], version [{}]", indexRequest, version),
e
);
if (stop) {
// interrupt often comes as a RuntimeException so check to stop here too.
return;
}
}
}
} catch (InterruptedException e) {
assert stop : "should only be interrupted when stopped";
} catch (BrokenBarrierException e) {
// a thread can go here either because it completed before disruption ended, timeout on main thread causes broken
// barrier
} catch (TimeoutException e) {
// this is timeout on the barrier, unexpected.
throw new AssertionError("Unexpected timeout in thread: " + Thread.currentThread(), e);
}
}
}
public void terminate() {
stop = true;
this.interrupt();
}
public void await() {
try {
join(60000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
/**
* Our version, which is primaryTerm,seqNo.
*/
private static final class Version implements NamedWriteable, Comparable<Version> {
public final long primaryTerm;
public final long seqNo;
Version(long primaryTerm, long seqNo) {
this.primaryTerm = primaryTerm;
this.seqNo = seqNo;
}
Version(StreamInput input) throws IOException {
this.primaryTerm = input.readLong();
this.seqNo = input.readLong();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Version version = (Version) o;
return primaryTerm == version.primaryTerm && seqNo == version.seqNo;
}
@Override
public int hashCode() {
return Objects.hash(primaryTerm, seqNo);
}
@Override
public int compareTo(Version other) {
int termCompare = Long.compare(primaryTerm, other.primaryTerm);
if (termCompare != 0) return termCompare;
return Long.compare(seqNo, other.seqNo);
}
@Override
public String toString() {
return "{" + "primaryTerm=" + primaryTerm + ", seqNo=" + seqNo + '}';
}
public Version nextSeqNo(int increment) {
return new Version(primaryTerm, seqNo + increment);
}
public Version previousSeqNo(int decrement) {
return new Version(primaryTerm, Math.max(seqNo - decrement, 0));
}
@Override
public String getWriteableName() {
return "version";
}
public void writeTo(StreamOutput out) throws IOException {
out.writeLong(primaryTerm);
out.writeLong(seqNo);
}
public Version previousTerm() {
return new Version(primaryTerm - 1, seqNo);
}
public Version nextTerm() {
return new Version(primaryTerm + 1, seqNo);
}
}
private static class AtomicVersion {
private final AtomicReference<Version> current;
private AtomicVersion(Version initialVersion) {
this.current = new AtomicReference<>(initialVersion);
}
public Version get() {
return current.get();
}
public void consume(Version version) {
if (version == null) {
return;
}
this.current.updateAndGet(currentVersion -> version.compareTo(currentVersion) <= 0 ? currentVersion : version);
}
}
private class Partition {
private final String id;
private final AtomicVersion latestSuccessfulVersion;
private final AtomicVersion latestObservedVersion;
private final Version initialVersion;
private final LinearizabilityChecker.History history = new LinearizabilityChecker.History();
private Partition(String id, Version initialVersion) {
this.id = id;
this.latestSuccessfulVersion = new AtomicVersion(initialVersion);
this.latestObservedVersion = new AtomicVersion(initialVersion);
this.initialVersion = initialVersion;
}
// latest version that was observed, possibly dirty read of a write that does not survive
public Version latestObservedVersion() {
return latestObservedVersion.get();
}
// latest version for which we got a successful response on a write.
public Version latestSuccessfulVersion() {
return latestSuccessfulVersion.get();
}
public Consumer<HistoryOutput> invoke(Version version) {
int eventId = history.invoke(version);
logger.debug("invocation partition ({}) event ({}) version ({})", id, eventId, version);
return output -> consumeOutput(output, eventId);
}
private void consumeOutput(HistoryOutput output, int eventId) {
history.respond(eventId, output);
logger.debug("response partition ({}) event ({}) output ({})", id, eventId, output);
latestObservedVersion.consume(output.getVersion());
if (output instanceof IndexResponseHistoryOutput) {
latestSuccessfulVersion.consume(output.getVersion());
}
}
public void assertLinearizable() {
logger.info(
"--> Linearizability checking history of size: {} for key: {} and initialVersion: {}: {}",
history.size(),
id,
initialVersion,
history
);
LinearizabilityChecker.SequentialSpec spec = new CASSequentialSpec(initialVersion);
boolean linearizable = false;
try {
final ScheduledThreadPoolExecutor scheduler = Scheduler.initScheduler(Settings.EMPTY, "test-scheduler");
final AtomicBoolean abort = new AtomicBoolean();
// Large histories can be problematic and have the linearizability checker run OOM
// Bound the time how long the checker can run on such histories (Values empirically determined)
if (history.size() > 300) {
scheduler.schedule(() -> abort.set(true), 10, TimeUnit.SECONDS);
}
linearizable = new LinearizabilityChecker().isLinearizable(spec, history, missingResponseGenerator(), abort::get);
ThreadPool.terminate(scheduler, 1, TimeUnit.SECONDS);
if (abort.get() && linearizable == false) {
linearizable = true; // let the test pass
}
} finally {
// implicitly test that we can serialize all histories.
String serializedHistory = base64Serialize(history);
if (linearizable == false) {
// we dump base64 encoded data, since the nature of this test is that it does not reproduce even with same seed.
logger.error(
"Linearizability check failed. Spec: {}, initial version: {}, serialized history: {}",
spec,
initialVersion,
serializedHistory
);
}
}
assertTrue("Must be linearizable", linearizable);
}
}
private static class CASSequentialSpec implements LinearizabilityChecker.SequentialSpec {
private final Version initialVersion;
private CASSequentialSpec(Version initialVersion) {
this.initialVersion = initialVersion;
}
@Override
public Object initialState() {
return casSuccess(initialVersion);
}
@Override
public Optional<Object> nextState(Object currentState, Object input, Object output) {
State state = (State) currentState;
if (output instanceof IndexResponseHistoryOutput) {
if (input.equals(state.safeVersion) || (state.lastFailed && ((Version) input).compareTo(state.safeVersion) > 0)) {
return Optional.of(casSuccess(((IndexResponseHistoryOutput) output).getVersion()));
} else {
return Optional.empty();
}
} else {
return Optional.of(state.failed());
}
}
}
private static final class State {
private final Version safeVersion;
private final boolean lastFailed;
private State(Version safeVersion, boolean lastFailed) {
this.safeVersion = safeVersion;
this.lastFailed = lastFailed;
}
public State failed() {
return lastFailed ? this : casFail(safeVersion);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
State that = (State) o;
return lastFailed == that.lastFailed && safeVersion.equals(that.safeVersion);
}
@Override
public int hashCode() {
return Objects.hash(safeVersion, lastFailed);
}
@Override
public String toString() {
return "State{" + "safeVersion=" + safeVersion + ", lastFailed=" + lastFailed + '}';
}
}
private static State casFail(Version stateVersion) {
return new State(stateVersion, true);
}
private static State casSuccess(Version version1) {
return new State(version1, false);
}
/**
* HistoryOutput contains the information from the output of calls.
*/
private interface HistoryOutput extends NamedWriteable {
Version getVersion();
}
private static class IndexResponseHistoryOutput implements HistoryOutput {
private final Version outputVersion;
private IndexResponseHistoryOutput(IndexResponse response) {
this(new Version(response.getPrimaryTerm(), response.getSeqNo()));
}
private IndexResponseHistoryOutput(StreamInput input) throws IOException {
this(new Version(input));
}
private IndexResponseHistoryOutput(Version outputVersion) {
this.outputVersion = outputVersion;
}
@Override
public Version getVersion() {
return outputVersion;
}
@Override
public String toString() {
return "Index{" + outputVersion + "}";
}
@Override
public String getWriteableName() {
return "index";
}
@Override
public void writeTo(StreamOutput out) throws IOException {
outputVersion.writeTo(out);
}
}
/**
* We treat CAS failures (version conflicts) identically to failures in linearizability checker, but keep this separate
* to parse out the latest observed version and to ease debugging.
*/
private static class CASFailureHistoryOutput implements HistoryOutput {
private Version outputVersion;
private CASFailureHistoryOutput(VersionConflictEngineException exception) {
this(parseException(exception.getMessage()));
}
private CASFailureHistoryOutput(StreamInput input) throws IOException {
this(new Version(input));
}
private CASFailureHistoryOutput(Version outputVersion) {
this.outputVersion = outputVersion;
}
private static Version parseException(String message) {
// parsing out the version increases chance of hitting races against CAS successes, since if we did not parse this out, no
// writes would succeed after a fail on own write failure (unless we were lucky enough to guess the seqNo/primaryTerm using the
// random futureTerm/futureSeqNo handling in CASUpdateThread).
try {
Matcher matcher = EXTRACT_VERSION.matcher(message);
matcher.find();
return new Version(Long.parseLong(matcher.group(2)), Long.parseLong(matcher.group(1)));
} catch (RuntimeException e) {
throw new RuntimeException("Unable to parse message: " + message, e);
}
}
@Override
public Version getVersion() {
return outputVersion;
}
@Override
public String toString() {
return "CASFail{" + outputVersion + "}";
}
@Override
public String getWriteableName() {
return "casfail";
}
@Override
public void writeTo(StreamOutput out) throws IOException {
outputVersion.writeTo(out);
}
}
/**
* A non version conflict failure.
*/
private static class FailureHistoryOutput implements HistoryOutput {
private FailureHistoryOutput() {}
private FailureHistoryOutput(@SuppressWarnings("unused") StreamInput streamInput) {}
@Override
public Version getVersion() {
return null;
}
@Override
public String toString() {
return "Fail";
}
@Override
public String getWriteableName() {
return "fail";
}
@Override
public void writeTo(StreamOutput out) throws IOException {
// nothing to write.
}
}
private static Function<Object, Object> missingResponseGenerator() {
return input -> new FailureHistoryOutput();
}
private String base64Serialize(LinearizabilityChecker.History history) {
BytesStreamOutput output = new BytesStreamOutput();
try {
List<LinearizabilityChecker.Event> events = history.copyEvents();
output.writeInt(events.size());
for (LinearizabilityChecker.Event event : events) {
writeEvent(event, output);
}
output.close();
return Base64.getEncoder().encodeToString(BytesReference.toBytes(output.bytes()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static LinearizabilityChecker.History readHistory(StreamInput input) throws IOException {
int size = input.readInt();
List<LinearizabilityChecker.Event> events = new ArrayList<>(size);
for (int i = 0; i < size; ++i) {
events.add(readEvent(input));
}
return new LinearizabilityChecker.History(events);
}
private static void writeEvent(LinearizabilityChecker.Event event, BytesStreamOutput output) throws IOException {
output.writeEnum(event.type);
output.writeNamedWriteable((NamedWriteable) event.value);
output.writeInt(event.id);
}
private static LinearizabilityChecker.Event readEvent(StreamInput input) throws IOException {
return new LinearizabilityChecker.Event(
input.readEnum(LinearizabilityChecker.EventType.class),
input.readNamedWriteable(NamedWriteable.class),
input.readInt()
);
}
@SuppressForbidden(reason = "system err is ok for a command line tool")
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.err.println("usage: <file> <primaryTerm> <seqNo>");
} else {
runLinearizabilityChecker(new FileInputStream(args[0]), Long.parseLong(args[1]), Long.parseLong(args[2]));
}
}
@SuppressForbidden(reason = "system out is ok for a command line tool")
private static void runLinearizabilityChecker(FileInputStream fileInputStream, long primaryTerm, long seqNo) throws IOException {
StreamInput is = new InputStreamStreamInput(Base64.getDecoder().wrap(fileInputStream));
is = new NamedWriteableAwareStreamInput(is, createNamedWriteableRegistry());
LinearizabilityChecker.History history = readHistory(is);
Version initialVersion = new Version(primaryTerm, seqNo);
boolean result = new LinearizabilityChecker().isLinearizable(
new CASSequentialSpec(initialVersion),
history,
missingResponseGenerator()
);
System.out.println(LinearizabilityChecker.visualize(new CASSequentialSpec(initialVersion), history, missingResponseGenerator()));
System.out.println("Linearizable?: " + result);
}
private static NamedWriteableRegistry createNamedWriteableRegistry() {
return new NamedWriteableRegistry(
Arrays.asList(
new NamedWriteableRegistry.Entry(NamedWriteable.class, "version", Version::new),
new NamedWriteableRegistry.Entry(NamedWriteable.class, "index", IndexResponseHistoryOutput::new),
new NamedWriteableRegistry.Entry(NamedWriteable.class, "casfail", CASFailureHistoryOutput::new),
new NamedWriteableRegistry.Entry(NamedWriteable.class, "fail", FailureHistoryOutput::new)
)
);
}
public void testSequentialSpec() {
// Generate 3 increasing versions
Version version1 = new Version(randomIntBetween(1, 5), randomIntBetween(0, 100));
Version version2 = futureVersion(version1);
Version version3 = futureVersion(version2);
List<Version> versions = List.of(version1, version2, version3);
LinearizabilityChecker.SequentialSpec spec = new CASSequentialSpec(version1);
assertThat(spec.initialState(), equalTo(casSuccess(version1)));
assertThat(
spec.nextState(casSuccess(version1), version1, new IndexResponseHistoryOutput(version2)),
equalTo(Optional.of(casSuccess(version2)))
);
assertThat(
spec.nextState(casFail(version1), version2, new IndexResponseHistoryOutput(version3)),
equalTo(Optional.of(casSuccess(version3)))
);
assertThat(spec.nextState(casSuccess(version1), version2, new IndexResponseHistoryOutput(version3)), equalTo(Optional.empty()));
assertThat(spec.nextState(casSuccess(version2), version1, new IndexResponseHistoryOutput(version3)), equalTo(Optional.empty()));
assertThat(spec.nextState(casFail(version2), version1, new IndexResponseHistoryOutput(version3)), equalTo(Optional.empty()));
// for version conflicts, we keep state version with lastFailed set, regardless of input/output version.
versions.forEach(stateVersion -> versions.forEach(inputVersion -> versions.forEach(outputVersion -> {
assertThat(
spec.nextState(casSuccess(stateVersion), inputVersion, new CASFailureHistoryOutput(outputVersion)),
equalTo(Optional.of(casFail(stateVersion)))
);
assertThat(
spec.nextState(casFail(stateVersion), inputVersion, new CASFailureHistoryOutput(outputVersion)),
equalTo(Optional.of(casFail(stateVersion)))
);
})));
// for non version conflict failures, we keep state version with lastFailed set, regardless of input version.
versions.forEach(stateVersion -> versions.forEach(inputVersion -> {
assertThat(
spec.nextState(casSuccess(stateVersion), inputVersion, new FailureHistoryOutput()),
equalTo(Optional.of(casFail(stateVersion)))
);
assertThat(
spec.nextState(casFail(stateVersion), inputVersion, new FailureHistoryOutput()),
equalTo(Optional.of(casFail(stateVersion)))
);
}));
}
private Version futureVersion(Version version) {
Version futureVersion = version.nextSeqNo(randomIntBetween(1, 10));
if (randomBoolean()) futureVersion = futureVersion.nextTerm();
return futureVersion;
}
}
| GlenRSmith/elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/versioning/ConcurrentSeqNoVersioningIT.java | Java | apache-2.0 | 35,884 |
package com.gitonway.lee.niftymodaldialogeffects.lib.effects;
import android.view.View;
import com.nineoldandroids.animation.ObjectAnimator;
/**
* Created by lee on 2014/7/31.
*/
public class FlipV extends BaseEffects{
@Override
protected void setupAnimation(View view) {
getAnimatorSet().playTogether(
ObjectAnimator.ofFloat(view, "rotationX", -90, 0).setDuration(mDuration)
);
}
}
| zhujohnle/qbcp | QBLibrary/src/com/gitonway/lee/niftymodaldialogeffects/lib/effects/FlipV.java | Java | apache-2.0 | 434 |
/*
* 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.
*/
package org.apache.reef.examples.group.bgd.data.parser;
import org.apache.commons.lang.StringUtils;
import org.apache.reef.examples.group.bgd.data.Example;
import org.apache.reef.examples.group.bgd.data.SparseExample;
import javax.inject.Inject;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A Parser for SVMLight records.
*/
public class SVMLightParser implements Parser<String> {
private static final Logger LOG = Logger.getLogger(SVMLightParser.class.getName());
@Inject
public SVMLightParser() {
}
@Override
public Example parse(final String line) {
final int entriesCount = StringUtils.countMatches(line, ":");
final int[] indices = new int[entriesCount];
final float[] values = new float[entriesCount];
final String[] entries = StringUtils.split(line, ' ');
String labelStr = entries[0];
final boolean pipeExists = labelStr.indexOf('|') != -1;
if (pipeExists) {
labelStr = labelStr.substring(0, labelStr.indexOf('|'));
}
double label = Double.parseDouble(labelStr);
if (label != 1) {
label = -1;
}
for (int j = 1; j < entries.length; ++j) {
final String x = entries[j];
final String[] entity = StringUtils.split(x, ':');
final int offset = pipeExists ? 0 : 1;
indices[j - 1] = Integer.parseInt(entity[0]) - offset;
values[j - 1] = Float.parseFloat(entity[1]);
}
return new SparseExample(label, values, indices);
}
public static void main(final String[] args) {
final Parser<String> parser = new SVMLightParser();
for (int i = 0; i < 10; i++) {
final List<SparseExample> examples = new ArrayList<>();
float avgFtLen = 0;
try (BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("C:\\Users\\shravan\\data\\splice\\hdi\\hdi_uncomp\\part-r-0000" + i),
StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
final SparseExample spEx = (SparseExample) parser.parse(line);
avgFtLen += spEx.getFeatureLength();
examples.add(spEx);
}
} catch (final IOException e) {
throw new RuntimeException("Exception", e);
}
LOG.log(Level.INFO, "OUT: {0} {1} {2}",
new Object[] {examples.size(), avgFtLen, avgFtLen / examples.size()});
examples.clear();
}
}
}
| dongjoon-hyun/reef | lang/java/reef-examples/src/main/java/org/apache/reef/examples/group/bgd/data/parser/SVMLightParser.java | Java | apache-2.0 | 3,331 |
// Copyright 2009-2015 Josh Close and Contributors
// This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0.
// See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0.
// http://csvhelper.com
using System;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace CsvHelper.Tests.Exceptions
{
[TestClass]
public class ExceptionTests
{
[TestMethod]
public void NoDefaultConstructorTest()
{
using( var stream = new MemoryStream() )
using( var reader = new StreamReader( stream ) )
using( var writer = new StreamWriter( stream ) )
using( var csv = new CsvReader( reader ) )
{
writer.WriteLine( "Id,Name" );
writer.WriteLine( "1,2" );
writer.WriteLine( "3,4" );
writer.Flush();
stream.Position = 0;
try
{
var list = csv.GetRecords<NoDefaultConstructor>().ToList();
Assert.Fail();
}
catch( ArgumentException ex )
{
var data = ex.Data["CsvHelper"];
var expected = new StringBuilder();
expected.AppendLine( "Row: '2' (1 based)" );
expected.AppendLine( "Type: 'CsvHelper.Tests.Exceptions.ExceptionTests+NoDefaultConstructor'" );
expected.AppendLine( "Field Index: '-1' (0 based)" );
Assert.IsNotNull( data );
Assert.AreEqual( expected.ToString(), data );
}
}
}
private class NoDefaultConstructor
{
public int Id { get; set; }
public string Name { get; set; }
public NoDefaultConstructor( int id, string name )
{
Id = id;
Name = name;
}
}
}
}
| erdincay/CsvHelper | src/CsvHelper.Tests/Exceptions/ExceptionTests.cs | C# | apache-2.0 | 1,740 |
<div class="page-header">
<h1>
Roles
<span ng-show="model.waiting" class="waiting label label-info">Searching...</span>
<span ng-show="model.pager" class="badge">{{model.pager.total}} found</span>
</h1>
</div>
<form ng-submit="search(model.filter)" class="form-group">
<div class="col-sm-6">
<div class="input-group form-group">
<input type="text" id="filter" ng-model="model.filter" class="form-control" placeholder="Filter" autofocus>
<span class="input-group-btn">
<button class="btn btn-primary">Search</button>
</span>
</div>
</div>
</form>
<div class="row" ng-show="model.message">
<div class="col-sm-8">
<div class="alert alert-danger alert-dismissable">{{model.message}}</div>
</div>
</div>
<div class="row" ng-hide="model.waiting || model.message || (model.roles.length > 0)">
<div class="col-sm-8">
<div class="alert alert-info">No Roles Found</div>
</div>
</div>
<div class="row" ng-show="model.roles.length > 0">
<table class="table table-condensed table-responsive table-striped xtable-bordered">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Description</th>
<th>Subject</th>
</tr>
</thead>
<tr ng-repeat="role in model.roles">
<td><a ng-show="role.links.detail" href="#/roles/edit/{{role.data.subject}}" class="btn btn-primary btn-xs">edit</a></td>
<td>{{role.data.name}}</td>
<td>{{role.data.description}}</td>
<td>{{role.data.subject}}</td>
</tr>
</table>
</div>
<div class="row" ng-show="model.pager">
<div class="col-sm-8">
<tt-pager-buttons pager="model.pager" path="roles"></tt-pager-buttons>
</div>
<div class="col-sm-4 pager-text">
<tt-pager-summary pager="model.pager"></tt-pager-summary>
</div>
</div>
| Ernesto99/IdentityManager | source/Core/Assets/Templates/roles/list.html | HTML | apache-2.0 | 1,979 |
package org.wiztools.restclient.jfx.req;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
/**
* FXML Controller class
*
* @author subhash
*/
public class UrlPaneController implements Initializable {
@FXML
private ComboBox urlCombo;
@FXML
private void handleButtonAction(ActionEvent event) {
urlCombo.setValue("http://www.wiztools.org/");
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
| geub/rest-client | restclient-jfx/src/main/java/org/wiztools/restclient/jfx/req/UrlPaneController.java | Java | apache-2.0 | 681 |
"use strict";
var _utils = require("./utils");
var _placeholders = require("./placeholders");
{
(0, _utils.default)("Noop", {
visitor: []
});
}
(0, _utils.default)("Placeholder", {
visitor: [],
builder: ["expectedNode", "name"],
fields: {
name: {
validate: (0, _utils.assertNodeType)("Identifier")
},
expectedNode: {
validate: (0, _utils.assertOneOf)(..._placeholders.PLACEHOLDERS)
}
}
});
(0, _utils.default)("V8IntrinsicIdentifier", {
builder: ["name"],
fields: {
name: {
validate: (0, _utils.assertValueType)("string")
}
}
}); | GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/@babel/types/lib/definitions/misc.js | JavaScript | apache-2.0 | 596 |
/*
* Copyright 2011 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.
*/
package org.gradle.plugins.signing.signatory.pgp;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSignature;
/**
* A normalised form for keys, which are friendliest for users as hex strings but used internally as longs.
*/
public class PgpKeyId implements Comparable<PgpKeyId> {
private final long asLong;
private final String asHex;
public PgpKeyId(long keyId) {
asLong = keyId;
asHex = toHex(keyId);
}
public PgpKeyId(PGPPublicKey keyId) {
this(keyId.getKeyID());
}
public PgpKeyId(PGPSignature signature) {
this(signature.getKeyID());
}
public PgpKeyId(String keyId) {
asLong = toLong(keyId);
asHex = toHex(asLong);
}
@Override
public boolean equals(Object other) {
return other instanceof PgpKeyId
&& ((PgpKeyId) other).asHex.equals(this.asHex);
}
@Override
public int hashCode() {
return asHex.hashCode();
}
@Override
public String toString() {
return asHex;
}
@Override
public int compareTo(PgpKeyId other) {
return other == null
? -1
: this.asHex.compareTo(other.asHex);
}
public final String getAsHex() {
return asHex;
}
public final long getAsLong() {
return asLong;
}
public static String toHex(long keyId) {
return String.format("%08X", 0xFFFFFFFFL & keyId);
}
public static long toLong(String keyId) {
if (keyId == null) {
throw new IllegalArgumentException("'keyId' cannot be null");
}
String normalised = normaliseKeyId(keyId);
try {
return Long.parseLong(normalised, 16);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("the key id \'" + keyId + "\' is not a valid hex string");
}
}
private static String normaliseKeyId(String keyId) {
String keyIdUpped = keyId.toUpperCase();
switch (keyIdUpped.length()) {
case 10:
if (!keyIdUpped.startsWith("0X")) {
throw new IllegalArgumentException("10 character key IDs must start with 0x (given value: " + keyId + ")");
}
return keyIdUpped.substring(2);
case 8:
if (keyId.startsWith("0X")) {
throw new IllegalArgumentException("8 character key IDs must not start with 0x (given value: " + keyId + ")");
}
return keyIdUpped;
default:
throw new IllegalStateException("The key ID must be in a valid form (eg 00B5050F or 0x00B5050F), given value: " + keyId);
}
}
}
| gstevey/gradle | subprojects/signing/src/main/java/org/gradle/plugins/signing/signatory/pgp/PgpKeyId.java | Java | apache-2.0 | 3,372 |
# Display KML network links
Display a file with a KML network link, including displaying any network link control messages at launch.
![Image of display KML network links](DisplayKmlNetworkLinks.jpg)
## Use case
KML files can reference other KML files on the network and support automatically refreshing content. For example, survey workers will benefit from KML data shown on their devices automatically refreshing to show the most up-to-date state. Additionally, discovering KML files linked to the data they are currently viewing provides additional information to make better decisions in the field.
## How to use the sample
The sample will load the KML file automatically. The data shown should refresh automatically every few seconds. Pan and zoom to explore the map.
## How it works
1. Create a `KmlDataset` from a KML source which has network links.
2. Construct a `KmlLayer` with the dataset and add the layer as an operational layer.
3. To listen for network messages, add an event handler to the `NetworkLinkControlMessage` event on the dataset.
## Relevant API
* KmlDataset
* KmlDataset.NetworkLinkControlMessage
* KmlLayer
* KmlNetworkLinkControlMessageEventArgs
## Offline data
This sample uses the radar.kmz file, which can be found on [ArcGIS Online](https://arcgisruntime.maps.arcgis.com/home/item.html?id=600748d4464442288f6db8a4ba27dc95).
## About the data
This map shows the current air traffic in parts of Europe with heading, altitude, and ground speed. Additionally, noise levels from ground monitoring stations are shown.
## Tags
Keyhole, KML, KMZ, Network Link, Network Link Control, OGC | Esri/arcgis-runtime-samples-dotnet | src/iOS/Xamarin.iOS/Samples/Layers/DisplayKmlNetworkLinks/readme.md | Markdown | apache-2.0 | 1,631 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi;
import com.intellij.lang.FileASTNode;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.tree.IFileElementType;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A PSI element representing a file.
* <p/>
* Please see <a href="http://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/psi_files.html">PSI Files</a>
* for high-level overview.
*
* @see com.intellij.openapi.actionSystem.LangDataKeys#PSI_FILE
* @see PsiElement#getContainingFile()
* @see PsiManager#findFile(VirtualFile)
* @see PsiDocumentManager#getPsiFile(com.intellij.openapi.editor.Document)
*/
public interface PsiFile extends PsiFileSystemItem {
/**
* The empty array of PSI files which can be reused to avoid unnecessary allocations.
*/
PsiFile[] EMPTY_ARRAY = new PsiFile[0];
/**
* Returns the virtual file corresponding to the PSI file.
*
* @return the virtual file, or {@code null} if the file exists only in memory.
*/
@Override
VirtualFile getVirtualFile();
/**
* Returns the directory containing the file.
*
* @return the containing directory, or {@code null} if the file exists only in memory.
*/
PsiDirectory getContainingDirectory();
@Override
PsiDirectory getParent();
/**
* Gets the modification stamp value. Modification stamp is a value changed by any modification
* of the content of the file. Note that it is not related to the file modification time.
*
* @return the modification stamp value
* @see VirtualFile#getModificationStamp()
*/
long getModificationStamp();
/**
* If the file is a non-physical copy of a file, returns the original file which had
* been copied. Otherwise, returns the same file.
*
* @return the original file of a copy, or the same file if the file is not a copy.
*/
@NotNull
PsiFile getOriginalFile();
/**
* Returns the file type for the file.
*
* @return the file type instance.
*/
@NotNull
FileType getFileType();
/**
* If the file contains multiple interspersed languages, returns the roots for
* PSI trees for each of these languages. (For example, a JSPX file contains JSP,
* XML and Java trees.)
*
* @return the array of PSI roots, or a single-element array containing {@code this}
* if the file has only a single language.
* @deprecated Use {@link FileViewProvider#getAllFiles()} instead.
*/
@Deprecated
PsiFile @NotNull [] getPsiRoots();
@NotNull
FileViewProvider getViewProvider();
@Override
FileASTNode getNode();
/**
* Called by the PSI framework when the contents of the file changes.
* If you override this method, you <b>must</b> call the base class implementation.
* While this method can be used to invalidate file-level caches, it is more much safe to invalidate them in {@link #clearCaches()}
* since file contents can be reloaded completely (without any specific subtree change) without this method being called.
*/
void subtreeChanged();
/**
* Invalidate any file-specific cache in this method. It is called on file content change.
* If you override this method, you <b>must</b> call the base class implementation.
*/
default void clearCaches() {}
/**
* @return the element type of the file node, but possibly in an efficient node that doesn't instantiate the node.
*/
@Nullable
default IFileElementType getFileElementType() {
return ObjectUtils.tryCast(PsiUtilCore.getElementType(getNode()), IFileElementType.class);
}
}
| ingokegel/intellij-community | platform/core-api/src/com/intellij/psi/PsiFile.java | Java | apache-2.0 | 3,843 |
/**
* 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.
*/
package org.apache.camel.model;
import java.util.Set;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
public class GatherAllStaticEndpointUrisTest extends ContextTestSupport {
public void testGatherAllStaticEndpointUris() throws Exception {
RouteDefinition route = context.getRouteDefinition("foo");
Set<String> uris = RouteDefinitionHelper.gatherAllStaticEndpointUris(context, route, true, true);
assertNotNull(uris);
assertEquals(5, uris.size());
RouteDefinition route2 = context.getRouteDefinition("bar");
Set<String> uris2 = RouteDefinitionHelper.gatherAllStaticEndpointUris(context, route2, true, true);
assertNotNull(uris2);
assertEquals(2, uris2.size());
Set<String> uris2out = RouteDefinitionHelper.gatherAllStaticEndpointUris(context, route2, false, true);
assertNotNull(uris2out);
assertEquals(1, uris2out.size());
String json = context.createRouteStaticEndpointJson(null);
assertNotNull(json);
assertTrue(json.contains("{ \"uri\": \"direct://foo\" }"));
assertTrue(json.contains("{ \"uri\": \"seda://bar\" }"));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:foo").routeId("foo")
.to("seda:bar")
.log("Hello World")
.wireTap("mock:tap")
.to("mock:foo")
.enrich("seda:stuff");
from("seda:bar").routeId("bar")
.log("Bye World")
.to("mock:bar");
}
};
}
}
| koscejev/camel | camel-core/src/test/java/org/apache/camel/model/GatherAllStaticEndpointUrisTest.java | Java | apache-2.0 | 2,605 |
/**
* CreativePlaceholder.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201408;
/**
* A {@code CreativePlaceholder} describes a slot that a creative
* is expected to
* fill. This is used primarily to help in forecasting, and
* also to validate
* that the correct creatives are associated with the line
* item. A
* {@code CreativePlaceholder} must contain a size, and it
* can optionally
* contain companions. Companions are only valid if the line
* item's environment
* type is {@link EnvironmentType#VIDEO_PLAYER}.
*/
public class CreativePlaceholder implements java.io.Serializable {
/* The dimensions that the creative is expected to have. This
* attribute is
* required. */
private com.google.api.ads.dfp.axis.v201408.Size size;
/* The companions that the creative is expected to have. This
* attribute can
* only be set if the line item it belongs to has a
* {@link LineItem#environmentType} of {@link EnvironmentType#VIDEO_PLAYER}
* or
* {@link LineItem#roadblockingType} of {@link RoadblockingType#CREATIVE_SET}. */
private com.google.api.ads.dfp.axis.v201408.CreativePlaceholder[] companions;
/* The set of label frequency caps applied directly to this creative
* placeholder. */
private com.google.api.ads.dfp.axis.v201408.AppliedLabel[] appliedLabels;
/* Contains the set of labels applied directly to this creative
* placeholder
* as well as those inherited from the creative template
* from which this
* creative placeholder was instantiated. This field
* is readonly and is
* assigned by Google. */
private com.google.api.ads.dfp.axis.v201408.AppliedLabel[] effectiveAppliedLabels;
/* The ID of this placeholder. This field is generated by the
* server and is read-only. */
private java.lang.Long id;
/* Expected number of creatives that will be uploaded corresponding
* to this
* creative placeholder. This estimate is used to improve
* the accuracy of
* forecasting; for example, if label frequency capping
* limits the number of
* times a creative may be served. */
private java.lang.Integer expectedCreativeCount;
/* Describes the types of sizes a creative can be. By default,
* the creative's size
* is {@link CreativeSizeType#PIXEL}, which is a dimension
* based size (width-height pair). */
private com.google.api.ads.dfp.axis.v201408.CreativeSizeType creativeSizeType;
public CreativePlaceholder() {
}
public CreativePlaceholder(
com.google.api.ads.dfp.axis.v201408.Size size,
com.google.api.ads.dfp.axis.v201408.CreativePlaceholder[] companions,
com.google.api.ads.dfp.axis.v201408.AppliedLabel[] appliedLabels,
com.google.api.ads.dfp.axis.v201408.AppliedLabel[] effectiveAppliedLabels,
java.lang.Long id,
java.lang.Integer expectedCreativeCount,
com.google.api.ads.dfp.axis.v201408.CreativeSizeType creativeSizeType) {
this.size = size;
this.companions = companions;
this.appliedLabels = appliedLabels;
this.effectiveAppliedLabels = effectiveAppliedLabels;
this.id = id;
this.expectedCreativeCount = expectedCreativeCount;
this.creativeSizeType = creativeSizeType;
}
/**
* Gets the size value for this CreativePlaceholder.
*
* @return size * The dimensions that the creative is expected to have. This
* attribute is
* required.
*/
public com.google.api.ads.dfp.axis.v201408.Size getSize() {
return size;
}
/**
* Sets the size value for this CreativePlaceholder.
*
* @param size * The dimensions that the creative is expected to have. This
* attribute is
* required.
*/
public void setSize(com.google.api.ads.dfp.axis.v201408.Size size) {
this.size = size;
}
/**
* Gets the companions value for this CreativePlaceholder.
*
* @return companions * The companions that the creative is expected to have. This
* attribute can
* only be set if the line item it belongs to has a
* {@link LineItem#environmentType} of {@link EnvironmentType#VIDEO_PLAYER}
* or
* {@link LineItem#roadblockingType} of {@link RoadblockingType#CREATIVE_SET}.
*/
public com.google.api.ads.dfp.axis.v201408.CreativePlaceholder[] getCompanions() {
return companions;
}
/**
* Sets the companions value for this CreativePlaceholder.
*
* @param companions * The companions that the creative is expected to have. This
* attribute can
* only be set if the line item it belongs to has a
* {@link LineItem#environmentType} of {@link EnvironmentType#VIDEO_PLAYER}
* or
* {@link LineItem#roadblockingType} of {@link RoadblockingType#CREATIVE_SET}.
*/
public void setCompanions(com.google.api.ads.dfp.axis.v201408.CreativePlaceholder[] companions) {
this.companions = companions;
}
public com.google.api.ads.dfp.axis.v201408.CreativePlaceholder getCompanions(int i) {
return this.companions[i];
}
public void setCompanions(int i, com.google.api.ads.dfp.axis.v201408.CreativePlaceholder _value) {
this.companions[i] = _value;
}
/**
* Gets the appliedLabels value for this CreativePlaceholder.
*
* @return appliedLabels * The set of label frequency caps applied directly to this creative
* placeholder.
*/
public com.google.api.ads.dfp.axis.v201408.AppliedLabel[] getAppliedLabels() {
return appliedLabels;
}
/**
* Sets the appliedLabels value for this CreativePlaceholder.
*
* @param appliedLabels * The set of label frequency caps applied directly to this creative
* placeholder.
*/
public void setAppliedLabels(com.google.api.ads.dfp.axis.v201408.AppliedLabel[] appliedLabels) {
this.appliedLabels = appliedLabels;
}
public com.google.api.ads.dfp.axis.v201408.AppliedLabel getAppliedLabels(int i) {
return this.appliedLabels[i];
}
public void setAppliedLabels(int i, com.google.api.ads.dfp.axis.v201408.AppliedLabel _value) {
this.appliedLabels[i] = _value;
}
/**
* Gets the effectiveAppliedLabels value for this CreativePlaceholder.
*
* @return effectiveAppliedLabels * Contains the set of labels applied directly to this creative
* placeholder
* as well as those inherited from the creative template
* from which this
* creative placeholder was instantiated. This field
* is readonly and is
* assigned by Google.
*/
public com.google.api.ads.dfp.axis.v201408.AppliedLabel[] getEffectiveAppliedLabels() {
return effectiveAppliedLabels;
}
/**
* Sets the effectiveAppliedLabels value for this CreativePlaceholder.
*
* @param effectiveAppliedLabels * Contains the set of labels applied directly to this creative
* placeholder
* as well as those inherited from the creative template
* from which this
* creative placeholder was instantiated. This field
* is readonly and is
* assigned by Google.
*/
public void setEffectiveAppliedLabels(com.google.api.ads.dfp.axis.v201408.AppliedLabel[] effectiveAppliedLabels) {
this.effectiveAppliedLabels = effectiveAppliedLabels;
}
public com.google.api.ads.dfp.axis.v201408.AppliedLabel getEffectiveAppliedLabels(int i) {
return this.effectiveAppliedLabels[i];
}
public void setEffectiveAppliedLabels(int i, com.google.api.ads.dfp.axis.v201408.AppliedLabel _value) {
this.effectiveAppliedLabels[i] = _value;
}
/**
* Gets the id value for this CreativePlaceholder.
*
* @return id * The ID of this placeholder. This field is generated by the
* server and is read-only.
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this CreativePlaceholder.
*
* @param id * The ID of this placeholder. This field is generated by the
* server and is read-only.
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the expectedCreativeCount value for this CreativePlaceholder.
*
* @return expectedCreativeCount * Expected number of creatives that will be uploaded corresponding
* to this
* creative placeholder. This estimate is used to improve
* the accuracy of
* forecasting; for example, if label frequency capping
* limits the number of
* times a creative may be served.
*/
public java.lang.Integer getExpectedCreativeCount() {
return expectedCreativeCount;
}
/**
* Sets the expectedCreativeCount value for this CreativePlaceholder.
*
* @param expectedCreativeCount * Expected number of creatives that will be uploaded corresponding
* to this
* creative placeholder. This estimate is used to improve
* the accuracy of
* forecasting; for example, if label frequency capping
* limits the number of
* times a creative may be served.
*/
public void setExpectedCreativeCount(java.lang.Integer expectedCreativeCount) {
this.expectedCreativeCount = expectedCreativeCount;
}
/**
* Gets the creativeSizeType value for this CreativePlaceholder.
*
* @return creativeSizeType * Describes the types of sizes a creative can be. By default,
* the creative's size
* is {@link CreativeSizeType#PIXEL}, which is a dimension
* based size (width-height pair).
*/
public com.google.api.ads.dfp.axis.v201408.CreativeSizeType getCreativeSizeType() {
return creativeSizeType;
}
/**
* Sets the creativeSizeType value for this CreativePlaceholder.
*
* @param creativeSizeType * Describes the types of sizes a creative can be. By default,
* the creative's size
* is {@link CreativeSizeType#PIXEL}, which is a dimension
* based size (width-height pair).
*/
public void setCreativeSizeType(com.google.api.ads.dfp.axis.v201408.CreativeSizeType creativeSizeType) {
this.creativeSizeType = creativeSizeType;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CreativePlaceholder)) return false;
CreativePlaceholder other = (CreativePlaceholder) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.size==null && other.getSize()==null) ||
(this.size!=null &&
this.size.equals(other.getSize()))) &&
((this.companions==null && other.getCompanions()==null) ||
(this.companions!=null &&
java.util.Arrays.equals(this.companions, other.getCompanions()))) &&
((this.appliedLabels==null && other.getAppliedLabels()==null) ||
(this.appliedLabels!=null &&
java.util.Arrays.equals(this.appliedLabels, other.getAppliedLabels()))) &&
((this.effectiveAppliedLabels==null && other.getEffectiveAppliedLabels()==null) ||
(this.effectiveAppliedLabels!=null &&
java.util.Arrays.equals(this.effectiveAppliedLabels, other.getEffectiveAppliedLabels()))) &&
((this.id==null && other.getId()==null) ||
(this.id!=null &&
this.id.equals(other.getId()))) &&
((this.expectedCreativeCount==null && other.getExpectedCreativeCount()==null) ||
(this.expectedCreativeCount!=null &&
this.expectedCreativeCount.equals(other.getExpectedCreativeCount()))) &&
((this.creativeSizeType==null && other.getCreativeSizeType()==null) ||
(this.creativeSizeType!=null &&
this.creativeSizeType.equals(other.getCreativeSizeType())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getSize() != null) {
_hashCode += getSize().hashCode();
}
if (getCompanions() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getCompanions());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getCompanions(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getAppliedLabels() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getAppliedLabels());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getAppliedLabels(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getEffectiveAppliedLabels() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getEffectiveAppliedLabels());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getEffectiveAppliedLabels(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getExpectedCreativeCount() != null) {
_hashCode += getExpectedCreativeCount().hashCode();
}
if (getCreativeSizeType() != null) {
_hashCode += getCreativeSizeType().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CreativePlaceholder.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "CreativePlaceholder"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("size");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "size"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "Size"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companions");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "companions"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "CreativePlaceholder"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("appliedLabels");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "appliedLabels"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "AppliedLabel"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("effectiveAppliedLabels");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "effectiveAppliedLabels"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "AppliedLabel"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("expectedCreativeCount");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "expectedCreativeCount"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("creativeSizeType");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "creativeSizeType"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "CreativeSizeType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201408/CreativePlaceholder.java | Java | apache-2.0 | 19,799 |
class Virustotaluploader < Cask
url 'https://www.virustotal.com/static/bin/VirusTotalUploader_1.1.dmg'
homepage 'https://www.virustotal.com/'
version '1.1'
sha256 'e757f8eb49592dfe67169a5582bcc3cca01c8ecc6634853398813a2aa92f24a7'
link 'VirusTotalUploader.app'
end
| tonyseek/homebrew-cask | Casks/virustotaluploader.rb | Ruby | bsd-2-clause | 274 |
// Copyright 2016 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.
#ifndef WebEventListenerProperties_h
#define WebEventListenerProperties_h
#include "WebCommon.h"
namespace blink {
enum class WebEventListenerClass {
TouchStartOrMove, // This value includes "touchstart", "touchmove" and
// "pointer" events.
MouseWheel, // This value includes "wheel" and "mousewheel" events.
TouchEndOrCancel, // This value includes "touchend", "touchcancel" events.
};
// Indicates the variety of event listener types for a given
// WebEventListenerClass.
enum class WebEventListenerProperties {
Nothing, // This should be "None"; but None #defined in X11's X.h
Passive, // This indicates solely passive listeners.
Blocking, // This indicates solely blocking listeners.
BlockingAndPassive, // This indicates >= 1 blocking listener and >= 1 passive
// listeners.
};
} // namespace blink
#endif
| ssaroha/node-webrtc | third_party/webrtc/include/chromium/src/third_party/WebKit/public/platform/WebEventListenerProperties.h | C | bsd-2-clause | 1,088 |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * 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.
*
* 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 HOLDER 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.
*/
using System;
using System.Collections.Generic;
using XenAdmin;
using XenAdmin.Alerts;
using XenAdmin.Core;
namespace XenAPI
{
public partial class VMPP
{
public DateTime GetNextRunTime()
{
var time = Host.get_server_localtime(Connection.Session, Helpers.GetMaster(Connection).opaque_ref);
if (backup_frequency == vmpp_backup_frequency.hourly)
{
return GetHourlyDate(time, Convert.ToInt32(backup_schedule_min));
}
if (backup_frequency == vmpp_backup_frequency.daily)
{
var hour = Convert.ToInt32(backup_schedule_hour);
var min = Convert.ToInt32(backup_schedule_min);
return GetDailyDate(time, min, hour);
}
if (backup_frequency == vmpp_backup_frequency.weekly)
{
var hour = Convert.ToInt32(backup_schedule_hour);
var min = Convert.ToInt32(backup_schedule_min);
return GetWeeklyDate(time, hour, min, new List<DayOfWeek>(DaysOfWeekBackup));
}
return new DateTime();
}
private static DateTime GetDailyDate(DateTime time, int min, int hour)
{
var nextDateTime = new DateTime(time.Year, time.Month, time.Day, hour, min, 0);
if (time > nextDateTime)
nextDateTime = nextDateTime.AddDays(1);
return nextDateTime;
}
private static DateTime GetHourlyDate(DateTime time, int min)
{
var nextDateTime = new DateTime(time.Year, time.Month, time.Day, time.Hour, min, 0);
if (time > nextDateTime)
nextDateTime = nextDateTime.AddHours(1);
return nextDateTime;
}
public static DateTime GetWeeklyDate(DateTime time, int hour, int min, List<DayOfWeek> listDaysOfWeek)
{
listDaysOfWeek.Sort();
int daysOfDifference;
DayOfWeek today = time.DayOfWeek;
int nextDay = listDaysOfWeek.FindIndex(x => x >= time.DayOfWeek);
// No scheduled days later in the week: take first day next week
if (nextDay < 0)
{
daysOfDifference = 7 - (today - listDaysOfWeek[0]);
}
else
{
daysOfDifference = listDaysOfWeek[nextDay] - today;
// Today is a scheduled day: but is the time already past?
if (daysOfDifference == 0)
{
var todaysScheduledTime = new DateTime(time.Year, time.Month, time.Day, hour, min, 0);
if (time > todaysScheduledTime)
{
// Yes, the time is already past. Find the next day in the schedule instead.
if (listDaysOfWeek.Count == nextDay + 1) // we're at the last scheduled day in the week: go to next week
daysOfDifference = 7 - (today - listDaysOfWeek[0]);
else
daysOfDifference = listDaysOfWeek[nextDay + 1] - today;
}
}
}
return (new DateTime(time.Year, time.Month, time.Day, hour, min, 0)).AddDays(daysOfDifference);
}
public IEnumerable<DayOfWeek> DaysOfWeekBackup
{
get
{
return GetDaysFromDictionary(backup_schedule);
}
}
private static IEnumerable<DayOfWeek> GetDaysFromDictionary(Dictionary<string, string> dictionary)
{
if (dictionary.ContainsKey("days"))
{
if (dictionary["days"].IndexOf("monday", StringComparison.InvariantCultureIgnoreCase) >= 0)
yield return DayOfWeek.Monday;
if (dictionary["days"].IndexOf("tuesday", StringComparison.InvariantCultureIgnoreCase) >= 0)
yield return DayOfWeek.Tuesday;
if (dictionary["days"].IndexOf("wednesday", StringComparison.InvariantCultureIgnoreCase) >= 0)
yield return DayOfWeek.Wednesday;
if (dictionary["days"].IndexOf("thursday", StringComparison.InvariantCultureIgnoreCase) >= 0)
yield return DayOfWeek.Thursday;
if (dictionary["days"].IndexOf("friday", StringComparison.InvariantCultureIgnoreCase) >= 0)
yield return DayOfWeek.Friday;
if (dictionary["days"].IndexOf("saturday", StringComparison.InvariantCultureIgnoreCase) >= 0)
yield return DayOfWeek.Saturday;
if (dictionary["days"].IndexOf("sunday", StringComparison.InvariantCultureIgnoreCase) >= 0)
yield return DayOfWeek.Sunday;
}
}
public IEnumerable<DayOfWeek> DaysOfWeekArchive
{
get
{
return GetDaysFromDictionary(archive_schedule);
}
}
public override string Name
{
get { return name_label; }
}
public override string Description
{
get { return name_description; }
}
public string alarm_config_smtp_server
{
get
{
return TryGetKey(alarm_config, "smtp_server");
}
}
public string alarm_config_smtp_port
{
get
{
return TryGetKey(alarm_config, "smtp_port");
}
}
private string TryGetKey(Dictionary<string, string> dict, string key)
{
string r;
if (dict.TryGetValue(key, out r))
{
return r;
}
return "";
}
public string alarm_config_email_address
{
get
{
return TryGetKey(alarm_config, "email_address");
}
}
public DateTime GetNextArchiveRunTime()
{
var time = Host.get_server_localtime(Connection.Session, Helpers.GetMaster(Connection).opaque_ref);
if (archive_frequency == vmpp_archive_frequency.daily)
{
return GetDailyDate(time,
Convert.ToInt32(archive_schedule_min),
Convert.ToInt32(archive_schedule_hour));
}
if (archive_frequency == vmpp_archive_frequency.weekly)
{
var hour = Convert.ToInt32(archive_schedule_hour);
var min = Convert.ToInt32(archive_schedule_min);
return GetWeeklyDate(time, hour, min, new List<DayOfWeek>(DaysOfWeekArchive));
}
if (archive_frequency == vmpp_archive_frequency.always_after_backup)
return GetNextRunTime();
return DateTime.MinValue;
}
public string archive_target_config_location
{
get
{
return TryGetKey(archive_target_config, "location");
}
}
public string archive_target_config_username
{
get
{
return TryGetKey(archive_target_config, "username");
}
}
public string archive_target_config_password_uuid
{
get
{
return TryGetKey(archive_target_config, "password");
}
}
public string archive_target_config_password_value
{
get
{
string uuid = archive_target_config_password_uuid;
try
{
string opaqueref = Secret.get_by_uuid(Connection.Session, uuid);
return Secret.get_value(Connection.Session, opaqueref);
}
catch (Exception)
{
return "";
}
}
}
public string backup_schedule_min
{
get
{
return TryGetKey(backup_schedule, "min");
}
}
public string backup_schedule_hour
{
get
{
return TryGetKey(backup_schedule, "hour");
}
}
public string backup_schedule_days
{
get
{
return TryGetKey(backup_schedule, "days");
}
}
public string archive_schedule_min
{
get
{
return TryGetKey(archive_schedule, "min");
}
}
public string archive_schedule_hour
{
get
{
return TryGetKey(archive_schedule, "hour");
}
}
public string archive_schedule_days
{
get
{
return TryGetKey(archive_schedule, "days");
}
}
private List<PolicyAlert> _alerts = new List<PolicyAlert>();
public List<PolicyAlert> Alerts
{
get
{
foreach (var recent in RecentAlerts)
{
if (!_alerts.Contains(recent))
_alerts.Add(recent);
}
return _alerts;
}
set { _alerts = value; }
}
public List<PolicyAlert> RecentAlerts
{
get
{
List<PolicyAlert> result = new List<PolicyAlert>();
foreach (var body in recent_alerts)
{
result.Add(new PolicyAlert(Connection, body));
}
return result;
}
}
public string LastResult
{
get
{
if (_recent_alerts.Length > 0)
{
var listRecentAlerts = new List<PolicyAlert>(RecentAlerts);
listRecentAlerts.Sort((x, y) => y.Time.CompareTo(x.Time));
if (listRecentAlerts[0].Type == "info")
return Messages.VM_PROTECTION_POLICY_SUCCEEDED;
return Messages.FAILED;
}
return Messages.NOT_YET_RUN;
}
}
}
}
| agimofcarmen/xenadmin | XenModel/XenAPI-Extensions/VMPP.cs | C# | bsd-2-clause | 12,194 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding-for-await/ary-ptrn-elision.case
// - src/dstr-binding-for-await/default/for-await-of-async-func-let.template
/*---
description: Elision advances iterator (for-await-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
features: [generators, destructuring-binding, async-iteration]
flags: [generated, async]
info: |
IterationStatement :
for await ( ForDeclaration of AssignmentExpression ) Statement
[...]
2. Return ? ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet, async).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. Let destructuring be IsDestructuring of lhs.
[...]
6. Repeat
[...]
j. If destructuring is false, then
[...]
k. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
[...]
iii. Else,
1. Assert: lhsKind is lexicalBinding.
2. Assert: lhs is a ForDeclaration.
3. Let status be the result of performing BindingInitialization
for lhs passing nextValue and iterationEnv as arguments.
[...]
13.3.3.6 Runtime Semantics: IteratorBindingInitialization
ArrayBindingPattern : [ Elision ]
1. Return the result of performing
IteratorDestructuringAssignmentEvaluation of Elision with iteratorRecord
as the argument.
12.14.5.3 Runtime Semantics: IteratorDestructuringAssignmentEvaluation
Elision : ,
1. If iteratorRecord.[[done]] is false, then
a. Let next be IteratorStep(iteratorRecord.[[iterator]]).
b. If next is an abrupt completion, set iteratorRecord.[[done]] to true.
c. ReturnIfAbrupt(next).
d. If next is false, set iteratorRecord.[[done]] to true.
2. Return NormalCompletion(empty).
---*/
var first = 0;
var second = 0;
function* g() {
first += 1;
yield;
second += 1;
};
var iterCount = 0;
async function fn() {
for await (let [,] of [g()]) {
assert.sameValue(first, 1);
assert.sameValue(second, 0);
iterCount += 1;
}
}
fn()
.then(() => assert.sameValue(iterCount, 1, 'iteration occurred as expected'), $DONE)
.then($DONE, $DONE);
| sebastienros/jint | Jint.Tests.Test262/test/language/statements/for-await-of/async-func-dstr-let-ary-ptrn-elision.js | JavaScript | bsd-2-clause | 2,376 |
cask "syncterm" do
version "1.1"
sha256 "24d7d0167a187336701fa1730fb4e04ed0d166204de73bb2d5cc2dd388a54308"
# sourceforge.net/syncterm/ was verified as official when first introduced to the cask
url "https://downloads.sourceforge.net/syncterm/syncterm/syncterm-#{version}/syncterm-#{version}-osx.zip"
appcast "https://sourceforge.net/projects/syncterm/rss"
name "SyncTERM"
homepage "https://syncterm.bbsdev.net/"
app "SyncTERM.app"
zap trash: [
"~/Library/Preferences/SyncTERM",
"~/Library/Preferences/syncterm.plist",
]
end
| haha1903/homebrew-cask | Casks/syncterm.rb | Ruby | bsd-2-clause | 555 |
#!/usr/bin/env python
import time
from concurrent.futures import ThreadPoolExecutor
from eucaops import Eucaops
from eucaops import S3ops
from eutester.eutestcase import EutesterTestCase
class WalrusConcurrent(EutesterTestCase):
def __init__(self):
self.setuptestcase()
self.setup_parser()
self.parser.add_argument("-n", "--number", type=int, default=100)
self.parser.add_argument("-c", "--concurrent", type=int, default=10)
self.parser.add_argument("-s", "--size", type=int, default=1024)
self.get_args()
# Setup basic eutester object
if self.args.region:
self.tester = S3ops( credpath=self.args.credpath, region=self.args.region)
else:
self.tester = Eucaops( credpath=self.args.credpath, config_file=self.args.config,password=self.args.password)
self.start = time.time()
self.bucket_name = "concurrency-" + str(int(self.start))
self.tester.create_bucket(self.bucket_name)
def clean_method(self):
self.tester.clear_bucket(self.bucket_name)
def Concurrent(self):
key_payload = self.tester.id_generator(self.args.size)
thread_count = self.args.number
thread_pool = []
with ThreadPoolExecutor(max_workers=thread_count) as executor:
for i in xrange(thread_count):
thread_pool.append(executor.submit(self.tester.upload_object, bucket_name=self.bucket_name, key_name="test" + str(i), contents=key_payload))
end = time.time()
total = end - self.start
self.tester.debug("\nExecution time: {0}\n# of Objects: {1}\nObject Size: {2}B\nConcurrency Level of {3}".format(
total, self.args.number, self.args.size, self.args.concurrent))
with ThreadPoolExecutor(max_workers=thread_count) as executor:
for object in thread_pool:
thread_pool.append(executor.submit(self.tester.delete_object, object))
if __name__ == "__main__":
testcase = WalrusConcurrent()
### Use the list of tests passed from config/command line to determine what subset of tests to run
### or use a predefined list
list = testcase.args.tests or ["Concurrent"]
### Convert test suite methods to EutesterUnitTest objects
unit_list = [ ]
for test in list:
unit_list.append( testcase.create_testunit_by_name(test) )
### Run the EutesterUnitTest objects
result = testcase.run_test_case_list(unit_list)
exit(result) | nagyistoce/eutester | testcases/cloud_user/s3/walrus_concurrency.py | Python | bsd-2-clause | 2,530 |
// Copyright 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.
#ifndef COMPONENTS_SYNC_ENGINE_SYNC_MANAGER_FACTORY_FOR_PROFILE_SYNC_TEST_H_
#define COMPONENTS_SYNC_ENGINE_SYNC_MANAGER_FACTORY_FOR_PROFILE_SYNC_TEST_H_
#include <memory>
#include <string>
#include "base/callback.h"
#include "components/sync/engine/sync_manager_factory.h"
namespace syncer {
class SyncManagerFactoryForProfileSyncTest : public SyncManagerFactory {
public:
explicit SyncManagerFactoryForProfileSyncTest(base::Closure init_callback);
~SyncManagerFactoryForProfileSyncTest() override;
std::unique_ptr<SyncManager> CreateSyncManager(
const std::string& name) override;
private:
base::Closure init_callback_;
};
} // namespace syncer
#endif // COMPONENTS_SYNC_ENGINE_SYNC_MANAGER_FACTORY_FOR_PROFILE_SYNC_TEST_H_
| ssaroha/node-webrtc | third_party/webrtc/include/chromium/src/components/sync/engine/sync_manager_factory_for_profile_sync_test.h | C | bsd-2-clause | 917 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML3.2 EN">
<HTML>
<HEAD>
<META NAME="GENERATOR" CONTENT="DOCTEXT">
<TITLE>MPI_Allgather</TITLE>
</HEAD>
<BODY BGCOLOR="FFFFFF">
<A NAME="MPI_Allgather"><H1>MPI_Allgather</H1></A>
Gathers data from all tasks and distribute the combined data to all tasks
<H2>Synopsis</H2>
<PRE>
int MPI_Allgather(void *sendbuf, int sendcount, MPI_Datatype sendtype,
void *recvbuf, int recvcount, MPI_Datatype recvtype,
MPI_Comm comm)
</PRE>
<H2>Input Parameters</H2>
<DL>
<DT><B>sendbuf </B><DD>starting address of send buffer (choice)
<DT><B>sendcount </B><DD>number of elements in send buffer (integer)
<DT><B>sendtype </B><DD>data type of send buffer elements (handle)
<DT><B>recvcount </B><DD>number of elements received from any process (integer)
<DT><B>recvtype </B><DD>data type of receive buffer elements (handle)
<DT><B>comm </B><DD>communicator (handle)
</DL>
<P>
<H2>Output Parameter</H2>
<DL><DT><B>recvbuf </B> <DD> address of receive buffer (choice)
</DL>
<P>
<H2>Notes</H2>
The MPI standard (1.0 and 1.1) says that
<BR>
<P>
<BR>
<P>
The jth block of data sent from each process is received by every process
and placed in the jth block of the buffer <TT>recvbuf</TT>.
<BR>
<P>
<BR>
<P>
This is misleading; a better description is
<BR>
<P>
<BR>
<P>
The block of data sent from the jth process is received by every
process and placed in the jth block of the buffer <TT>recvbuf</TT>.
<BR>
<P>
<BR>
<P>
This text was suggested by Rajeev Thakur and has been adopted as a
clarification by the MPI Forum.
<P>
<H2>Thread and Interrupt Safety</H2>
<P>
This routine is thread-safe. This means that this routine may be
safely used by multiple threads without the need for any user-provided
thread locks. However, the routine is not interrupt safe. Typically,
this is due to the use of memory allocation routines such as <TT>malloc
</TT>or other non-MPICH runtime routines that are themselves not interrupt-safe.
<P>
<H2>Notes for Fortran</H2>
All MPI routines in Fortran (except for <TT>MPI_WTIME</TT> and <TT>MPI_WTICK</TT>) have
an additional argument <TT>ierr</TT> at the end of the argument list. <TT>ierr
</TT>is an integer and has the same meaning as the return value of the routine
in C. In Fortran, MPI routines are subroutines, and are invoked with the
<TT>call</TT> statement.
<P>
All MPI objects (e.g., <TT>MPI_Datatype</TT>, <TT>MPI_Comm</TT>) are of type <TT>INTEGER
</TT>in Fortran.
<P>
<H2>Errors</H2>
<P>
All MPI routines (except <TT>MPI_Wtime</TT> and <TT>MPI_Wtick</TT>) return an error value;
C routines as the value of the function and Fortran routines in the last
argument. Before the value is returned, the current MPI error handler is
called. By default, this error handler aborts the MPI job. The error handler
may be changed with <TT>MPI_Comm_set_errhandler</TT> (for communicators),
<TT>MPI_File_set_errhandler</TT> (for files), and <TT>MPI_Win_set_errhandler</TT> (for
RMA windows). The MPI-1 routine <TT>MPI_Errhandler_set</TT> may be used but
its use is deprecated. The predefined error handler
<TT>MPI_ERRORS_RETURN</TT> may be used to cause error values to be returned.
Note that MPI does <EM>not</EM> guarentee that an MPI program can continue past
an error; however, MPI implementations will attempt to continue whenever
possible.
<P>
<DL><DT><B>MPI_ERR_COMM </B> <DD> Invalid communicator. A common error is to use a null
communicator in a call (not even allowed in <TT>MPI_Comm_rank</TT>).
</DL>
<DL><DT><B>MPI_ERR_COUNT </B> <DD> Invalid count argument. Count arguments must be
non-negative; a count of zero is often valid.
</DL>
<DL><DT><B>MPI_ERR_TYPE </B> <DD> Invalid datatype argument. May be an uncommitted
MPI_Datatype (see <TT>MPI_Type_commit</TT>).
</DL>
<DL><DT><B>MPI_ERR_BUFFER </B> <DD> Invalid buffer pointer. Usually a null buffer where
one is not valid.
</DL>
<P><B>Location:</B>allgather.c<P>
</BODY></HTML>
| hydrosolutions/model_RRMDA_Themi | java/resources/linux64_gnu/share/doc/www3/MPI_Allgather.html | HTML | bsd-2-clause | 3,951 |
#
# Copyright (c) 2005
# The President and Fellows of Harvard College.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the University 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 UNIVERSITY 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 UNIVERSITY 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: Geoffrey Mainland <mainland@eecs.harvard.edu>
#
__all__ = ["message", "packet", "utils", "tossim"]
| jf87/smap | python/tinyos/__init__.py | Python | bsd-2-clause | 1,659 |
/**
*
*/
package cz.metacentrum.perun.core.bl;
import cz.metacentrum.perun.core.api.ActionType;
import java.util.HashMap;
import java.util.List;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributeRights;
import cz.metacentrum.perun.core.api.Facility;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Host;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.PerunBean;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.Resource;
import cz.metacentrum.perun.core.api.RichAttribute;
import cz.metacentrum.perun.core.api.Service;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.UserExtSource;
import cz.metacentrum.perun.core.api.Vo;
import cz.metacentrum.perun.core.api.exceptions.ActionTypeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.AttributeExistsException;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.ModuleNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.RelationExistsException;
import cz.metacentrum.perun.core.api.exceptions.UserNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.VoNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongModuleTypeException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.implApi.modules.attributes.UserVirtualAttributesModuleImplApi;
import java.util.Map;
import java.util.Set;
/**
* @author Michal Prochazka <michalp@ics.muni.cz>
* @author Slavek Licehammer <glory@ics.muni.cz>
*/
public interface AttributesManagerBl {
/**
* Get all <b>non-empty</b> attributes associated with the facility.
*
* @param sess perun session
* @param facility facility to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Facility facility) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the vo.
*
* @param sess perun session
* @param vo vo to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Vo vo) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the group.
*
* @param sess perun session
* @param group group to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Group group) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the resource.
*
* @param sess perun session
* @param resource resource to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Resource resource) throws InternalErrorException;
/**
* Remove all non-virtual group-resource attributes assigned to resource
*
* @param sess
* @param resource
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
void removeAllGroupResourceAttributes(PerunSession sess, Resource resource) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Remove all non-virtual member-resource attributes assigned to resource
*
* @param sess
* @param resource
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
void removeAllMemberResourceAttributes(PerunSession sess, Resource resource) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Get all virtual attributes associated with the member-resource attributes.
*
* @param sess perun session
* @param resource to get the attributes from
* @param member to get the attributes from
* @return list of attributes
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getVirtualAttributes(PerunSession sess, Resource resource, Member member) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the member on the resource.
*
* @param sess perun session
* @param resource to get the attributes from
* @param member to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getAttributes(PerunSession sess, Resource resource, Member member) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Gets all <b>non-empty</b> attributes associated with the member on the resource and if workWithUserAttributes is
* true, gets also all <b>non-empty</b> user, user-facility and member attributes.
*
* @param sess perun session
* @param resource to get the attributes from
* @param member to get the attributes from
* @param workWithUserAttributes if true returns also user-facility, user and member attributes (user is automatically get from member a facility is get from resource)
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/
List<Attribute> getAttributes(PerunSession sess, Resource resource, Member member, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get all <b>non-empty</b> attributes associated with the member in the group.
*
* @param sess perun session
* @param member to get the attributes from
* @param group group to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getAttributes(PerunSession sess, Member member, Group group) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get all attributes (empty and virtual too) associated with the member in the group which have name in list attrNames.
*
* @param sess perun session
* @param member to get the attributes from
* @param group group to get the attributes from
* @param attrNames list of attributes' names
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getAttributes(PerunSession sess, Member member, Group group, List<String> attrNames) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get all attributes associated with the member in the group and if workWithUserAttributes is true, gets also all <b>non-empty</b> user and member attributes.
*
* @param sess perun session
* @param member to get the attributes from
* @param group group to get the attributes from
* @param workWithUserAttributes if true returns also user and member attributes (user is automatically get from member)
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getAttributes(PerunSession sess, Member member, Group group, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get all <b>non-empty</b> attributes associated with the member and if workWithUserAttributes is
* true, get all <b>non-empty</b> attributes associated with user, who is this member.
*
* @param sess perun session
* @param member to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Member member, boolean workWithUserAttributes) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the member.
*
* @param sess perun session
* @param member to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Member member) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the group starts with name startPartOfName.
* Get only nonvirtual attributes with notNull Value.
*
*
* @param sess perun session
* @param group to get the attributes from
* @param startPartOfName attribute name start with this part
* @return list of attributes which name start with startPartOfName
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAllAttributesStartWithNameWithoutNullValue(PerunSession sess, Group group, String startPartOfName) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the resource starts with name startPartOfName.
* Get only nonvirtual attributes with notNull value.
*
* @param sess perun session
* @param resource to get the attributes from
* @param startPartOfName attribute name start with this part
* @return list of attributes which name start with startPartOfName
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAllAttributesStartWithNameWithoutNullValue(PerunSession sess, Resource resource, String startPartOfName) throws InternalErrorException;
/**
* Get all attributes associated with the member which have name in list attrNames (empty too)
* Virtual attributes too.
*
* If workWithUserAttribute is true, return also all user attributes in list of attrNames (with virtual attributes too).
*
* @param sess perun session
* @param member to get the attributes from
* @param attrNames list of attributes' names
* @param workWithUserAttributes if user attributes need to be return too
* @return list of member (and also if needed user) attributes
* @throws InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Member member, List<String> attrNames, boolean workWithUserAttributes) throws InternalErrorException;
/**
* Get all attributes associated with the member which have name in list attrNames (empty and virtual too).
*
* @param sess perun session
* @param member to get the attributes from
* @param attrNames list of attributes' names
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Member member, List<String> attrNames) throws InternalErrorException;
/**
* Get all attributes associated with the group which have name in list attrNames (empty too).
* Virtual attribute too.
*
* @param sess perun session
* @param group to get the attributes from
* @param attrNames list of attributes' names
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Group group, List<String> attrNames) throws InternalErrorException;
/**
* Get all attributes associated with the vo which have name in list attrNames (empty and virtual too).
*
* @param sess perun session
* @param vo to get the attributes from
* @param attrNames list of attributes' names
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wraped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Vo vo, List<String> attrNames) throws InternalErrorException;
/**
* Get all attributes associated with the user which have name in list attrNames (empty and virtual too).
*
* @param sess perun session
* @param user to get the attributes from
* @param attrNames list of attributes' names
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, User user, List<String> attrNames) throws InternalErrorException;
/**
* Get all attributes associated with the UserExtSource which have name in list attrNames (empty and virtual too).
*
* @param sess perun session
* @param ues to get the attributes from
* @param attrNames list of attributes' names
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wraped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, UserExtSource ues, List<String> attrNames) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the user on the facility.
*
* @param sess perun session
* @param facility to get the attributes from
* @param user to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Facility facility, User user) throws InternalErrorException;
/**
* Returns all attributes with not-null value which fits the attributeDefinition. Can't process core or virtual attributes.
*
* @param sess
* @param attributeDefinition can't be core or virtual attribute
* @return list of attributes
* @throws InternalErrorException
*/
List<Attribute> getAttributesByAttributeDefinition(PerunSession sess, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get all virtual attributes associated with the user on the facility.
*
* @param sess perun session
* @param facility to get the attributes from
* @param user to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getVirtualAttributes(PerunSession sess, Facility facility, User user) throws InternalErrorException;
/**
* Get all virtual attributes associated with the user.
*
* @param sess perun session
* @param user to get the attributes from
* @return list of attributes
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getVirtualAttributes(PerunSession sess, User user) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the user.
*
* @param sess perun session
* @param user to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, User user) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the host
* @param sess perun session
* @param host host to get attributes from
* @return list of attributes
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, Host host) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the group on resource.
* @param sess
* @param resource
* @param group
* @return list of attributes
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getAttributes(PerunSession sess, Resource resource, Group group) throws InternalErrorException, WrongAttributeAssignmentException;
List<Attribute> getAttributes(PerunSession sess, Resource resource, Group group, boolean workWithGroupAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get all <b>non-empty</b> member, user, member-resource and user-facility attributes.
*
* @param sess
* @param facility
* @param resource
* @param user
* @param member
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getAttributes(PerunSession sess, Facility facility, Resource resource, User user, Member member) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get all entityless attributes with subject equaled String key
*
* @param sess
* @param Key
* @return
* @throws InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, String Key) throws InternalErrorException;
/**
* Get all <b>non-empty</b> attributes associated with the UserExtSource.
*
* @param sess perun session
* @param ues to get the attributes from
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getAttributes(PerunSession sess, UserExtSource ues) throws InternalErrorException;
/**
* Get all entityless attributes with attributeName
* @param sess perun session
* @param attrName
* @return attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getEntitylessAttributes(PerunSession sess, String attrName) throws InternalErrorException;
/**
* Returns list of Keys which fits the attributeDefinition.
* @param sess
* @param attributeDefinition
* @return
* @throws InternalErrorException
*/
List<String> getEntitylessKeys(PerunSession sess, AttributeDefinition attributeDefinition) throws InternalErrorException;
/**
* Returns entityless attribute by attr_id and key (subject) for update!
*
* For update - means lock row with attr_values in DB (entityless_attr_values with specific subject and attr_id)
*
* Not lock row in attr_names!
*
* IMPORTANT: This method use "select for update" and locks row for transaction. Use clever.
*
* If attribute with subject=key not exists, create new one with null value and return it.
*
* @param sess
* @param attrName
* @param key
* @return attr_value in string
*
* @throws InternalErrorException if runtime error exception has been thrown
* @throws AttributeNotExistsException throw exception if attribute with value not exists in DB
*/
Attribute getEntitylessAttributeForUpdate(PerunSession sess, String key, String attrName) throws InternalErrorException, AttributeNotExistsException;
/**
* Store the attributes associated with the facility. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param facility facility to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not facility attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Facility facility, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the facility, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess perun session
* @param facility facility to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is not resource attribute or if it is core attribute
*
* @return true, if attribute was set in DB
*/
boolean setAttributeWithoutCheck(PerunSession sess, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the vo, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess
* @param vo
* @param attribute
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
boolean setAttributeWithoutCheck(PerunSession sess, Vo vo, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the user-facility, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess
* @param facility
* @param user
* @param attribute
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
boolean setAttributeWithoutCheck(PerunSession sess, Facility facility, User user, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the member-resource, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess
* @param resource
* @param member
* @param attribute
* @param workWithUserAttributes
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
boolean setAttributeWithoutCheck(PerunSession sess, Resource resource, Member member, Attribute attribute, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the member-group, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess
* @param member
* @param group
* @param attribute
* @param workWithUserAttributes
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
boolean setAttributeWithoutCheck(PerunSession sess, Member member, Group group, Attribute attribute, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the member, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess
* @param member
* @param attribute
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
boolean setAttributeWithoutCheck(PerunSession sess, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the host, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess
* @param host
* @param attribute
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
boolean setAttributeWithoutCheck(PerunSession sess, Host host, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the entityless, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess
* @param key
* @param attribute
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
boolean setAttributeWithoutCheck(PerunSession sess, String key, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the vo. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param vo vo to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not vo attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Vo vo, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the group. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param group group to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not group attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Group group, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the resource. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param resource resource to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not resource attribute
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeValueException
*/
void setAttributes(PerunSession sess, Resource resource, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the resource and member combination. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param resource resource to set on
* @param member member to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Resource resource, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the resource and member combination. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
* If workWithUserAttributes is true, the method stores also the attributes associated with user, user-facility and member.
*
* @param sess perun session
* @param resource resource to set on
* @param member member to set on
* @param attributes attribute to set
* @param workWithUserAttributes method can process also user, user-facility and member attributes (user is automatically get from member a facility is get from resource)
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute
* @throws WrongReferenceAttributeValueException
*
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/
void setAttributes(PerunSession sess, Resource resource, Member member, List<Attribute> attributes, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the resource and member combination. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param member member to set on
* @param group group to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Member member, Group group, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException, UserNotExistsException;
/**
* Store the attributes associated with the resource and member combination. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
* If workWithUserAttributes is true, the method stores also the attributes associated with user and member.
*
* @param sess perun session
* @param member member to set on
* @param group group to set on
* @param attributes attribute to set
* @param workWithUserAttributes method can process also user and member attributes (user is automatically get from member)
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Member member, Group group, List<Attribute> attributes, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException, UserNotExistsException;
/**
* Store the member, user, member-resource and user-facility attributes. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param facility
* @param resource
* @param user
* @param member
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Facility facility, Resource resource, User user, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the resource. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param member member to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the facility and user combination. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param facility facility to set on
* @param user user to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not user-facility attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Facility facility, User user, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the user. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param user user to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not user-facility attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, User user, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the host. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
* @param sess perun session
* @param host host to set attributes for
* @param attributes attributes to be set
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not host attribute
*/
void setAttributes(PerunSession sess, Host host, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Stores the group-resource attributes.
* @param sess
* @param resource
* @param group
* @param attributes
* @throws InternalErrorException
* @throws WrongAttributeValueException
* @throws WrongAttributeAssignmentException
*/
void setAttributes(PerunSession sess, Resource resource, Group group, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
void setAttributes(PerunSession sess, Resource resource, Group group, List<Attribute> attributes, boolean workWithGroupAttributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with the user external source. If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param ues user external source to set on
* @param attributes attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not user external source attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, UserExtSource ues, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Get particular attribute for the facility.
*
* @param sess
* @param facility to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, Facility facility, String attributeName) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException;
/**
* Get particular attribute for the vo.
*
* @param sess
* @param vo to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws AttributeNotExistsException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, Vo vo, String attributeName) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException;
/**
* This method get all similar attr_names which start with partOfAttributeName
*
* @param sess
* @param startingPartOfAttributeName is something like: urn:perun:user_facility:attribute-def:def:login-namespace:
* @return list of similar attribute names like: urn:perun:user_facility:attribute-def:def:login-namespace:cesnet etc.
* @throws InternalErrorException
* @throws AttributeNotExistsException
*/
List<String> getAllSimilarAttributeNames(PerunSession sess, String startingPartOfAttributeName) throws InternalErrorException;
/**
* Get particular attribute for the group.
*
* @param sess
* @param group group get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws AttributeNotExistsException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, Group group, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the resource.
*
* @param sess
* @param resource to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, Resource resource, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the member on this resource.
*
* @param sess
* @param resource to get attribute from
* @param member to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, Resource resource, Member member, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the member in this group.
*
* @param sess
* @param member to get attribute from
* @param group to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws AttributeNotExistsException if the attribute doesn't exists in the underlying data source
*/
Attribute getAttribute(PerunSession sess, Member member, Group group, String attributeName) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException;
/**
* Get particular attribute for the member.
*
* @param sess
* @param member to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, Member member, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the user on this facility.
*
* @param sess
* @param facility to get attribute from
* @param user to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, Facility facility, User user, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the user.
*
* @param sess
* @param user to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, User user, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the host
* @param sess
* @param host host to get attribute from
* @param attributeName attribute name
* @return attribute
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws AttributeNotExistsException
*/
Attribute getAttribute(PerunSession sess, Host host, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular group attribute on the resource
* @param sess
* @param resource
* @param group
* @param attributeName
* @return attribute
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws AttributeNotExistsException
*/
Attribute getAttribute(PerunSession sess, Resource resource, Group group, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular entityless attribute
* @param sess perun session
* @param key key to get attribute for
* @param attributeName
* @return attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source
* @throws WrongAttributeAssignmentException if attribute isn't entityless attribute
*/
Attribute getAttribute(PerunSession sess, String key, String attributeName) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException;
/**
* Get particular attribute for the User External Source.
*
* @param sess
* @param ues to get attribute from
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttribute(PerunSession sess, UserExtSource ues, String attributeName) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get attribute definition (attribute without defined value).
*
* @param attributeName attribute name defined in the particular manager
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
AttributeDefinition getAttributeDefinition(PerunSession sess, String attributeName) throws InternalErrorException, AttributeNotExistsException;
/**
* Get all attributes definition (attribute without defined value).
*
* @return List od attributes definitions
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<AttributeDefinition> getAttributesDefinition(PerunSession sess) throws InternalErrorException;
/**
* Get all (for entities) attributeDefinitions which user has right to READ them and fill attribute writable (if user has also right to WRITE them).
* For entities means that return only those attributeDefinition which are in namespace of entities or possible combination of entities.
* For Example: If enityties are "member, user, resource" then return only AD in namespaces "member, user, resource and resource-member"
*
* @param sess
* @param entities list of perunBeans (member, user...)
*
* @return list of AttributeDefinitions with rights (writable will be filled correctly by user in session)
* @throws InternalErrorException
* @throws AttributeNotExistsException
*/
List<AttributeDefinition> getAttributesDefinitionWithRights(PerunSession sess, List<PerunBean> entities) throws InternalErrorException, AttributeNotExistsException;
/**
* From listOfAttributesNames get list of attributeDefinitions
*
* @param sess
* @param listOfAttributesNames
* @return list of AttributeDefinitions
* @throws InternalErrorException
* @throws AttributeNotExistsException
*/
List<AttributeDefinition> getAttributesDefinition(PerunSession sess, List<String> listOfAttributesNames) throws InternalErrorException, AttributeNotExistsException;
/**
* Get attribute definition (attribute without defined value).
*
* @param id attribute id
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
AttributeDefinition getAttributeDefinitionById(PerunSession sess, int id) throws InternalErrorException, AttributeNotExistsException;
/**
* Get attributes definition (attribute without defined value) with specified namespace.
*
* @param namespace get only attributes with this namespace
* @return List of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<AttributeDefinition> getAttributesDefinitionByNamespace(PerunSession sess, String namespace) throws InternalErrorException;
/**
* Get particular attribute for the facility.
*
* @param sess
* @param facility to get attribute from
* @param id attribute id
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttributeById(PerunSession sess, Facility facility, int id) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the vo.
*
* @param sess
* @param vo to get attribute from
* @param id attribute id
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttributeById(PerunSession sess, Vo vo, int id) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the resource.
*
* @param sess
* @param resource to get attribute from
* @param id attribute id
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttributeById(PerunSession sess, Resource resource, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the member on this resource.
*
* @param sess
* @param resource to get attribute from
* @param member to get attribute from
* @param id attribute id
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttributeById(PerunSession sess, Resource resource, Member member, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the member in this group. Also it can return only member or only user attribute
* if attr definition is not from NS_MEMBER_GROUP_ATTR but from NS_MEMBER_ATTR or NS_GROUP_ATTR
*
* @param sess perun session
* @param member to get attribute from
* @param group to get attribute from
* @param id attribute id
* @return memberGroup, member OR user attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws AttributeNotExistsException if the attribute doesn't exists in the underlying data source
*/
Attribute getAttributeById(PerunSession sess, Member member, Group group, int id) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException;
/**
* Get particular attribute for the member.
*
* @param sess
* @param member to get attribute from
* @param id attribute id
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttributeById(PerunSession sess, Member member, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the user on this facility.
*
* @param sess
* @param facility to get attribute from
* @param user to get attribute from
* @param id attribute id
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttributeById(PerunSession sess, Facility facility, User user, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the user.
*
* @param sess
* @param user to get attribute from
* @param id attribute id
* @return attribute
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute getAttributeById(PerunSession sess, User user, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the host
* @param sess perun session
* @param host to get attribute from
* @param id id of attribute
* @return attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is not host attribute
* @throws AttributeNotExistsException if attribute doesn't exist
*/
Attribute getAttributeById(PerunSession sess, Host host, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular group-resource attribute
* @param sess
* @param resource
* @param group
* @param id
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws AttributeNotExistsException
*/
Attribute getAttributeById(PerunSession sess, Resource resource, Group group, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular group attribute
* @param sess
* @param group
* @param id
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws AttributeNotExistsException
*/
Attribute getAttributeById(PerunSession sess, Group group, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get particular attribute for the user external source
* @param sess perun session
* @param ues to get attribute from
* @param id id of attribute
* @return attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is not user external source attribute
* @throws AttributeNotExistsException if attribute doesn't exist
*/
Attribute getAttributeById(PerunSession sess, UserExtSource ues, int id) throws InternalErrorException, WrongAttributeAssignmentException, AttributeNotExistsException;
/**
* Get and set required attribute for member, resource, user and facility.
*
* Procedure:
* 1] Get all member, member-resource, user, user-facility required attributes for member and resource.
* 2] Fill attributes and store those which were really filled. (value changed)
* 3] Set filled attributes.
* 4] Refresh value in all virtual attributes.
* 5] Check all attributes and their dependencies.
*
* @param sess
* @param member
* @param resource
* @param user
* @param facility
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongReferenceAttributeValueException
* @throws AttributeNotExistsException
* @throws WrongAttributeValueException
*/
void setRequiredAttributes(PerunSession sess, Facility facility, Resource resource, User user, Member member) throws InternalErrorException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeValueException;
/**
* Get and set required attribute for member, resource, user, facility and specific service.
*
* Procedure:
* 1] Get all member, member-resource, user, user-facility required attributes for member, resource and specific service.
* 2] Fill attributes and store those which were really filled. (value changed)
* 3] Set filled attributes.
* 4] Refresh value in all virtual attributes.
* 5] Check all attributes and their dependencies.
*
* @param sess
* @param service
* @param facility
* @param resource
* @param user
* @param member
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongReferenceAttributeValueException
* @throws AttributeNotExistsException
* @throws WrongAttributeValueException
*/
void setRequiredAttributes(PerunSession sess, Service service, Facility facility, Resource resource, User user, Member member) throws InternalErrorException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeValueException;
/**
* Get and set required attributes from arrayList for member, resource, user and facility.
*
* IMPORTANT: set all attrs from arrayList, set not required attrs too if they are in arrayList
*
* Procedure:
* 1] Get all attrs from arrayList
* 2] Fill attributes and store those which were really filled. (value changed)
* 3] Set filled attributes.
* 4] Refresh value in all virtual attributes.
* 5] Check all attributes and their dependencies.
*
* @param sess
* @param facility
* @param resource
* @param user
* @param member
* @param attributes
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongReferenceAttributeValueException
* @throws AttributeNotExistsException
* @throws WrongAttributeValueException
*/
void setRequiredAttributes(PerunSession sess, Facility facility, Resource resource, User user, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException, AttributeNotExistsException, WrongAttributeValueException;
/**
* Store the particular attribute associated with the facility. Core attributes can't be set this way.
*
* @param sess perun session
* @param facility facility to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not facility attribute or if it is core attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the particular attribute associated with the vo. Core attributes can't be set this way.
*
* @param sess perun session
* @param vo vo to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not vo attribute or if it is core attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Vo vo, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the particular attribute associated with the group. Core attributes can't be set this way.
*
* @param sess perun session
* @param group group to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not group attribute or if it is core attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the particular attribute associated with the resource. Core attributes can't be set this way.
*
* @param sess perun session
* @param resource resource to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not resource attribute or if it is core attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the resource, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess perun session
* @param resource resource to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is not resource attribute or if it is core attribute
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*
* @return true, if attribute was set in DB
*/
boolean setAttributeWithoutCheck(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the particular attribute associated with the group, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess perun session
* @param group
* @param attribute
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is not group attribute or if it is core attribute
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*
* @return true, if attribute was set in DB
*/
boolean setAttributeWithoutCheck(PerunSession sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Store the particular attribute associated with the resource and member combination. Core attributes can't be set this way.
*
* @param sess perun session
* @param resource resource to set on
* @param member member to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute or if it is core attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Resource resource, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the particular attribute associated with the group and member combination. Core attributes can't be set this way.
*
* @param sess perun session
* @param member member to set on
* @param group group to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws AttributeNotExistsException if the attribute doesn't exists in the underlying data source
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute or if it is core attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Member member, Group group, Attribute attribute) throws InternalErrorException, AttributeNotExistsException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the particular attribute associated with the member. Core attributes can't be set this way.
*
* @param sess perun session
* @param member member to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute or if it is core attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the particular attribute associated with the member. Core attributes can't be set this way.
*
* This method creates nested transaction to prevent storing value to DB if it throws any exception.
*
* @param sess perun session
* @param member member to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource attribute or if it is core attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributeInNestedTransaction(PerunSession sess, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attribute associated with the facility and user combination. Core attributes can't be set this way.
*
* @param sess perun session
* @param facility facility to set on
* @param user user to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not user-facility attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Facility facility, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attribute associated with the user. Core attributes can't be set this way.
*
* @param sess perun session
* @param user user to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not user-facility attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attribute associated with the user. Core attributes can't be set this way.
*
* This method creates nested transaction to prevent storing value to DB if it throws any exception.
*
* @param sess perun session
* @param user user to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not user-facility attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttributeInNestedTransaction(PerunSession sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Just store the attribute associated with the user, doesn't preform any value check. Core attributes can't be set this way.
*
* @param sess perun session
* @param user user to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is not user-facility attribute
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*
* @return true, if attribute was set in DB
*/
boolean setAttributeWithoutCheck(PerunSession sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Store the attribute associated with the host. Core attributes can't be set this way.
* @param sess perun session
* @param host host to set attributes for
* @param attribute attribute to be set
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is not host attribute
* @throws WrongAttributeValueException if the attribute value is illegal
*/
void setAttribute(PerunSession sess, Host host, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Store the group-resource attribute
* @param sess
* @param resource
* @param group
* @param attribute
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Just store the group-resource attribute, do not preform any value check.
* @param sess
* @param resource
* @param group
* @param attribute
* @throws InternalErrorException
* @throws WrongReferenceAttributeValueException Can be raised while storing virtual attribute if another attribute which is required for set virtual attribute have wrong value
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
*
* @return true, if attribute was set in DB
*/
boolean setAttributeWithoutCheck(PerunSession sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Stores entityless attribute (associated with string key).
* @param sess perun session
* @param key store the attribute for this key
* @param attribute attribute to set
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not entityless attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, String key, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Store the attribute associated with the user external source.
*
* @param sess perun session
* @param ues user external source to set on
* @param attribute attribute to set
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not user external source attribute
* @throws WrongReferenceAttributeValueException
*/
void setAttribute(PerunSession sess, UserExtSource ues, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Creates an attribute, the attribute is stored into the appropriate DB table according to the namespace
*
* @param sess perun session
* @param attributeDefinition attribute to create
*
* @return attribute with set id
*
* @throws AttributeExistsException if attribute already exists
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
AttributeDefinition createAttribute(PerunSession sess, AttributeDefinition attributeDefinition) throws InternalErrorException, AttributeExistsException;
/**
* Deletes the attribute.
*
* @param sess
* @param attributeDefinition
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws RelationExistsException
*/
void deleteAttribute(PerunSession sess, AttributeDefinition attributeDefinition) throws InternalErrorException, RelationExistsException;
/**
* Delete all authz for the attribute.
*
* @param sess
* @param attribute the attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorExceptions
*/
void deleteAllAttributeAuthz(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException;
/**
* Deletes the attribute.
*
* @param sess
* @param attributeDefinition attribute to delete
* @param force delete also all existing relation. If this parameter is true the RelationExistsException is never thrown.
* @throws InternalErrorException
* @throws RelationExistsException
*/
void deleteAttribute(PerunSession sess, AttributeDefinition attributeDefinition, boolean force) throws InternalErrorException, RelationExistsException;
/**
* Get attributes definions required by all services assigned on the resource.
*
* @param sess perun session
* @param resource
* @return attributes definions required by all services assigned on the resource.
*
* @throws InternalErrorException
*/
List<AttributeDefinition> getResourceRequiredAttributesDefinition(PerunSession sess, Resource resource) throws InternalErrorException;
/**
* Get facility attributes which are required by services. Services are known from the resource.
*
* @param sess perun session
* @param resourceToGetServicesFrom resource from which the services are taken
* @param facility you get attributes for this facility
* @return list of facility attributes which are required by services which are assigned to resource
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Facility facility) throws InternalErrorException;
/**
* Get resource attributes which are required by services. Services are known from the resourceToGetServicesFrom.
*
* @param sess perun session
* @param resourceToGetServicesFrom resource from which the services are taken
* @param resource resource from which the services are taken and for which you want to get the attributes
* @return list of resource attributes which are required by services which are assigned to resource.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Resource resource) throws InternalErrorException;
/**
* Get member-resource attributes which are required by services. Services are known from the resourceToGetServicesFrom.
*
* @param sess perun session
* @param resourceToGetServicesFrom resource from which the services are taken
* @param resource you get attributes for this resource and the member
* @param member you get attributes for this member
* @return list of facility attributes which are required by services which are assigned to resource.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Resource resource, Member member) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get member-resource attributes which are required by services and if workWithUserAttributes is true also user, user-facility and member attributes.
* Services are known from the resourceToGetServicesFrom.
*
* @param sess perun session
* @param resourceToGetServicesFrom getRequired attributes from services which are assigned on this resource
* @param resource you get attributes for this resource and the member
* @param member you get attributes for this member and the resource
* @param workWithUserAttributes method can process also user, user-facility and member attributes (user is automatically get from member a facility is get from resource)
* @return list of member-resource attributes (if workWithUserAttributes is true also user, user-facility and member attributes) which are required by services which are assigned to another resource.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Resource resource, Member member, boolean workWithUserAttributes) throws WrongAttributeAssignmentException, InternalErrorException;
/**
* Get member-group attributes which are required by services. Services are known from the resourceToGetServicesFrom.
*
* @param sess perun session
* @param resourceToGetServicesFrom resource from which the services are taken
* @param member you get attributes for this member
* @param group you get attributes for this group and the member
* @return list of member-group's attributes which are required by services defined on specified resource
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Member member, Group group) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get member-group attributes which are required by services if workWithUserAttributes is true also user and member attributes.
* Services are known from the resourceToGetServicesFrom.
*
* @param sess perun session
* @param resourceToGetServicesFrom resource from which the services are taken
* @param member you get attributes for this member
* @param group you get attributes for this group and the member
* @param workWithUserAttributes method can process also user and member attributes (user is automatically get from member)
* @return list of member-group's attributes which are required by services defined on specified resource
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Member member, Group group, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get member, user, member-resource and user-facility attributes which are required by services which are defined on "resourceToGetServicesFrom" resource.
*
* @param sess perun session
* @param resourceToGetServicesFrom getRequired attributes from services which are assigned on this resource
* @param facility
* @param resource you get attributes for this resource and the member
* @param user
* @param member you get attributes for this member and the resource
* @return list of member-resource attributes which are required by services which are assigned to specified resource
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Facility facility, Resource resource, User user, Member member) throws WrongAttributeAssignmentException, InternalErrorException;
/**
* Get member attributes which are required by services defined on specified resource
*
* @param sess perun session
* @param member you get attributes for this member
* @param resourceToGetServicesFrom getRequired attributes from services which are assigned on this resource
* @return list of member attributes which are required by services defined on specified resource
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Member member) throws InternalErrorException;
/**
* Get user-facility attributes which are required by services. Services are known from the resource.
*
* @param sess perun session
* @param resourceToGetServicesFrom resource from which the services are taken
* @param facility facility from which the services are taken
* @param user you get attributes for this user
* @return list of user-facility attributes which are required by service
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Facility facility, User user) throws InternalErrorException;
/**
* Get user attributes which are required by services. Services are known from the resource.
*
* @param sess perun session
* @param resourceToGetServicesFrom resource from which the services are taken
* @param user you get attributes for this user
* @return list of users attributes which are required by service
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, User user) throws InternalErrorException;
/**
* Get the group-resource attributes which are required by services. Services are known from the resource.
* @param sess
* @param resourceToGetServicesFrom resource from which the services are taken
* @param resource
* @param group
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Resource resource, Group group) throws InternalErrorException, WrongAttributeAssignmentException;
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Resource resource, Group group, boolean workWithGroupAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get the host attributes which are required by services. Services are known from the resource.
* @param sess
* @param resourceToGetServicesFrom
* @param host
* @return
* @throws InternalErrorException
*/
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Host host) throws InternalErrorException;
List<Attribute> getResourceRequiredAttributes(PerunSession sess, Resource resourceToGetServicesFrom, Group group) throws InternalErrorException;
/**
* Get facility attributes which are required by all services which are connected to this facility.
*
* @param sess perun session
* @param facility you get attributes for this facility
* @return list of facility attributes which are required by all services which are connected to this facility.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Facility facility) throws InternalErrorException;
/**
* Get resource attributes which are required by selected services.
*
* @param sess perun session
* @param resource you get attributes for this resource
* @param services
* @return list of resource attributes which are required by selected services.
* @throws InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Resource resource) throws InternalErrorException;
/**
* Get resource attributes which are required by services which is related to this resource.
*
* @param sess perun session
* @param resource resource for which you want to get the attributes
* @return list of resource attributes which are required by services which are assigned to resource.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Resource resource) throws InternalErrorException;
/**
* Get member-resource attributes which are required by services which are relater to this member-resource.
*
* @param sess perun session
* @param resource you get attributes for this resource and the member
* @param member you get attributes for this member and the resource
* @return list of facility attributes which are required by services which are assigned to resource.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Resource resource, Member member) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* If workWithUserAttribute is false => Get member-resource attributes which are required by services which are relater to this member-resource.
* If workWithUserAttributes is true => Get member-resource, user-facility, user and member attributes. (user is get from member and facility from resource)
*
* @param sess perun session
* @param resource you get attributes for this resource and the member
* @param member you get attributes for this member and the resource
* @param workWithUserAttributes method can process also user, user-facility and member attributes (user is automatically get from member a facility is get from resource)
* @return list of member-resource attributes or if workWithUserAttributes is true return list of member-resource, user, member and user-facility attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Resource resource, Member member, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get user-facility attributes which are required by services which are related to this user-facility.
*
* @param sess perun session
* @param facility facility from which the services are taken
* @param user you get attributes for this user
* @return list of facility attributes which are required by services which are assigned to facility.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Facility facility, User user) throws InternalErrorException;
/**
* Get user attributes which are required by services which are relater to this user.
*
* @param sess perun session
* @param user
* @return list of user's attributes which are required by services which are related to this user
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, User user) throws InternalErrorException;
/**
* Get member attributes which are required by services which are relater to this member and
* if is workWithUserAttributes = true, then also user required attributes
*
* @param sess perun session
* @param member you get attributes for this member
*
* @return list of member, user attributes which are required by services which are related to this member
* @param workWithUserAttributes method can process also user and user-facility attributes (user is automatically get from member a facility is get from resource)
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Member member, boolean workWithUserAttributes) throws InternalErrorException;
/**
* Get all attributes which are required by service.
* Required attributes are requisite for Service to run.
*
* @param sess sess
* @param service service from which the attributes will be listed
*
* @return All attributes which are required by service.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<AttributeDefinition> getRequiredAttributesDefinition(PerunSession sess, Service service) throws InternalErrorException;
/**
* Get facility attributes which are required by the service.
*
* @param sess perun session
* @param facility you get attributes for this facility
* @param service attribute required by this service you'll get
* @return list of facility attributes which are required by the service
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Facility facility) throws InternalErrorException;
/**
* Get vo attributes which are required by the service.
*
* @param sess perun session
* @param vo you get attributes for this vo
* @param service attribute required by this service you'll get
* @return list of vo attributes which are required by the service
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Vo vo) throws InternalErrorException;
/**
* Get resource attributes which are required by the service.
*
* @param sess perun session
* @param resource resource for which you want to get the attributes
* @param service attribute required by this service you'll get
* @return list of resource attributes which are required by the service
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Resource resource) throws InternalErrorException;
/**
* Get member-resource attributes which are required by the service.
*
* @param sess perun session
* @param resource you get attributes for this resource and the member
* @param member you get attributes for this member and the resource
* @param service attribute required by this service you'll get
* @return list of attributes which are required by the service.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Resource resource, Member member) throws InternalErrorException, WrongAttributeAssignmentException;
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Resource resource, Member member, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get member-resource, member, user-facility and user attributes which are required by service for each member in list of members.
* If workWithUserAttributes is false return only member-resource attributes.
* !!! Method checks if members list is not empty (returns empty HashMap)!!!
*
* @param sess perun session
* @param service attribute required by this service
* @param resource you get attributes for this resource
* @param members you get attributes for this list of members
* @param workWithUserAttributes if true method can process also user, user-facility and member attributes
* @return map of member objects and his list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if methods checkMemberIsFromTheSameVoLikeResource finds that user is not from same vo like resource
*/
HashMap<Member, List<Attribute>> getRequiredAttributes(PerunSession sess, Service service, Facility facility, Resource resource, List<Member> members, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get member-resource attributes which are required by service for each member in list of members.
* !!! Method checks if members list is not empty (returns empty HashMap)!!!
*
* @param sess perun session
* @param service attribute required by this service
* @param resource you get attributes for this resource and the members
* @param members you get attributes for this list of members and the resource
* @return map of member objects and his list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
HashMap<Member, List<Attribute>> getRequiredAttributes(PerunSession sess, Service service, Resource resource, List<Member> members) throws InternalErrorException;
/**
* Get member attributes which are required by service for each member in list of members.
* !!! Method checks if members list is not empty (returns empty HashMap)!!!
*
* @param sess perun session
* @param service attribute required by this service
* @param resource resource only to get allowed members
* @param members you get attributes for this list of members
* @return map of member objects and his list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
HashMap<Member, List<Attribute>> getRequiredAttributes(PerunSession sess, Resource resource, Service service, List<Member> members) throws InternalErrorException;
/**
* Get user-facility attributes which are required by the service for each user in list of users.
* !!! Method checks if members list is not empty (returns empty HashMap)!!!
*
* @param sess perun session
* @param service attribute required by this service
* @param facility you get attributes for this facility and user
* @param users you get attributes for this user and facility
* @return map of user and his list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
HashMap<User, List<Attribute>> getRequiredAttributes(PerunSession sess, Service service, Facility facility, List<User> users) throws InternalErrorException;
/**
* Get user attributes which are required by the service for each user in list of users.
* !!! Method checks if members list is not empty (returns empty HashMap)!!!
*
* @param sess perun session
* @param service attribute required by this service
* @param users you get attributes for this user and facility
* @return map of user and his list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
HashMap<User, List<Attribute>> getRequiredAttributes(PerunSession sess, Service service, List<User> users) throws InternalErrorException;
/**
* Get member-group attributes which are required by the service.
*
* @param sess perun session
* @param member you get attributes for this member and the group
* @param group you get attributes for this group in which member is associated
* @param service attribute required by this service you'll get
* @return list of attributes which are required by the service.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Member member, Group group) throws InternalErrorException, WrongAttributeAssignmentException;
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Member member, Group group, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get memner, user, member-resource, user-facility attributes which are required by the service.
*
*
* @param sess
* @param service
* @param facility
* @param resource
* @param user
* @param member
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Facility facility, Resource resource, User user, Member member) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Get group-resource attributes which are required by the service.
*
* @param sess perun session
* @param resource
* @param group
* @param service attribute required by this service you'll get
* @param withGroupAttributes get also group attributes (which is required by the service) for this group
* @return list of attributes which are required by the service.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Resource resource, Group group, boolean withGroupAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Resource resource, Group group) throws InternalErrorException, WrongAttributeAssignmentException;
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Group group) throws InternalErrorException;
/**
* Get host attributes which are required by service
* @param sess
* @param service
* @param host
* @return
* @throws InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Host host) throws InternalErrorException;
/**
* Get member attributes which are required by the service.
*
* @param sess perun session
* @param member you get attributes for this member
* @param service attribute required by this service you'll get
* @return list of attributes which are required by the service.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Member member) throws InternalErrorException;
/**
* Get user attributes which are required by the service.
*
* @param sess perun session
* @param user you get attributes for this user
* @param service attribute required by this service you'll get
* @return list of attributes which are required by the service.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, User user) throws InternalErrorException;
/**
* Get user-facility attributes which are required by the service.
*
* @param sess perun session
* @param user you get attributes for this user and the facility
* @param facility you get attributes for this facility and the user
* @param service attribute required by this service you'll get
* @return list of attributes which are required by the service.
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
List<Attribute> getRequiredAttributes(PerunSession sess, Service service, Facility facility, User user) throws InternalErrorException;
/**
* This method try to fill a value of the resource attribute. Value may be copied from some facility attribute.
*
* @param sess perun session
* @param resource resource, attribute of which you want to fill
* @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it.
* @return attribute which MAY have filled value
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @see cz.metacentrum.perun.core.api.AttributesManager#fillAttribute(PerunSession,Resource,Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, Resource resource, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* This method try to fill value of the member-resource attribute. This value is automatically generated, but not all attributes can be filled this way.
*
* @param sess perun session
* @param resource attribute of this resource (and member) and you want to fill
* @param member attribute of this member (and resource) and you want to fill
* @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it.
* @return attribute which MAY have filled value
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, Resource resource, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @throws WrongAttributeValueException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#fillAttribute(PerunSession,Resource,Member,Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, Resource resource, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* @param workWithUserAttributes method can process also user and user-facility attributes (user is automatically get from member a facility is get from resource)
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/
List<Attribute> fillAttributes(PerunSession sess, Resource resource, Member member, List<Attribute> attributes, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* This method tries to fill value of the member-group attribute. This value is automatically generated, but not all attributes can be filled this way.
*
* @param sess perun session
* @param member attribute of this member (and group) you want to fill
* @param group attribute of this group (and member) you want to fill
* @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it.
* @return attribute which MAY have filled value
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, Member member, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @throws WrongAttributeAssignmentException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#fillAttribute(PerunSession,Member,Group,Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, Member member, Group group, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* @param workWithUserAttributes method can process also user and memebr attributes (user is automatically get from member)
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/
List<Attribute> fillAttributes(PerunSession sess, Member member, Group group, List<Attribute> attributes, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
*
* This method try to fill value of the user, member, member-resource and user-facility attributes. This value is automatically generated, but not all attributes can be filled this way.
* This method skips all attributes with not-null value.
*
* @param sess
* @param facility
* @param resource
* @param user
* @param member
* @param attributes
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<Attribute> fillAttributes(PerunSession sess, Facility facility, Resource resource, User user, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
*
* This method try to fill value of the user, member, member-resource and user-facility attributes. This value is automatically generated, but not all attributes can be filled this way.
* This method skips all attributes with not-null value.
*
* if returnOnlyAttributesWithChangedValue is true - return only attributes which changed value by filling new one
* If false, has the same functionality like fillAttributes(PerunSession sess, Facility facility, Resource resource, User user, Member member, List<Attribute> attributes)
*
* @param sess
* @param facility
* @param resource
* @param user
* @param member
* @param attributes
* @param returnOnlyAttributesWithChangedValue
* @return
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
public List<Attribute> fillAttributes(PerunSession sess, Facility facility, Resource resource, User user, Member member, List<Attribute> attributes, boolean returnOnlyAttributesWithChangedValue) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* This method try to fill value of the member attribute. This value is automatically generated, but not all attributes can be filled this way.
*
* @param sess perun session
* @param member attribute of this member (and resource) and you want to fill
* @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it.
* @return attribute which MAY have filled value
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @throws WrongAttributeValueException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#fillAttribute(PerunSession,Resource,Member,Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* This method try to fill value of the user-facility attribute. This value is automatically generated, but not all attributes can be filled this way.
*
* @param sess perun session
* @param facility attribute of this facility (and user) and you want to fill
* @param user attribute of this user (and facility) and you want to fill
* @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it.
* @return attribute which MAY have filled value
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, Facility facility, User user, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @throws WrongAttributeValueException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#fillAttribute(PerunSession,Facility,User,Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, Facility facility, User user, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* This method try to fill value of the user attribute. This value is automatically generated, but not all attributes can be filled this way.
*
* @param sess perun session
* @param user attribute of this user (and facility) and you want to fill
* @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it.
* @return attribute which MAY have filled value
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @throws WrongAttributeValueException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#fillAttribute(PerunSession,User,Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, User user, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* This method tries to fill value of the host attribute. This value is automatically generated, but not all attributes can be filled this way
* @param sess
* @param host
* @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it.
* @return attribute which may have filled value
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, Host host, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
Attribute fillAttribute(PerunSession sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
List<Attribute> fillAttributes(PerunSession sess, Group group, List<Attribute> groupReqAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @see cz.metacentrum.perun.core.api.AttributesManager#fillAttribute(PerunSession,Host,Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, Host host, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* This method tries to fill value of group-resource attribute. This value is automatically generated, but not all attributes can be filled this way
* @param sess
* @param resource
* @param group
* @param attribute
* @return attribute which may have filled value
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @see cz.metacentrum.perun.core.api.AttributesManager#fillAttribute(cz.metacentrum.perun.core.api.PerunSession, cz.metacentrum.perun.core.api.Resource, cz.metacentrum.perun.core.api.Group, cz.metacentrum.perun.core.api.Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, Resource resource, Group group, List<Attribute> attribute) throws InternalErrorException, WrongAttributeAssignmentException;
List<Attribute> fillAttributes(PerunSession sess, Resource resource, Group group, List<Attribute> attribute, boolean workWithGroupAttributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* This method tries to fill value of the user external source attribute. This value is automatically generated, but not all attributes can be filled this way
* @param sess
* @param ues
* @param attribute attribute to fill. If attributes already have set value, this value won't be overwritten. This means the attribute value must be empty otherwise this method won't fill it.
* @return attribute which may have filled value
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
Attribute fillAttribute(PerunSession sess, UserExtSource ues, Attribute attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Batch version of fillAttribute. This method skips all attributes with not-null value.
* @see cz.metacentrAttributesManager#fillAttribute(PerunSession, UserExtSource, Attribute)
*/
List<Attribute> fillAttributes(PerunSession sess, UserExtSource ues, List<Attribute> attributes) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Check if value of this facility attribute is valid.
*
* @param sess perun session
* @param facility facility for which you want to check validity of attribute
* @param attribute attribute to check
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't facility attribute
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Facility facility, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of checkAttributeValue
* @throws WrongAttributeValueException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Facility,Attribute)
*/
void checkAttributesValue(PerunSession sess, Facility facility, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this vo attribute is valid.
*
* @param sess perun session
* @param vo vo for which you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't vo attribute
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Vo vo, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of checkAttributeValue
* @throws WrongAttributeValueException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Vo,Attribute)
*/
void checkAttributesValue(PerunSession sess, Vo vo, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this group attribute is valid.
*
* @param sess perun session
* @param group group for which you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't group attribute
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of checkAttributeValue
* @throws WrongAttributeValueException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Group,Attribute)
*/
void checkAttributesValue(PerunSession sess, Group group, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this resource attribute is valid.
*
* @param sess perun session
* @param resource resource for which you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if attribute isn't resource attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of checkAttributeValue
* @throws WrongAttributeValueException if any of attributes values is wrong/illegal
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Resource,Attribute)
*/
void checkAttributesValue(PerunSession sess, Resource resource, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this member-resource attribute is valid.
*
*
* @param sess perun session
* @param resource resource for which (and for specified member) you want to check validity of attribute
* @param member member for which (and for specified resource) you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if attribute isn't member-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Resource resource, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of fillAttribute
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Resource,Member,Attribute)
*/
void checkAttributesValue(PerunSession sess, Resource resource, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of fillAttribute
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Resource,Member,Attribute)
* @param workWithUserAttributes method can process also user and user-facility attributes (user is automatically get from member a facility is get from resource)
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/
void checkAttributesValue(PerunSession sess, Resource resource, Member member, List<Attribute> attributes, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this member-group attribute is valid.
*
* @param sess perun session
* @param group group for which (and for specified member) you want to check validity of attribute
* @param member member for which (and for specified group) you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if attribute isn't member-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Member member, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of fillAttribute
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Member,Group,Attribute)
*/
void checkAttributesValue(PerunSession sess, Member member, Group group, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of fillAttribute
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Member,Group,Attribute)
* @param workWithUserAttributes method can process also user and member attributes (user is automatically get from member)
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/
void checkAttributesValue(PerunSession sess, Member member, Group group, List<Attribute> attributes, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of attributes is valied. Attributes can be from namespace: member, user, member-resource and user-facility.
*
* @param sess
* @param facility
* @param resource
* @param user
* @param member
* @param attributes
*
* @throws InternalErrorException
* @throws WrongAttributeValueException
* @throws WrongAttributeAssignmentException
* @throws WrongReferenceAttributeValueException
*/
void checkAttributesValue(PerunSession sess, Facility facility, Resource resource, User user, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this member attribute is valid.
*
*
* @param sess perun session
* @param member member for which (and for specified resource) you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if attribute isn't member-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Member member, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of fillAttribute
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Resource,Member,Attribute)
*/
void checkAttributesValue(PerunSession sess, Member member, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this user-facility attribute is valid.
*
*
* @param sess perun session
* @param facility facility for which (and for specified user) you want to check validity of attribute
* @param user user for which (and for specified facility) you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if attribute isn't user-facility attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Facility facility, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of checkAttributeValue
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Facility,User,Attribute)
*/
void checkAttributesValue(PerunSession sess, Facility facility, User user, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this group-resource attribute is valid
* @param sess perun session
* @param resource
* @param group
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't group-resource attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException,WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* batch version of checkAttributeValue
*@see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(cz.metacentrum.perun.core.api.PerunSession, cz.metacentrum.perun.core.api.Resource, cz.metacentrum.perun.core.api.Group, cz.metacentrum.perun.core.api.Attribute)
*/
void checkAttributesValue(PerunSession sess, Resource resource, Group group, List<Attribute> attribute) throws InternalErrorException,WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
void checkAttributesValue(PerunSession sess, Resource resource, Group group, List<Attribute> attribute, boolean workWithGroupAttribute) throws InternalErrorException,WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Check if value of this user attribute is valid.
*
*
* @param sess perun session
* @param user user for which (and for specified facility) you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if attribute isn't user-facility attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of checkAttributeValue
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,User,Attribute)
*/
void checkAttributesValue(PerunSession sess, User user, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if the value of this host attribute is valid
* @param sess perun session
* @param host host which attribute validity is checked
* @param attribute attribute to check
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if the attribute isn't host attribute
*/
void checkAttributeValue(PerunSession sess, Host host, Attribute attribute) throws InternalErrorException,WrongAttributeValueException,WrongAttributeAssignmentException;
/**
* Batch version of checkAttributeValue
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,Host,Attribute)
*/
void checkAttributesValue(PerunSession sess, Host host, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException,WrongAttributeAssignmentException;
/**
* Check if the value of this entityless attribute is valid
* @param sess perun session
* @param key check the attribute for this key
* @param attribute attribute to check
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if the attribute isn't entityless attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, String key, Attribute attribute) throws InternalErrorException,WrongAttributeValueException,WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this user ext source attribute is valid.
* @param sess perun session
* @param ues user external source for which you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if attribute isn't user external source attribute
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeValue(PerunSession sess, UserExtSource ues, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Batch version of checkAttributeValue
* @see cz.metacentrum.perun.core.api.AttributesManager#checkAttributeValue(PerunSession,UserExtSource,Attribute)
*/
void checkAttributesValue(PerunSession sess, UserExtSource ues, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this group attribute is valid no matter if attribute is required or not.
*
* @param sess perun session
* @param group group for which you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't group attribute
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongReferenceAttributeValueException
*/
void forceCheckAttributeValue(PerunSession sess, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Check if value of this resource attribute is valid no matter if attribute is required or not.
*
* @param sess perun session
* @param resource resource for which you want to check validity of attribute
* @param attribute attribute to check
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongAttributeAssignmentException if attribute isn't resource attribute
* @throws WrongReferenceAttributeValueException
*/
void forceCheckAttributeValue(PerunSession sess, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the facility. Core attributes can't be removed this way.
*
* @param sess perun session
* @param facility remove attribute from this facility
* @param attribute attribute to remove
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't facility attribute or if it is core attribute
*/
void removeAttribute(PerunSession sess, Facility facility, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular entityless attribute with subject equals key.
*
* @param sess perun session
* @param key subject of entityless attribute
* @param attribute attribute to remove
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is wrong/illegal
* @throws WrongReferenceAttributeValueException if the attribute isn't entityless attribute
* @throws WrongAttributeAssignmentException
*/
void removeAttribute(PerunSession sess, String key, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Unset the group_resource attributes. If an attribute is core attribute, then the attribute isn't unseted (it's skipped without notification).
* If workWithGroupAttributes is true, unset also group attributes.
*
* Remove only attributes which are in list of attributes.
*
* PRIVILEGE: Remove attributes only when principal has access to write on them.
*
* @param sess perun session
* @param group group to set on
* @param resource resource to set on
* @param attributes attributes which will be used to removing
* @param workWithGroupAttributes if true, remove also group attributes, if false, remove only group_resource attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws AttributeNotExistsException if the attribute doesn't exists in the underlaying data source
* @throws WrongAttributeAssignmentException if attribute is not group-resource or group attribute
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongReferenceAttributeValueException if some reference attribute has illegal value
*/
void removeAttributes(PerunSession sess, Resource resource, Group group, List<? extends AttributeDefinition> attributes, boolean workWithGroupAttributes) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the group and resource.
* If workWithGroupAttributes is true, remove also all group attributes.
*
* PRIVILEGE: Remove attributes only when principal has access to write on them.
*
* @param sess perun session
* @param group group to set on
* @param resource resource to set on
* @param workWithGroupAttributes if true, remove also group attributes, if false, remove only group_resource attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongReferenceAttributeValueException if some reference attribute has illegal value
* @throws WrongAttributeAssignmentException if attribute is not group-resource or group attribute
*/
void removeAllAttributes(PerunSession sess, Resource resource, Group group, boolean workWithGroupAttributes) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession,Facility,AttributeDefinition)
*/
void removeAttributes(PerunSession sess, Facility facility, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all <b>non-empty</b> attributes associated with the member and if workWithUserAttributes is
* true, unset all <b>non-empty</b> attributes associated with user, who is this member.
*
* @param sess perun session
* @param member remove attribute from this member
* @param workWithUserAttributes true if I want to unset all attributes associated with user, who is the member too
* @param attributes attribute to remove
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException if attribute isn't member attribute or if it is core attribute
*/
void removeAttributes(PerunSession sess, Member member, boolean workWithUserAttributes, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset the member, user, member-resource and user-facility attributes. If an attribute is core attribute then the attribute isn't unseted (It's skipped without any notification).
*
* @param sess perun session
* @param facility
* @param resource resource to set on
* @param user
* @param member member to set on
* @param attributes
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member-resource, user, member or user-facility attribute
* @throws WrongReferenceAttributeValueException
*/
void removeAttributes(PerunSession sess, Facility facility, Resource resource, User user, Member member, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the facility.
*
* @param sess perun session
* @param facility remove attributes from this facility
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Facility facility) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the facility.
* If removeAlsoUserFacilityAttributes is true, remove all user-facility attributes of this facility and any user allowed in this facility.
*
* @param sess perun session
* @param facility remove attributes from this facility
* @param removeAlsoUserFacilityAttributes if true, remove all user-facility attributes for any user in this facility too
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeValueException
*/
void removeAllAttributes(PerunSession sess, Facility facility, boolean removeAlsoUserFacilityAttributes) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the vo. Core attributes can't be removed this way.
*
* @param sess perun session
* @param vo remove attribute from this vo
* @param attribute attribute to remove
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't vo attribute or if it is core attribute
*/
void removeAttribute(PerunSession sess, Vo vo, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, Vo vo, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, Vo vo, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Store the attributes associated with member and user (which we get from this member) if workWithUserAttributes is true.
* If an attribute is core attribute then the attribute isn't stored (It's skipped without any notification).
*
* @param sess perun session
* @param member member to set on
* @param attributes attribute to set
* @param workWithUserAttributes true/false If true, we can use user attributes (get from this member) too
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeValueException if the attribute value is illegal
* @throws WrongAttributeAssignmentException if attribute is not member attribute or with workWithUserAttributes=true, if its not member or user attribute.
* @throws WrongReferenceAttributeValueException
*/
void setAttributes(PerunSession sess, Member member, List<Attribute> attributes, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the vo.
*
* @param sess perun session
* @param vo remove attributes from this vo
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Vo vo) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the group. Core attributes can't be removed this way.
*
* @param sess perun session
* @param group remove attribute from this group
* @param attribute attribute to remove
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't group attribute or if it is core attribute
*/
void removeAttribute(PerunSession sess, Group group, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, Group group, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, Group group, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the group.
*
* @param sess perun session
* @param group remove attributes from this group
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Group group) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the resource. Core attributes can't be removed this way.
*
* @param sess perun session
* @param resource remove attribute from this resource
* @param attribute attribute to remove
*
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't resource attribute or if it is core attribute
*/
boolean removeAttribute(PerunSession sess, Resource resource, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, Resource resource, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, Resource resource, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the resource.
*
* @param sess perun session
* @param resource remove attributes from this resource
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Resource resource) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the member on the resource. Core attributes can't be removed this way.
*
* @param sess perun session
* @param member remove attribute from this member
* @param resource remove attributes for this resource
* @param attribute attribute to remove
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't member-resource attribute or if it is core attribute
*/
void removeAttribute(PerunSession sess, Resource resource, Member member, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
*/
void removeAttributes(PerunSession sess, Resource resource, Member member, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the member on the resource.
*
* @param sess perun session
* @param member remove attributes from this member
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Resource resource, Member member) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException;
/**
* Unset particular attribute for the member in the group. Core attributes can't be removed this way.
*
* @param sess perun session
* @param group remove attributes for this group
* @param member remove attribute from this member
* @param attribute attribute to remove
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeValueException
* @throws WrongAttributeAssignmentException if attribute isn't member-resource attribute or if it is core attribute
*/
void removeAttribute(PerunSession sess, Member member, Group group, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @throws AttributeNotExistsException if the any of attributes doesn't exists in underlying data source
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession, Member, Group, AttributeDefinition)
*/
void removeAttributes(PerunSession sess, Member member, Group group, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
void removeAttributes(PerunSession sess, Member member, Group group, List<? extends AttributeDefinition> attributes, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the member in the group.
*
* @param sess perun session
* @param group remove attributes for this group
* @param member remove attributes from this member
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeValueException
* @throws WrongAttributeAssignmentException
*/
void removeAllAttributes(PerunSession sess, Member member, Group group) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the member. Core attributes can't be removed this way.
*
* @param sess perun session
* @param member remove attribute from this member
* @param attribute attribute to remove
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't member-resource attribute or if it is core attribute
*/
void removeAttribute(PerunSession sess, Member member, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, Resource resource, Member member, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, Member member, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the member.
*
* @param sess perun session
* @param member remove attributes from this member
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Member member) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the user on the facility. Core attributes can't be removed this way.
*
* @param sess perun session
* @param user remove attribute from this user
* @param facility remove attributes for this facility
* @param attribute attribute to remove
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't user-facility attribute or if it is core attribute
*/
void removeAttribute(PerunSession sess, Facility facility, User user, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, Facility facility, User user, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, Facility facility, User user, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes (user-facility) for the user on the facility.
*
* @param sess perun session
* @param facility
* @param user
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Facility facility, User user) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all <b>non-virtual</b> user-facility attributes for the user and <b>all facilities</b>
*
* @param sess perun session
* @param user
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeValueException
*/
void removeAllUserFacilityAttributes(PerunSession sess, User user) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the user. Core attributes can't be removed this way.
*
* @param sess perun session
* @param user remove attribute from this user
* @param attribute attribute to remove
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't user-facility attribute or if it is core attribute
*/
void removeAttribute(PerunSession sess, User user, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, Facility facility, User user, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, User user, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the user.
*
* @param sess perun session
* @param user remove attributes from this user
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, User user) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular attribute for the host. Core attributes can't be removed this way.
* @param sess
* @param host
* @param attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is not host attribute
*/
void removeAttribute(PerunSession sess, Host host, AttributeDefinition attribute) throws InternalErrorException,WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute. This method automatically skip all core attributes which can't be removed this way.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, Host host, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, Host host, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the host.
*
* @param sess perun session
* @param host remove attributes from this host
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Host host) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset particular group-resource attribute
* @param sess
* @param resource
* @param group
* @param attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException
*/
void removeAttribute(PerunSession sess, Resource resource, Group group, AttributeDefinition attribute) throws InternalErrorException,WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, Resource resource, Group group, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, Resource resource, Group group, List<? extends AttributeDefinition> attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all group-resource attributes
* @param sess
* @param resource
* @param group
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, Resource resource, Group group) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException;
/**
* Unset particular attribute for the user external source.
*
* @param sess perun session
* @param ues remove attribute from this user external source
* @param attribute attribute to remove
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws WrongAttributeAssignmentException if attribute isn't user external source attribute
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
void removeAttribute(PerunSession sess, UserExtSource ues, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Batch version of removeAttribute.
* @see cz.metacentrum.perun.core.api.AttributesManager#removeAttribute(PerunSession sess, UserExtSource ues, AttributeDefinition attribute)
*/
void removeAttributes(PerunSession sess, UserExtSource ues, List<? extends AttributeDefinition> attributes) throws InternalErrorException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the user external source.
*
* @param sess perun session
* @param ues remove attributes from this user external source
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
void removeAllAttributes(PerunSession sess, UserExtSource ues) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Unset all attributes for the key (entityless) without check of value.
*
* @param sess
* @param key
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't entityless attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, String key, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the facility without check of value.
*
* @param sess
* @param facility
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't facility attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Facility facility, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the host without check of value.
*
* @param sess
* @param host
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't host attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Host host, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the vo without check of value.
*
* @param sess
* @param vo
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't vo attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Vo vo, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the group without check of value.
*
* @param sess
* @param group
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't group attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Group group, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the resource without check of value.
*
* @param sess
* @param resource
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't resource attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Resource resource, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the member-resource without check of value.
*
* @param sess
* @param resource
* @param member
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't member-resource attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Resource resource, Member member, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the member-group without check of value.
*
* @param sess
* @param member
* @param group
* @param attribute
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Member member, Group group, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the member without check of value.
*
* @param sess
* @param member
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't member attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Member member, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the user-facility without check of value.
*
* @param sess
* @param facility
* @param user
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't user-facility attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Facility facility, User user, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the user without check of value.
*
* @param sess
* @param user
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't user attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, User user, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Unset all attributes for the group-resource without check of value.
*
* @param sess
* @param resource
* @param group
* @param attribute
* @return {@code true} if attribute was changed (deleted) or {@code false} if attribute was not present in a first place
* @throws WrongAttributeAssignmentException if attribute isn't group-resource attribute or if it is core attribute
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
*/
boolean removeAttributeWithoutCheck(PerunSession sess, Resource resource, Group group, AttributeDefinition attribute) throws InternalErrorException, WrongAttributeAssignmentException;
void checkAttributeExists(PerunSession sess, AttributeDefinition attribute) throws InternalErrorException, AttributeNotExistsException;
void checkAttributesExists(PerunSession sess, List<? extends AttributeDefinition> attributes) throws InternalErrorException, AttributeNotExistsException;
/**
* Determine if attribute is core attribute.
*
* @param sess
* @param attribute
* @return true if attribute is core attribute
*/
boolean isCoreAttribute(PerunSession sess, AttributeDefinition attribute);
/**
* Determine if attribute is defined (def) attribute.
*
* @param sess
* @param attribute
* @return true if attribute is defined attribute
* false otherwise
*/
boolean isDefAttribute(PerunSession sess, AttributeDefinition attribute);
/**
* Determine if attribute is optional (opt) attribute.
*
* @param sess
* @param attribute
* @return true if attribute is optional attribute
* false otherwise
*/
boolean isOptAttribute(PerunSession sess, AttributeDefinition attribute);
/**
* Determine if attribute is virtual (virt) attribute.
*
* @param sess
* @param attribute
* @return true if attribute is virtual attribute
* false otherwise
*/
boolean isVirtAttribute(PerunSession sess, AttributeDefinition attribute);
/**
* Determine if attribute is core-managed attribute.
*
* @param sess
* @param attribute
* @return true if attribute is core-managed
*/
boolean isCoreManagedAttribute(PerunSession sess, AttributeDefinition attribute);
/**
* Determine if attribute is from specified namespace.
*
* @param sess
* @param attribute
* @param namespace
* @return true if the attribute is from specified namespace false otherwise
*/
boolean isFromNamespace(PerunSession sess, AttributeDefinition attribute, String namespace);
/**
* Determine if attribute is from specified namespace.
*
* @param sess
* @param attribute
* @param namespace
*
* @throws WrongAttributeAssignmentException if the attribute isn't from specified namespace
*/
void checkNamespace(PerunSession sess, AttributeDefinition attribute, String namespace) throws WrongAttributeAssignmentException;
/**
* Determine if attributes are from specified namespace.
*
* @param sess
* @param attributes
* @param namespace
*
* @throws WrongAttributeAssignmentException if any of the attribute isn't from specified namespace
*/
void checkNamespace(PerunSession sess, List<? extends AttributeDefinition> attributes, String namespace) throws WrongAttributeAssignmentException;
/**
* Gets the namespace from the attribute name.
*
* @param attributeName
* @return the namespace from the attribute name
*/
String getNamespaceFromAttributeName(String attributeName);
/**
* Gets the friendly name from the attribute name.
*
* @param attributeName
* @return the friendly name from the attribute name
*/
String getFriendlyNameFromAttributeName(String attributeName);
/**
* Get all <b>non-empty</b> attributes with user's logins.
*
* @param sess
* @param user
* @return list of attributes with login
*
* @throws InternalErrorException
*/
List<Attribute> getLogins(PerunSession sess, User user) throws InternalErrorException;
/**
* Get all values for specified attribute. Attribute can't be core, core-managed or virt.
*
* @param sess
* @param attributeDefinition
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException if attribute is core, core-managed or virt
*/
List<Object> getAllValues(PerunSession sess, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Check if this the attribute is truly required for the facility right now. Truly means that the nothing (member, resource...) is invalid.
*
* @param sess
* @param facility
* @param attributeDefinition
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
boolean isTrulyRequiredAttribute(PerunSession sess, Facility facility, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Check if this the attribute is truly required for the resource right now. Truly means that the nothing (member, resource...) is invalid.
*
* @param sess
* @param resource
* @param attributeDefinition
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
boolean isTrulyRequiredAttribute(PerunSession sess, Resource resource, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
*
* Check if this the attribute is truly required for the member right now. Truly means that the nothing (member, resource...) is invalid.
*
* @param sess
* @param member
* @param attributeDefinition
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
boolean isTrulyRequiredAttribute(PerunSession sess, Member member, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Check if this the attribute is truly required for the user right now. Truly means that the nothing (member, resource...) is invalid.
*
* @param sess
* @param user
* @param attributeDefinition
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
boolean isTrulyRequiredAttribute(PerunSession sess, User user, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Check if this the attribute is truly required for the user and the facility right now. Truly means that the nothing (member, resource...) is invalid.
*
* @param sess
* @param facility
* @param user
* @param attributeDefinition
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
boolean isTrulyRequiredAttribute(PerunSession sess, Facility facility, User user, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Check if this the attribute is truly required for the member and the resource right now. Truly means that the nothing (member, resource...) is invalid.
*
* @param sess
* @param resource
* @param member
* @param attributeDefinition
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
boolean isTrulyRequiredAttribute(PerunSession sess, Resource resource, Member member, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Check if this the attribute is truly required for the member and the group right now. Truly means that the nothing (member, group...) is invalid.
*
* @param sess
* @param member
* @param group
* @param attributeDefinition
* @return
*
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
boolean isTrulyRequiredAttribute(PerunSession sess, Member member, Group group, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException;
/**
* Same as doTheMagic(sess, member, false);
*/
void doTheMagic(PerunSession sess, Member member) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException;
/**
* This function takes all member-related attributes (member, user, member-resource, user-facility) and tries to fill them and set them.
* If trueMagic is set, this method can remove invalid attribute value (value which didn't pass checkAttributeValue test) and try to fill and set another. In this case, WrongReferenceAttributeValueException, WrongAttributeValueException are thrown if same attribute can't be set corraclty.
*
* @param sess
* @param member
* @param trueMagic
*
* @throws InternalErrorException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeAssignmentException
*/
void doTheMagic(PerunSession sess, Member member, boolean trueMagic) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException;
/**
* Converts string into the Object defined by type.
*
* @param value
* @param type
* @throws InternalErrorException
* @return
*/
public Object stringToAttributeValue(String value, String type) throws InternalErrorException;
/**
* Merges attribute value if the attribute type is list or map. In other cases it only stores new value.
* If the type is list, new values are added to the current stored list.
* It the type is map, new values are added and existing are overwritten with new values, but only if there is some change.
*
* @param sess
* @param user
* @param attribute
* @return attribute with updated value
* @throws InternalErrorException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeAssignmentException
*/
public Attribute mergeAttributeValue(PerunSession sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException,
WrongReferenceAttributeValueException, WrongAttributeAssignmentException;
/**
* Merges attribute value if the attribute type is list or map. In other cases it only stores new value.
* If the type is list, new values are added to the current stored list.
* It the type is map, new values are added and existing are overwritten with new values, but only if there is some change.
*
* This method creates nested transaction to prevent storing value to DB if it throws any exception.
*
* @param sess
* @param user
* @param attribute
* @return attribute with updated value
* @throws InternalErrorException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeAssignmentException
*/
public Attribute mergeAttributeValueInNestedTransaction(PerunSession sess, User user, Attribute attribute) throws InternalErrorException, WrongAttributeValueException,
WrongReferenceAttributeValueException, WrongAttributeAssignmentException;
/**
* Merges attributes values if the attribute type is list or map. In other cases it only stores new value.
* If the type is list, new values are added to the current stored list.
* It the type is map, new values are added and existing are overwritten with new values, but only if there is some change.
*
* @param sess
* @param user
* @param attributes
* @throws InternalErrorException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
* @throws WrongAttributeAssignmentException
*/
public void mergeAttributesValues(PerunSession sess, User user, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException,
WrongReferenceAttributeValueException, WrongAttributeAssignmentException;
/**
* This method checkValue on all possible dependent attributes for richAttr.
* RichAttribute is needed for useful objects which are in holders.
*
* @param sess
* @param richAttr
* @throws InternalErrorException
* @throws WrongAttributeValueException
* @throws WrongAttributeAssignmentException
* @throws WrongReferenceAttributeValueException
*/
void checkAttributeDependencies(PerunSession sess, RichAttribute richAttr) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
/**
* @return get map of all Dependencies
*/
Map<AttributeDefinition, Set<AttributeDefinition>> getAllDependencies();
/**
* Method get attribute Definition attrDef and aidingAttr which only holds one or two useful objects in holders.
* Thanks useful objects, method find all possibly richAttributes which can be get on specific attrDef with all
* existing combinations of needed objects.
*
* Example: I am looking for Member attrDef and I have primaryHolder: User.
* So i will find all members of this user and return all richAttributes of combination attribute + specific member in primaryHolder.
*
* @param sess
* @param attrDef
* @param aidingAttr
* @return
* @throws InternalErrorException
* @throws AttributeNotExistsException
* @throws VoNotExistsException
* @throws WrongAttributeAssignmentException
* @throws WrongAttributeValueException
* @throws WrongReferenceAttributeValueException
*/
List<RichAttribute> getRichAttributesWithHoldersForAttributeDefinition(PerunSession sess, AttributeDefinition attrDef, RichAttribute aidingAttr) throws InternalErrorException, AttributeNotExistsException, VoNotExistsException, WrongAttributeAssignmentException, WrongAttributeValueException, WrongReferenceAttributeValueException;
/**
* Get All user_facility attributes for any existing user
*
* @param sess
* @param facility
* @return list of user facility attributes
* @throws InternalErrorException
*/
List<Attribute> getUserFacilityAttributesForAnyUser(PerunSession sess, Facility facility) throws InternalErrorException;
/**
* Updates AttributeDefinition.
*
* @param perunSession
* @param attributeDefinition
* @return returns updated attributeDefinition
* @throws InternalErrorException
*/
AttributeDefinition updateAttributeDefinition(PerunSession perunSession, AttributeDefinition attributeDefinition) throws InternalErrorException;
/**
* Check if actionType exists in underlaying data source.
*
* @param sess perun session
* @param actionType actionType to check
* @throws InternalErrorException if unexpected error occure
* @throws ActionTypeNotExistsException if attribute doesn't exists
*/
void checkActionTypeExists(PerunSession sess, ActionType actionType) throws InternalErrorException, ActionTypeNotExistsException;
/**
* Set all Attributes in list to "writable = true".
*
* @param sess
* @param attributes
* @return list of attributes
* @throws InternalErrorException
*/
List<Attribute> setWritableTrue(PerunSession sess, List<Attribute> attributes) throws InternalErrorException;
/**
* Gets attribute rights of an attribute with id given as a parameter.
* If the attribute has no rights for a role, it returns empty list. That means the returned list has always 4 items
* for each of the roles VOADMIN, FACILITYADMIN, GROUPADMIN, SELF.
* Info: not return rights for role VoObserver (could be same like read rights for VoAdmin)
*
* @param sess perun session
* @param attributeId id of the attribute
* @return all rights of the attribute
* @throws InternalErrorException
*/
List<AttributeRights> getAttributeRights(PerunSession sess, int attributeId) throws InternalErrorException;
/**
* Sets all attribute rights in the list given as a parameter.
* The method sets the rights for attribute and role exactly as it is given in the list of action types. That means it can
* remove a right, if the right is missing in the list.
* Info: If there is role VoAdmin in the list, use it for setting also VoObserver rights (only for read) automatic
*
* @param sess perun session
* @param rights list of attribute rights
* @throws InternalErrorException
*/
void setAttributeRights(PerunSession sess, List<AttributeRights> rights) throws InternalErrorException;
/**
* Get user virtual attribute module by the attribute.
*
* @param sess
* @param attribute attribute for which you get the module
* @return instance of user attribute module
*
* @throws InternalErrorException
* @throws WrongModuleTypeException
* @throws ModuleNotExistsException
*/
public UserVirtualAttributesModuleImplApi getUserVirtualAttributeModule(PerunSession sess, AttributeDefinition attribute) throws ModuleNotExistsException, WrongModuleTypeException, InternalErrorException;
/**
* Method returns attribute with null value if attribute has empty string;
*
* @param attributeToConvert
* @return Attribute with original value or null value for empty string
*/
Attribute convertEmptyStringIntoNullInAttrValue(Attribute attributeToConvert);
/**
* Method returns attribute with null value if attribute value is boolean == false
*
* @param attributeToConvert
* @return Attribute with original value or null value for boolean == false
*/
Attribute convertBooleanFalseIntoNullInAttrValue(Attribute attributeToConvert);
}
| jirmauritz/perun | perun-core/src/main/java/cz/metacentrum/perun/core/bl/AttributesManagerBl.java | Java | bsd-2-clause | 193,360 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+react_native
*/
'use strict';
jest.setMock('NativeModules', {
BlobModule: require('../__mocks__/BlobModule'),
});
var Blob = require('Blob');
describe('Blob', function() {
it('should create empty blob', () => {
const blob = new Blob();
expect(blob).toBeInstanceOf(Blob);
expect(blob.data.offset).toBe(0);
expect(blob.data.size).toBe(0);
expect(blob.size).toBe(0);
expect(blob.type).toBe('');
});
it('should create blob from other blobs and strings', () => {
const blobA = new Blob();
const blobB = new Blob();
const textA = 'i \u2665 dogs';
const textB = '\uD800\uDC00';
const textC =
'Z\u0351\u036B\u0343\u036A\u0302\u036B\u033D\u034F\u0334\u0319\u0324' +
'\u031E\u0349\u035A\u032F\u031E\u0320\u034DA\u036B\u0357\u0334\u0362' +
'\u0335\u031C\u0330\u0354L\u0368\u0367\u0369\u0358\u0320G\u0311\u0357' +
'\u030E\u0305\u035B\u0341\u0334\u033B\u0348\u034D\u0354\u0339O\u0342' +
'\u030C\u030C\u0358\u0328\u0335\u0339\u033B\u031D\u0333!\u033F\u030B' +
'\u0365\u0365\u0302\u0363\u0310\u0301\u0301\u035E\u035C\u0356\u032C' +
'\u0330\u0319\u0317';
blobA.data.size = 34540;
blobB.data.size = 65452;
const blob = new Blob([blobA, blobB, textA, textB, textC]);
expect(blob.size).toBe(
blobA.size +
blobB.size +
global.Buffer.byteLength(textA, 'UTF-8') +
global.Buffer.byteLength(textB, 'UTF-8') +
global.Buffer.byteLength(textC, 'UTF-8'),
);
expect(blob.type).toBe('');
});
it('should slice a blob', () => {
const blob = new Blob();
blob.data.size = 34546;
const sliceA = blob.slice(0, 2354);
expect(sliceA.data.offset).toBe(0);
expect(sliceA.size).toBe(2354);
expect(sliceA.type).toBe('');
const sliceB = blob.slice(2384, 7621);
expect(sliceB.data.offset).toBe(2384);
expect(sliceB.size).toBe(7621 - 2384);
expect(sliceB.type).toBe('');
});
it('should close a blob', () => {
const blob = new Blob();
blob.close();
expect(() => blob.size).toThrow();
});
});
| hoastoolshop/react-native | Libraries/Blob/__tests__/Blob-test.js | JavaScript | bsd-3-clause | 2,292 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Feed_Reader
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Collection.php 24593 2012-01-05 20:35:02Z matthew $
*/
/**
* @category Zend
* @package Zend_Feed_Reader
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Feed_Reader_Collection extends ArrayObject
{
}
| Riges/KawaiViewModel | www/libs/Zend/Feed/Reader/Collection.php | PHP | bsd-3-clause | 1,076 |
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SKSL_EXPRESSIONSTATEMENT
#define SKSL_EXPRESSIONSTATEMENT
#include "SkSLExpression.h"
#include "SkSLStatement.h"
namespace SkSL {
/**
* A lone expression being used as a statement.
*/
struct ExpressionStatement : public Statement {
ExpressionStatement(std::unique_ptr<Expression> expression)
: INHERITED(expression->fOffset, kExpression_Kind)
, fExpression(std::move(expression)) {}
std::unique_ptr<Statement> clone() const override {
return std::unique_ptr<Statement>(new ExpressionStatement(fExpression->clone()));
}
String description() const override {
return fExpression->description() + ";";
}
std::unique_ptr<Expression> fExpression;
typedef Statement INHERITED;
};
} // namespace
#endif
| Hikari-no-Tenshi/android_external_skia | src/sksl/ir/SkSLExpressionStatement.h | C | bsd-3-clause | 911 |
#!/bin/sh
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
> "$RESOURCES_TO_COPY"
install_resource()
{
case $1 in
*.storyboard)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}"
;;
*.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}"
;;
*.framework)
echo "rsync -rp ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
rsync -rp "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
;;
*.xcdatamodeld)
echo "xcrun momc ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename $1 .xcdatamodeld`.momd"
xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename $1 .xcdatamodeld`.momd"
;;
*)
echo "${PODS_ROOT}/$1"
echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY"
;;
esac
}
rsync -avr --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
rm "$RESOURCES_TO_COPY"
| BeamApp/Transit | examples/objc-osx/Pods/Pods-resources.sh | Shell | bsd-3-clause | 2,016 |
;*****************************************************************************
;* x86inc.asm: x264asm abstraction layer
;*****************************************************************************
;* Copyright (C) 2005-2015 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;* Anton Mitrofanov <BugMaster@narod.ru>
;* Fiona Glaser <fiona@x264.com>
;* Henrik Gramner <henrik@gramner.com>
;*
;* 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.
;*****************************************************************************
; This is a header file for the x264ASM assembly language, which uses
; NASM/YASM syntax combined with a large number of macros to provide easy
; abstraction between different calling conventions (x86_32, win64, linux64).
; It also has various other useful features to simplify writing the kind of
; DSP functions that are most often used in x264.
; Unlike the rest of x264, this file is available under an ISC license, as it
; has significant usefulness outside of x264 and we want it to be available
; to the largest audience possible. Of course, if you modify it for your own
; purposes to add a new feature, we strongly encourage contributing a patch
; as this feature might be useful for others as well. Send patches or ideas
; to x264-devel@videolan.org .
%include "vpx_config.asm"
%ifndef private_prefix
%define private_prefix vpx
%endif
%ifndef public_prefix
%define public_prefix private_prefix
%endif
%ifndef STACK_ALIGNMENT
%if ARCH_X86_64
%define STACK_ALIGNMENT 16
%else
%define STACK_ALIGNMENT 4
%endif
%endif
%define WIN64 0
%define UNIX64 0
%if ARCH_X86_64
%ifidn __OUTPUT_FORMAT__,win32
%define WIN64 1
%elifidn __OUTPUT_FORMAT__,win64
%define WIN64 1
%elifidn __OUTPUT_FORMAT__,x64
%define WIN64 1
%else
%define UNIX64 1
%endif
%endif
%ifidn __OUTPUT_FORMAT__,elf32
%define mangle(x) x
%elifidn __OUTPUT_FORMAT__,elf64
%define mangle(x) x
%elifidn __OUTPUT_FORMAT__,x64
%define mangle(x) x
%elifidn __OUTPUT_FORMAT__,win64
%define mangle(x) x
%else
%define mangle(x) _ %+ x
%endif
; In some instances macho32 tables get misaligned when using .rodata.
; When looking at the disassembly it appears that the offset is either
; correct or consistently off by 90. Placing them in the .text section
; works around the issue. It appears to be specific to the way libvpx
; handles the tables.
%macro SECTION_RODATA 0-1 16
%ifidn __OUTPUT_FORMAT__,macho32
SECTION .text align=%1
fakegot:
%elifidn __OUTPUT_FORMAT__,aout
SECTION .text
%else
SECTION .rodata align=%1
%endif
%endmacro
%macro SECTION_TEXT 0-1 16
%ifidn __OUTPUT_FORMAT__,aout
SECTION .text
%else
SECTION .text align=%1
%endif
%endmacro
; PIC macros are copied from vpx_ports/x86_abi_support.asm. The "define PIC"
; from original code is added in for 64bit.
%ifidn __OUTPUT_FORMAT__,elf32
%define ABI_IS_32BIT 1
%elifidn __OUTPUT_FORMAT__,macho32
%define ABI_IS_32BIT 1
%elifidn __OUTPUT_FORMAT__,win32
%define ABI_IS_32BIT 1
%elifidn __OUTPUT_FORMAT__,aout
%define ABI_IS_32BIT 1
%else
%define ABI_IS_32BIT 0
%endif
%if ABI_IS_32BIT
%if CONFIG_PIC=1
%ifidn __OUTPUT_FORMAT__,elf32
%define GET_GOT_SAVE_ARG 1
%define WRT_PLT wrt ..plt
%macro GET_GOT 1
extern _GLOBAL_OFFSET_TABLE_
push %1
call %%get_got
%%sub_offset:
jmp %%exitGG
%%get_got:
mov %1, [esp]
add %1, _GLOBAL_OFFSET_TABLE_ + $$ - %%sub_offset wrt ..gotpc
ret
%%exitGG:
%undef GLOBAL
%define GLOBAL(x) x + %1 wrt ..gotoff
%undef RESTORE_GOT
%define RESTORE_GOT pop %1
%endmacro
%elifidn __OUTPUT_FORMAT__,macho32
%define GET_GOT_SAVE_ARG 1
%macro GET_GOT 1
push %1
call %%get_got
%%get_got:
pop %1
%undef GLOBAL
%define GLOBAL(x) x + %1 - %%get_got
%undef RESTORE_GOT
%define RESTORE_GOT pop %1
%endmacro
%endif
%endif
%if ARCH_X86_64 == 0
%undef PIC
%endif
%else
%macro GET_GOT 1
%endmacro
%define GLOBAL(x) rel x
%define WRT_PLT wrt ..plt
%if WIN64
%define PIC
%elifidn __OUTPUT_FORMAT__,macho64
%define PIC
%elif CONFIG_PIC
%define PIC
%endif
%endif
%ifnmacro GET_GOT
%macro GET_GOT 1
%endmacro
%define GLOBAL(x) x
%endif
%ifndef RESTORE_GOT
%define RESTORE_GOT
%endif
%ifndef WRT_PLT
%define WRT_PLT
%endif
%ifdef PIC
default rel
%endif
; Done with PIC macros
; Macros to eliminate most code duplication between x86_32 and x86_64:
; Currently this works only for leaf functions which load all their arguments
; into registers at the start, and make no other use of the stack. Luckily that
; covers most of x264's asm.
; PROLOGUE:
; %1 = number of arguments. loads them from stack if needed.
; %2 = number of registers used. pushes callee-saved regs if needed.
; %3 = number of xmm registers used. pushes callee-saved xmm regs if needed.
; %4 = (optional) stack size to be allocated. The stack will be aligned before
; allocating the specified stack size. If the required stack alignment is
; larger than the known stack alignment the stack will be manually aligned
; and an extra register will be allocated to hold the original stack
; pointer (to not invalidate r0m etc.). To prevent the use of an extra
; register as stack pointer, request a negative stack size.
; %4+/%5+ = list of names to define to registers
; PROLOGUE can also be invoked by adding the same options to cglobal
; e.g.
; cglobal foo, 2,3,7,0x40, dst, src, tmp
; declares a function (foo) that automatically loads two arguments (dst and
; src) into registers, uses one additional register (tmp) plus 7 vector
; registers (m0-m6) and allocates 0x40 bytes of stack space.
; TODO Some functions can use some args directly from the stack. If they're the
; last args then you can just not declare them, but if they're in the middle
; we need more flexible macro.
; RET:
; Pops anything that was pushed by PROLOGUE, and returns.
; REP_RET:
; Use this instead of RET if it's a branch target.
; registers:
; rN and rNq are the native-size register holding function argument N
; rNd, rNw, rNb are dword, word, and byte size
; rNh is the high 8 bits of the word size
; rNm is the original location of arg N (a register or on the stack), dword
; rNmp is native size
%macro DECLARE_REG 2-3
%define r%1q %2
%define r%1d %2d
%define r%1w %2w
%define r%1b %2b
%define r%1h %2h
%if %0 == 2
%define r%1m %2d
%define r%1mp %2
%elif ARCH_X86_64 ; memory
%define r%1m [rstk + stack_offset + %3]
%define r%1mp qword r %+ %1 %+ m
%else
%define r%1m [rstk + stack_offset + %3]
%define r%1mp dword r %+ %1 %+ m
%endif
%define r%1 %2
%endmacro
%macro DECLARE_REG_SIZE 3
%define r%1q r%1
%define e%1q r%1
%define r%1d e%1
%define e%1d e%1
%define r%1w %1
%define e%1w %1
%define r%1h %3
%define e%1h %3
%define r%1b %2
%define e%1b %2
%if ARCH_X86_64 == 0
%define r%1 e%1
%endif
%endmacro
DECLARE_REG_SIZE ax, al, ah
DECLARE_REG_SIZE bx, bl, bh
DECLARE_REG_SIZE cx, cl, ch
DECLARE_REG_SIZE dx, dl, dh
DECLARE_REG_SIZE si, sil, null
DECLARE_REG_SIZE di, dil, null
DECLARE_REG_SIZE bp, bpl, null
; t# defines for when per-arch register allocation is more complex than just function arguments
%macro DECLARE_REG_TMP 1-*
%assign %%i 0
%rep %0
CAT_XDEFINE t, %%i, r%1
%assign %%i %%i+1
%rotate 1
%endrep
%endmacro
%macro DECLARE_REG_TMP_SIZE 0-*
%rep %0
%define t%1q t%1 %+ q
%define t%1d t%1 %+ d
%define t%1w t%1 %+ w
%define t%1h t%1 %+ h
%define t%1b t%1 %+ b
%rotate 1
%endrep
%endmacro
DECLARE_REG_TMP_SIZE 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14
%if ARCH_X86_64
%define gprsize 8
%else
%define gprsize 4
%endif
%macro PUSH 1
push %1
%ifidn rstk, rsp
%assign stack_offset stack_offset+gprsize
%endif
%endmacro
%macro POP 1
pop %1
%ifidn rstk, rsp
%assign stack_offset stack_offset-gprsize
%endif
%endmacro
%macro PUSH_IF_USED 1-*
%rep %0
%if %1 < regs_used
PUSH r%1
%endif
%rotate 1
%endrep
%endmacro
%macro POP_IF_USED 1-*
%rep %0
%if %1 < regs_used
pop r%1
%endif
%rotate 1
%endrep
%endmacro
%macro LOAD_IF_USED 1-*
%rep %0
%if %1 < num_args
mov r%1, r %+ %1 %+ mp
%endif
%rotate 1
%endrep
%endmacro
%macro SUB 2
sub %1, %2
%ifidn %1, rstk
%assign stack_offset stack_offset+(%2)
%endif
%endmacro
%macro ADD 2
add %1, %2
%ifidn %1, rstk
%assign stack_offset stack_offset-(%2)
%endif
%endmacro
%macro movifnidn 2
%ifnidn %1, %2
mov %1, %2
%endif
%endmacro
%macro movsxdifnidn 2
%ifnidn %1, %2
movsxd %1, %2
%endif
%endmacro
%macro ASSERT 1
%if (%1) == 0
%error assert failed
%endif
%endmacro
%macro DEFINE_ARGS 0-*
%ifdef n_arg_names
%assign %%i 0
%rep n_arg_names
CAT_UNDEF arg_name %+ %%i, q
CAT_UNDEF arg_name %+ %%i, d
CAT_UNDEF arg_name %+ %%i, w
CAT_UNDEF arg_name %+ %%i, h
CAT_UNDEF arg_name %+ %%i, b
CAT_UNDEF arg_name %+ %%i, m
CAT_UNDEF arg_name %+ %%i, mp
CAT_UNDEF arg_name, %%i
%assign %%i %%i+1
%endrep
%endif
%xdefine %%stack_offset stack_offset
%undef stack_offset ; so that the current value of stack_offset doesn't get baked in by xdefine
%assign %%i 0
%rep %0
%xdefine %1q r %+ %%i %+ q
%xdefine %1d r %+ %%i %+ d
%xdefine %1w r %+ %%i %+ w
%xdefine %1h r %+ %%i %+ h
%xdefine %1b r %+ %%i %+ b
%xdefine %1m r %+ %%i %+ m
%xdefine %1mp r %+ %%i %+ mp
CAT_XDEFINE arg_name, %%i, %1
%assign %%i %%i+1
%rotate 1
%endrep
%xdefine stack_offset %%stack_offset
%assign n_arg_names %0
%endmacro
%define required_stack_alignment ((mmsize + 15) & ~15)
%macro ALLOC_STACK 1-2 0 ; stack_size, n_xmm_regs (for win64 only)
%ifnum %1
%if %1 != 0
%assign %%pad 0
%assign stack_size %1
%if stack_size < 0
%assign stack_size -stack_size
%endif
%if WIN64
%assign %%pad %%pad + 32 ; shadow space
%if mmsize != 8
%assign xmm_regs_used %2
%if xmm_regs_used > 8
%assign %%pad %%pad + (xmm_regs_used-8)*16 ; callee-saved xmm registers
%endif
%endif
%endif
%if required_stack_alignment <= STACK_ALIGNMENT
; maintain the current stack alignment
%assign stack_size_padded stack_size + %%pad + ((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1))
SUB rsp, stack_size_padded
%else
%assign %%reg_num (regs_used - 1)
%xdefine rstk r %+ %%reg_num
; align stack, and save original stack location directly above
; it, i.e. in [rsp+stack_size_padded], so we can restore the
; stack in a single instruction (i.e. mov rsp, rstk or mov
; rsp, [rsp+stack_size_padded])
%if %1 < 0 ; need to store rsp on stack
%xdefine rstkm [rsp + stack_size + %%pad]
%assign %%pad %%pad + gprsize
%else ; can keep rsp in rstk during whole function
%xdefine rstkm rstk
%endif
%assign stack_size_padded stack_size + ((%%pad + required_stack_alignment-1) & ~(required_stack_alignment-1))
mov rstk, rsp
and rsp, ~(required_stack_alignment-1)
sub rsp, stack_size_padded
movifnidn rstkm, rstk
%endif
WIN64_PUSH_XMM
%endif
%endif
%endmacro
%macro SETUP_STACK_POINTER 1
%ifnum %1
%if %1 != 0 && required_stack_alignment > STACK_ALIGNMENT
%if %1 > 0
%assign regs_used (regs_used + 1)
%elif ARCH_X86_64 && regs_used == num_args && num_args <= 4 + UNIX64 * 2
%warning "Stack pointer will overwrite register argument"
%endif
%endif
%endif
%endmacro
%macro DEFINE_ARGS_INTERNAL 3+
%ifnum %2
DEFINE_ARGS %3
%elif %1 == 4
DEFINE_ARGS %2
%elif %1 > 4
DEFINE_ARGS %2, %3
%endif
%endmacro
%if WIN64 ; Windows x64 ;=================================================
DECLARE_REG 0, rcx
DECLARE_REG 1, rdx
DECLARE_REG 2, R8
DECLARE_REG 3, R9
DECLARE_REG 4, R10, 40
DECLARE_REG 5, R11, 48
DECLARE_REG 6, rax, 56
DECLARE_REG 7, rdi, 64
DECLARE_REG 8, rsi, 72
DECLARE_REG 9, rbx, 80
DECLARE_REG 10, rbp, 88
DECLARE_REG 11, R12, 96
DECLARE_REG 12, R13, 104
DECLARE_REG 13, R14, 112
DECLARE_REG 14, R15, 120
%macro PROLOGUE 2-5+ 0 ; #args, #regs, #xmm_regs, [stack_size,] arg_names...
%assign num_args %1
%assign regs_used %2
ASSERT regs_used >= num_args
SETUP_STACK_POINTER %4
ASSERT regs_used <= 15
PUSH_IF_USED 7, 8, 9, 10, 11, 12, 13, 14
ALLOC_STACK %4, %3
%if mmsize != 8 && stack_size == 0
WIN64_SPILL_XMM %3
%endif
LOAD_IF_USED 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
DEFINE_ARGS_INTERNAL %0, %4, %5
%endmacro
%macro WIN64_PUSH_XMM 0
; Use the shadow space to store XMM6 and XMM7, the rest needs stack space allocated.
%if xmm_regs_used > 6
movaps [rstk + stack_offset + 8], xmm6
%endif
%if xmm_regs_used > 7
movaps [rstk + stack_offset + 24], xmm7
%endif
%if xmm_regs_used > 8
%assign %%i 8
%rep xmm_regs_used-8
movaps [rsp + (%%i-8)*16 + stack_size + 32], xmm %+ %%i
%assign %%i %%i+1
%endrep
%endif
%endmacro
%macro WIN64_SPILL_XMM 1
%assign xmm_regs_used %1
ASSERT xmm_regs_used <= 16
%if xmm_regs_used > 8
; Allocate stack space for callee-saved xmm registers plus shadow space and align the stack.
%assign %%pad (xmm_regs_used-8)*16 + 32
%assign stack_size_padded %%pad + ((-%%pad-stack_offset-gprsize) & (STACK_ALIGNMENT-1))
SUB rsp, stack_size_padded
%endif
WIN64_PUSH_XMM
%endmacro
%macro WIN64_RESTORE_XMM_INTERNAL 1
%assign %%pad_size 0
%if xmm_regs_used > 8
%assign %%i xmm_regs_used
%rep xmm_regs_used-8
%assign %%i %%i-1
movaps xmm %+ %%i, [%1 + (%%i-8)*16 + stack_size + 32]
%endrep
%endif
%if stack_size_padded > 0
%if stack_size > 0 && required_stack_alignment > STACK_ALIGNMENT
mov rsp, rstkm
%else
add %1, stack_size_padded
%assign %%pad_size stack_size_padded
%endif
%endif
%if xmm_regs_used > 7
movaps xmm7, [%1 + stack_offset - %%pad_size + 24]
%endif
%if xmm_regs_used > 6
movaps xmm6, [%1 + stack_offset - %%pad_size + 8]
%endif
%endmacro
%macro WIN64_RESTORE_XMM 1
WIN64_RESTORE_XMM_INTERNAL %1
%assign stack_offset (stack_offset-stack_size_padded)
%assign xmm_regs_used 0
%endmacro
%define has_epilogue regs_used > 7 || xmm_regs_used > 6 || mmsize == 32 || stack_size > 0
%macro RET 0
WIN64_RESTORE_XMM_INTERNAL rsp
POP_IF_USED 14, 13, 12, 11, 10, 9, 8, 7
%if mmsize == 32
vzeroupper
%endif
AUTO_REP_RET
%endmacro
%elif ARCH_X86_64 ; *nix x64 ;=============================================
DECLARE_REG 0, rdi
DECLARE_REG 1, rsi
DECLARE_REG 2, rdx
DECLARE_REG 3, rcx
DECLARE_REG 4, R8
DECLARE_REG 5, R9
DECLARE_REG 6, rax, 8
DECLARE_REG 7, R10, 16
DECLARE_REG 8, R11, 24
DECLARE_REG 9, rbx, 32
DECLARE_REG 10, rbp, 40
DECLARE_REG 11, R12, 48
DECLARE_REG 12, R13, 56
DECLARE_REG 13, R14, 64
DECLARE_REG 14, R15, 72
%macro PROLOGUE 2-5+ ; #args, #regs, #xmm_regs, [stack_size,] arg_names...
%assign num_args %1
%assign regs_used %2
ASSERT regs_used >= num_args
SETUP_STACK_POINTER %4
ASSERT regs_used <= 15
PUSH_IF_USED 9, 10, 11, 12, 13, 14
ALLOC_STACK %4
LOAD_IF_USED 6, 7, 8, 9, 10, 11, 12, 13, 14
DEFINE_ARGS_INTERNAL %0, %4, %5
%endmacro
%define has_epilogue regs_used > 9 || mmsize == 32 || stack_size > 0
%macro RET 0
%if stack_size_padded > 0
%if required_stack_alignment > STACK_ALIGNMENT
mov rsp, rstkm
%else
add rsp, stack_size_padded
%endif
%endif
POP_IF_USED 14, 13, 12, 11, 10, 9
%if mmsize == 32
vzeroupper
%endif
AUTO_REP_RET
%endmacro
%else ; X86_32 ;==============================================================
DECLARE_REG 0, eax, 4
DECLARE_REG 1, ecx, 8
DECLARE_REG 2, edx, 12
DECLARE_REG 3, ebx, 16
DECLARE_REG 4, esi, 20
DECLARE_REG 5, edi, 24
DECLARE_REG 6, ebp, 28
%define rsp esp
%macro DECLARE_ARG 1-*
%rep %0
%define r%1m [rstk + stack_offset + 4*%1 + 4]
%define r%1mp dword r%1m
%rotate 1
%endrep
%endmacro
DECLARE_ARG 7, 8, 9, 10, 11, 12, 13, 14
%macro PROLOGUE 2-5+ ; #args, #regs, #xmm_regs, [stack_size,] arg_names...
%assign num_args %1
%assign regs_used %2
ASSERT regs_used >= num_args
%if num_args > 7
%assign num_args 7
%endif
%if regs_used > 7
%assign regs_used 7
%endif
SETUP_STACK_POINTER %4
ASSERT regs_used <= 7
PUSH_IF_USED 3, 4, 5, 6
ALLOC_STACK %4
LOAD_IF_USED 0, 1, 2, 3, 4, 5, 6
DEFINE_ARGS_INTERNAL %0, %4, %5
%endmacro
%define has_epilogue regs_used > 3 || mmsize == 32 || stack_size > 0
%macro RET 0
%if stack_size_padded > 0
%if required_stack_alignment > STACK_ALIGNMENT
mov rsp, rstkm
%else
add rsp, stack_size_padded
%endif
%endif
POP_IF_USED 6, 5, 4, 3
%if mmsize == 32
vzeroupper
%endif
AUTO_REP_RET
%endmacro
%endif ;======================================================================
%if WIN64 == 0
%macro WIN64_SPILL_XMM 1
%endmacro
%macro WIN64_RESTORE_XMM 1
%endmacro
%macro WIN64_PUSH_XMM 0
%endmacro
%endif
; On AMD cpus <=K10, an ordinary ret is slow if it immediately follows either
; a branch or a branch target. So switch to a 2-byte form of ret in that case.
; We can automatically detect "follows a branch", but not a branch target.
; (SSSE3 is a sufficient condition to know that your cpu doesn't have this problem.)
%macro REP_RET 0
%if has_epilogue
RET
%else
rep ret
%endif
%endmacro
%define last_branch_adr $$
%macro AUTO_REP_RET 0
%ifndef cpuflags
times ((last_branch_adr-$)>>31)+1 rep ; times 1 iff $ != last_branch_adr.
%elif notcpuflag(ssse3)
times ((last_branch_adr-$)>>31)+1 rep
%endif
ret
%endmacro
%macro BRANCH_INSTR 0-*
%rep %0
%macro %1 1-2 %1
%2 %1
%%branch_instr:
%xdefine last_branch_adr %%branch_instr
%endmacro
%rotate 1
%endrep
%endmacro
BRANCH_INSTR jz, je, jnz, jne, jl, jle, jnl, jnle, jg, jge, jng, jnge, ja, jae, jna, jnae, jb, jbe, jnb, jnbe, jc, jnc, js, jns, jo, jno, jp, jnp
%macro TAIL_CALL 2 ; callee, is_nonadjacent
%if has_epilogue
call %1
RET
%elif %2
jmp %1
%endif
%endmacro
;=============================================================================
; arch-independent part
;=============================================================================
%assign function_align 16
; Begin a function.
; Applies any symbol mangling needed for C linkage, and sets up a define such that
; subsequent uses of the function name automatically refer to the mangled version.
; Appends cpuflags to the function name if cpuflags has been specified.
; The "" empty default parameter is a workaround for nasm, which fails if SUFFIX
; is empty and we call cglobal_internal with just %1 %+ SUFFIX (without %2).
%macro cglobal 1-2+ "" ; name, [PROLOGUE args]
cglobal_internal 1, %1 %+ SUFFIX, %2
%endmacro
%macro cvisible 1-2+ "" ; name, [PROLOGUE args]
cglobal_internal 0, %1 %+ SUFFIX, %2
%endmacro
%macro cglobal_internal 2-3+
%if %1
%xdefine %%FUNCTION_PREFIX private_prefix
; libvpx explicitly sets visibility in shared object builds. Avoid
; setting visibility to hidden as it may break builds that split
; sources on e.g., directory boundaries.
%ifdef CHROMIUM
%xdefine %%VISIBILITY hidden
%else
%xdefine %%VISIBILITY
%endif
%else
%xdefine %%FUNCTION_PREFIX public_prefix
%xdefine %%VISIBILITY
%endif
%ifndef cglobaled_%2
%xdefine %2 mangle(%%FUNCTION_PREFIX %+ _ %+ %2)
%xdefine %2.skip_prologue %2 %+ .skip_prologue
CAT_XDEFINE cglobaled_, %2, 1
%endif
%xdefine current_function %2
%ifidn __OUTPUT_FORMAT__,elf32
global %2:function %%VISIBILITY
%elifidn __OUTPUT_FORMAT__,elf64
global %2:function %%VISIBILITY
%elifidn __OUTPUT_FORMAT__,macho32
%ifdef __NASM_VER__
global %2
%else
global %2:private_extern
%endif
%elifidn __OUTPUT_FORMAT__,macho64
%ifdef __NASM_VER__
global %2
%else
global %2:private_extern
%endif
%else
global %2
%endif
align function_align
%2:
RESET_MM_PERMUTATION ; needed for x86-64, also makes disassembly somewhat nicer
%xdefine rstk rsp ; copy of the original stack pointer, used when greater alignment than the known stack alignment is required
%assign stack_offset 0 ; stack pointer offset relative to the return address
%assign stack_size 0 ; amount of stack space that can be freely used inside a function
%assign stack_size_padded 0 ; total amount of allocated stack space, including space for callee-saved xmm registers on WIN64 and alignment padding
%assign xmm_regs_used 0 ; number of XMM registers requested, used for dealing with callee-saved registers on WIN64
%ifnidn %3, ""
PROLOGUE %3
%endif
%endmacro
%macro cextern 1
%xdefine %1 mangle(private_prefix %+ _ %+ %1)
CAT_XDEFINE cglobaled_, %1, 1
extern %1
%endmacro
; like cextern, but without the prefix
%macro cextern_naked 1
%xdefine %1 mangle(%1)
CAT_XDEFINE cglobaled_, %1, 1
extern %1
%endmacro
%macro const 1-2+
%xdefine %1 mangle(private_prefix %+ _ %+ %1)
%ifidn __OUTPUT_FORMAT__,elf32
global %1:data hidden
%elifidn __OUTPUT_FORMAT__,elf64
global %1:data hidden
%else
global %1
%endif
%1: %2
%endmacro
; This is needed for ELF, otherwise the GNU linker assumes the stack is
; executable by default.
%ifidn __OUTPUT_FORMAT__,elf32
SECTION .note.GNU-stack noalloc noexec nowrite progbits
%elifidn __OUTPUT_FORMAT__,elf64
SECTION .note.GNU-stack noalloc noexec nowrite progbits
%endif
; cpuflags
%assign cpuflags_mmx (1<<0)
%assign cpuflags_mmx2 (1<<1) | cpuflags_mmx
%assign cpuflags_3dnow (1<<2) | cpuflags_mmx
%assign cpuflags_3dnowext (1<<3) | cpuflags_3dnow
%assign cpuflags_sse (1<<4) | cpuflags_mmx2
%assign cpuflags_sse2 (1<<5) | cpuflags_sse
%assign cpuflags_sse2slow (1<<6) | cpuflags_sse2
%assign cpuflags_sse3 (1<<7) | cpuflags_sse2
%assign cpuflags_ssse3 (1<<8) | cpuflags_sse3
%assign cpuflags_sse4 (1<<9) | cpuflags_ssse3
%assign cpuflags_sse42 (1<<10)| cpuflags_sse4
%assign cpuflags_avx (1<<11)| cpuflags_sse42
%assign cpuflags_xop (1<<12)| cpuflags_avx
%assign cpuflags_fma4 (1<<13)| cpuflags_avx
%assign cpuflags_fma3 (1<<14)| cpuflags_avx
%assign cpuflags_avx2 (1<<15)| cpuflags_fma3
%assign cpuflags_cache32 (1<<16)
%assign cpuflags_cache64 (1<<17)
%assign cpuflags_slowctz (1<<18)
%assign cpuflags_lzcnt (1<<19)
%assign cpuflags_aligned (1<<20) ; not a cpu feature, but a function variant
%assign cpuflags_atom (1<<21)
%assign cpuflags_bmi1 (1<<22)|cpuflags_lzcnt
%assign cpuflags_bmi2 (1<<23)|cpuflags_bmi1
%define cpuflag(x) ((cpuflags & (cpuflags_ %+ x)) == (cpuflags_ %+ x))
%define notcpuflag(x) ((cpuflags & (cpuflags_ %+ x)) != (cpuflags_ %+ x))
; Takes an arbitrary number of cpuflags from the above list.
; All subsequent functions (up to the next INIT_CPUFLAGS) is built for the specified cpu.
; You shouldn't need to invoke this macro directly, it's a subroutine for INIT_MMX &co.
%macro INIT_CPUFLAGS 0-*
%xdefine SUFFIX
%undef cpuname
%assign cpuflags 0
%if %0 >= 1
%rep %0
%ifdef cpuname
%xdefine cpuname cpuname %+ _%1
%else
%xdefine cpuname %1
%endif
%assign cpuflags cpuflags | cpuflags_%1
%rotate 1
%endrep
%xdefine SUFFIX _ %+ cpuname
%if cpuflag(avx)
%assign avx_enabled 1
%endif
%if (mmsize == 16 && notcpuflag(sse2)) || (mmsize == 32 && notcpuflag(avx2))
%define mova movaps
%define movu movups
%define movnta movntps
%endif
%if cpuflag(aligned)
%define movu mova
%elif cpuflag(sse3) && notcpuflag(ssse3)
%define movu lddqu
%endif
%endif
%ifdef __NASM_VER__
%use smartalign
ALIGNMODE k7
%elif ARCH_X86_64 || cpuflag(sse2)
CPU amdnop
%else
CPU basicnop
%endif
%endmacro
; Merge mmx and sse*
; m# is a simd register of the currently selected size
; xm# is the corresponding xmm register if mmsize >= 16, otherwise the same as m#
; ym# is the corresponding ymm register if mmsize >= 32, otherwise the same as m#
; (All 3 remain in sync through SWAP.)
%macro CAT_XDEFINE 3
%xdefine %1%2 %3
%endmacro
%macro CAT_UNDEF 2
%undef %1%2
%endmacro
%macro INIT_MMX 0-1+
%assign avx_enabled 0
%define RESET_MM_PERMUTATION INIT_MMX %1
%define mmsize 8
%define num_mmregs 8
%define mova movq
%define movu movq
%define movh movd
%define movnta movntq
%assign %%i 0
%rep 8
CAT_XDEFINE m, %%i, mm %+ %%i
CAT_XDEFINE nnmm, %%i, %%i
%assign %%i %%i+1
%endrep
%rep 8
CAT_UNDEF m, %%i
CAT_UNDEF nnmm, %%i
%assign %%i %%i+1
%endrep
INIT_CPUFLAGS %1
%endmacro
%macro INIT_XMM 0-1+
%assign avx_enabled 0
%define RESET_MM_PERMUTATION INIT_XMM %1
%define mmsize 16
%define num_mmregs 8
%if ARCH_X86_64
%define num_mmregs 16
%endif
%define mova movdqa
%define movu movdqu
%define movh movq
%define movnta movntdq
%assign %%i 0
%rep num_mmregs
CAT_XDEFINE m, %%i, xmm %+ %%i
CAT_XDEFINE nnxmm, %%i, %%i
%assign %%i %%i+1
%endrep
INIT_CPUFLAGS %1
%endmacro
%macro INIT_YMM 0-1+
%assign avx_enabled 1
%define RESET_MM_PERMUTATION INIT_YMM %1
%define mmsize 32
%define num_mmregs 8
%if ARCH_X86_64
%define num_mmregs 16
%endif
%define mova movdqa
%define movu movdqu
%undef movh
%define movnta movntdq
%assign %%i 0
%rep num_mmregs
CAT_XDEFINE m, %%i, ymm %+ %%i
CAT_XDEFINE nnymm, %%i, %%i
%assign %%i %%i+1
%endrep
INIT_CPUFLAGS %1
%endmacro
INIT_XMM
%macro DECLARE_MMCAST 1
%define mmmm%1 mm%1
%define mmxmm%1 mm%1
%define mmymm%1 mm%1
%define xmmmm%1 mm%1
%define xmmxmm%1 xmm%1
%define xmmymm%1 xmm%1
%define ymmmm%1 mm%1
%define ymmxmm%1 xmm%1
%define ymmymm%1 ymm%1
%define xm%1 xmm %+ m%1
%define ym%1 ymm %+ m%1
%endmacro
%assign i 0
%rep 16
DECLARE_MMCAST i
%assign i i+1
%endrep
; I often want to use macros that permute their arguments. e.g. there's no
; efficient way to implement butterfly or transpose or dct without swapping some
; arguments.
;
; I would like to not have to manually keep track of the permutations:
; If I insert a permutation in the middle of a function, it should automatically
; change everything that follows. For more complex macros I may also have multiple
; implementations, e.g. the SSE2 and SSSE3 versions may have different permutations.
;
; Hence these macros. Insert a PERMUTE or some SWAPs at the end of a macro that
; permutes its arguments. It's equivalent to exchanging the contents of the
; registers, except that this way you exchange the register names instead, so it
; doesn't cost any cycles.
%macro PERMUTE 2-* ; takes a list of pairs to swap
%rep %0/2
%xdefine %%tmp%2 m%2
%rotate 2
%endrep
%rep %0/2
%xdefine m%1 %%tmp%2
CAT_XDEFINE nn, m%1, %1
%rotate 2
%endrep
%endmacro
%macro SWAP 2+ ; swaps a single chain (sometimes more concise than pairs)
%ifnum %1 ; SWAP 0, 1, ...
SWAP_INTERNAL_NUM %1, %2
%else ; SWAP m0, m1, ...
SWAP_INTERNAL_NAME %1, %2
%endif
%endmacro
%macro SWAP_INTERNAL_NUM 2-*
%rep %0-1
%xdefine %%tmp m%1
%xdefine m%1 m%2
%xdefine m%2 %%tmp
CAT_XDEFINE nn, m%1, %1
CAT_XDEFINE nn, m%2, %2
%rotate 1
%endrep
%endmacro
%macro SWAP_INTERNAL_NAME 2-*
%xdefine %%args nn %+ %1
%rep %0-1
%xdefine %%args %%args, nn %+ %2
%rotate 1
%endrep
SWAP_INTERNAL_NUM %%args
%endmacro
; If SAVE_MM_PERMUTATION is placed at the end of a function, then any later
; calls to that function will automatically load the permutation, so values can
; be returned in mmregs.
%macro SAVE_MM_PERMUTATION 0-1
%if %0
%xdefine %%f %1_m
%else
%xdefine %%f current_function %+ _m
%endif
%assign %%i 0
%rep num_mmregs
CAT_XDEFINE %%f, %%i, m %+ %%i
%assign %%i %%i+1
%endrep
%endmacro
%macro LOAD_MM_PERMUTATION 1 ; name to load from
%ifdef %1_m0
%assign %%i 0
%rep num_mmregs
CAT_XDEFINE m, %%i, %1_m %+ %%i
CAT_XDEFINE nn, m %+ %%i, %%i
%assign %%i %%i+1
%endrep
%endif
%endmacro
; Append cpuflags to the callee's name iff the appended name is known and the plain name isn't
%macro call 1
call_internal %1, %1 %+ SUFFIX
%endmacro
%macro call_internal 2
%xdefine %%i %1
%ifndef cglobaled_%1
%ifdef cglobaled_%2
%xdefine %%i %2
%endif
%endif
call %%i
LOAD_MM_PERMUTATION %%i
%endmacro
; Substitutions that reduce instruction size but are functionally equivalent
%macro add 2
%ifnum %2
%if %2==128
sub %1, -128
%else
add %1, %2
%endif
%else
add %1, %2
%endif
%endmacro
%macro sub 2
%ifnum %2
%if %2==128
add %1, -128
%else
sub %1, %2
%endif
%else
sub %1, %2
%endif
%endmacro
;=============================================================================
; AVX abstraction layer
;=============================================================================
%assign i 0
%rep 16
%if i < 8
CAT_XDEFINE sizeofmm, i, 8
%endif
CAT_XDEFINE sizeofxmm, i, 16
CAT_XDEFINE sizeofymm, i, 32
%assign i i+1
%endrep
%undef i
%macro CHECK_AVX_INSTR_EMU 3-*
%xdefine %%opcode %1
%xdefine %%dst %2
%rep %0-2
%ifidn %%dst, %3
%error non-avx emulation of ``%%opcode'' is not supported
%endif
%rotate 1
%endrep
%endmacro
;%1 == instruction
;%2 == minimal instruction set
;%3 == 1 if float, 0 if int
;%4 == 1 if non-destructive or 4-operand (xmm, xmm, xmm, imm), 0 otherwise
;%5 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
;%6+: operands
%macro RUN_AVX_INSTR 6-9+
%ifnum sizeof%7
%assign __sizeofreg sizeof%7
%elifnum sizeof%6
%assign __sizeofreg sizeof%6
%else
%assign __sizeofreg mmsize
%endif
%assign __emulate_avx 0
%if avx_enabled && __sizeofreg >= 16
%xdefine __instr v%1
%else
%xdefine __instr %1
%if %0 >= 8+%4
%assign __emulate_avx 1
%endif
%endif
%ifnidn %2, fnord
%ifdef cpuname
%if notcpuflag(%2)
%error use of ``%1'' %2 instruction in cpuname function: current_function
%elif cpuflags_%2 < cpuflags_sse && notcpuflag(sse2) && __sizeofreg > 8
%error use of ``%1'' sse2 instruction in cpuname function: current_function
%endif
%endif
%endif
%if __emulate_avx
%xdefine __src1 %7
%xdefine __src2 %8
%ifnidn %6, %7
%if %0 >= 9
CHECK_AVX_INSTR_EMU {%1 %6, %7, %8, %9}, %6, %8, %9
%else
CHECK_AVX_INSTR_EMU {%1 %6, %7, %8}, %6, %8
%endif
%if %5 && %4 == 0
%ifnid %8
; 3-operand AVX instructions with a memory arg can only have it in src2,
; whereas SSE emulation prefers to have it in src1 (i.e. the mov).
; So, if the instruction is commutative with a memory arg, swap them.
%xdefine __src1 %8
%xdefine __src2 %7
%endif
%endif
%if __sizeofreg == 8
MOVQ %6, __src1
%elif %3
MOVAPS %6, __src1
%else
MOVDQA %6, __src1
%endif
%endif
%if %0 >= 9
%1 %6, __src2, %9
%else
%1 %6, __src2
%endif
%elif %0 >= 9
__instr %6, %7, %8, %9
%elif %0 == 8
__instr %6, %7, %8
%elif %0 == 7
__instr %6, %7
%else
__instr %6
%endif
%endmacro
;%1 == instruction
;%2 == minimal instruction set
;%3 == 1 if float, 0 if int
;%4 == 1 if non-destructive or 4-operand (xmm, xmm, xmm, imm), 0 otherwise
;%5 == 1 if commutative (i.e. doesn't matter which src arg is which), 0 if not
%macro AVX_INSTR 1-5 fnord, 0, 1, 0
%macro %1 1-10 fnord, fnord, fnord, fnord, %1, %2, %3, %4, %5
%ifidn %2, fnord
RUN_AVX_INSTR %6, %7, %8, %9, %10, %1
%elifidn %3, fnord
RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2
%elifidn %4, fnord
RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3
%elifidn %5, fnord
RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3, %4
%else
RUN_AVX_INSTR %6, %7, %8, %9, %10, %1, %2, %3, %4, %5
%endif
%endmacro
%endmacro
; Instructions with both VEX and non-VEX encodings
; Non-destructive instructions are written without parameters
AVX_INSTR addpd, sse2, 1, 0, 1
AVX_INSTR addps, sse, 1, 0, 1
AVX_INSTR addsd, sse2, 1, 0, 1
AVX_INSTR addss, sse, 1, 0, 1
AVX_INSTR addsubpd, sse3, 1, 0, 0
AVX_INSTR addsubps, sse3, 1, 0, 0
AVX_INSTR aesdec, fnord, 0, 0, 0
AVX_INSTR aesdeclast, fnord, 0, 0, 0
AVX_INSTR aesenc, fnord, 0, 0, 0
AVX_INSTR aesenclast, fnord, 0, 0, 0
AVX_INSTR aesimc
AVX_INSTR aeskeygenassist
AVX_INSTR andnpd, sse2, 1, 0, 0
AVX_INSTR andnps, sse, 1, 0, 0
AVX_INSTR andpd, sse2, 1, 0, 1
AVX_INSTR andps, sse, 1, 0, 1
AVX_INSTR blendpd, sse4, 1, 0, 0
AVX_INSTR blendps, sse4, 1, 0, 0
AVX_INSTR blendvpd, sse4, 1, 0, 0
AVX_INSTR blendvps, sse4, 1, 0, 0
AVX_INSTR cmppd, sse2, 1, 1, 0
AVX_INSTR cmpps, sse, 1, 1, 0
AVX_INSTR cmpsd, sse2, 1, 1, 0
AVX_INSTR cmpss, sse, 1, 1, 0
AVX_INSTR comisd, sse2
AVX_INSTR comiss, sse
AVX_INSTR cvtdq2pd, sse2
AVX_INSTR cvtdq2ps, sse2
AVX_INSTR cvtpd2dq, sse2
AVX_INSTR cvtpd2ps, sse2
AVX_INSTR cvtps2dq, sse2
AVX_INSTR cvtps2pd, sse2
AVX_INSTR cvtsd2si, sse2
AVX_INSTR cvtsd2ss, sse2
AVX_INSTR cvtsi2sd, sse2
AVX_INSTR cvtsi2ss, sse
AVX_INSTR cvtss2sd, sse2
AVX_INSTR cvtss2si, sse
AVX_INSTR cvttpd2dq, sse2
AVX_INSTR cvttps2dq, sse2
AVX_INSTR cvttsd2si, sse2
AVX_INSTR cvttss2si, sse
AVX_INSTR divpd, sse2, 1, 0, 0
AVX_INSTR divps, sse, 1, 0, 0
AVX_INSTR divsd, sse2, 1, 0, 0
AVX_INSTR divss, sse, 1, 0, 0
AVX_INSTR dppd, sse4, 1, 1, 0
AVX_INSTR dpps, sse4, 1, 1, 0
AVX_INSTR extractps, sse4
AVX_INSTR haddpd, sse3, 1, 0, 0
AVX_INSTR haddps, sse3, 1, 0, 0
AVX_INSTR hsubpd, sse3, 1, 0, 0
AVX_INSTR hsubps, sse3, 1, 0, 0
AVX_INSTR insertps, sse4, 1, 1, 0
AVX_INSTR lddqu, sse3
AVX_INSTR ldmxcsr, sse
AVX_INSTR maskmovdqu, sse2
AVX_INSTR maxpd, sse2, 1, 0, 1
AVX_INSTR maxps, sse, 1, 0, 1
AVX_INSTR maxsd, sse2, 1, 0, 1
AVX_INSTR maxss, sse, 1, 0, 1
AVX_INSTR minpd, sse2, 1, 0, 1
AVX_INSTR minps, sse, 1, 0, 1
AVX_INSTR minsd, sse2, 1, 0, 1
AVX_INSTR minss, sse, 1, 0, 1
AVX_INSTR movapd, sse2
AVX_INSTR movaps, sse
AVX_INSTR movd, mmx
AVX_INSTR movddup, sse3
AVX_INSTR movdqa, sse2
AVX_INSTR movdqu, sse2
AVX_INSTR movhlps, sse, 1, 0, 0
AVX_INSTR movhpd, sse2, 1, 0, 0
AVX_INSTR movhps, sse, 1, 0, 0
AVX_INSTR movlhps, sse, 1, 0, 0
AVX_INSTR movlpd, sse2, 1, 0, 0
AVX_INSTR movlps, sse, 1, 0, 0
AVX_INSTR movmskpd, sse2
AVX_INSTR movmskps, sse
AVX_INSTR movntdq, sse2
AVX_INSTR movntdqa, sse4
AVX_INSTR movntpd, sse2
AVX_INSTR movntps, sse
AVX_INSTR movq, mmx
AVX_INSTR movsd, sse2, 1, 0, 0
AVX_INSTR movshdup, sse3
AVX_INSTR movsldup, sse3
AVX_INSTR movss, sse, 1, 0, 0
AVX_INSTR movupd, sse2
AVX_INSTR movups, sse
AVX_INSTR mpsadbw, sse4
AVX_INSTR mulpd, sse2, 1, 0, 1
AVX_INSTR mulps, sse, 1, 0, 1
AVX_INSTR mulsd, sse2, 1, 0, 1
AVX_INSTR mulss, sse, 1, 0, 1
AVX_INSTR orpd, sse2, 1, 0, 1
AVX_INSTR orps, sse, 1, 0, 1
AVX_INSTR pabsb, ssse3
AVX_INSTR pabsd, ssse3
AVX_INSTR pabsw, ssse3
AVX_INSTR packsswb, mmx, 0, 0, 0
AVX_INSTR packssdw, mmx, 0, 0, 0
AVX_INSTR packuswb, mmx, 0, 0, 0
AVX_INSTR packusdw, sse4, 0, 0, 0
AVX_INSTR paddb, mmx, 0, 0, 1
AVX_INSTR paddw, mmx, 0, 0, 1
AVX_INSTR paddd, mmx, 0, 0, 1
AVX_INSTR paddq, sse2, 0, 0, 1
AVX_INSTR paddsb, mmx, 0, 0, 1
AVX_INSTR paddsw, mmx, 0, 0, 1
AVX_INSTR paddusb, mmx, 0, 0, 1
AVX_INSTR paddusw, mmx, 0, 0, 1
AVX_INSTR palignr, ssse3
AVX_INSTR pand, mmx, 0, 0, 1
AVX_INSTR pandn, mmx, 0, 0, 0
AVX_INSTR pavgb, mmx2, 0, 0, 1
AVX_INSTR pavgw, mmx2, 0, 0, 1
AVX_INSTR pblendvb, sse4, 0, 0, 0
AVX_INSTR pblendw, sse4
AVX_INSTR pclmulqdq
AVX_INSTR pcmpestri, sse42
AVX_INSTR pcmpestrm, sse42
AVX_INSTR pcmpistri, sse42
AVX_INSTR pcmpistrm, sse42
AVX_INSTR pcmpeqb, mmx, 0, 0, 1
AVX_INSTR pcmpeqw, mmx, 0, 0, 1
AVX_INSTR pcmpeqd, mmx, 0, 0, 1
AVX_INSTR pcmpeqq, sse4, 0, 0, 1
AVX_INSTR pcmpgtb, mmx, 0, 0, 0
AVX_INSTR pcmpgtw, mmx, 0, 0, 0
AVX_INSTR pcmpgtd, mmx, 0, 0, 0
AVX_INSTR pcmpgtq, sse42, 0, 0, 0
AVX_INSTR pextrb, sse4
AVX_INSTR pextrd, sse4
AVX_INSTR pextrq, sse4
AVX_INSTR pextrw, mmx2
AVX_INSTR phaddw, ssse3, 0, 0, 0
AVX_INSTR phaddd, ssse3, 0, 0, 0
AVX_INSTR phaddsw, ssse3, 0, 0, 0
AVX_INSTR phminposuw, sse4
AVX_INSTR phsubw, ssse3, 0, 0, 0
AVX_INSTR phsubd, ssse3, 0, 0, 0
AVX_INSTR phsubsw, ssse3, 0, 0, 0
AVX_INSTR pinsrb, sse4
AVX_INSTR pinsrd, sse4
AVX_INSTR pinsrq, sse4
AVX_INSTR pinsrw, mmx2
AVX_INSTR pmaddwd, mmx, 0, 0, 1
AVX_INSTR pmaddubsw, ssse3, 0, 0, 0
AVX_INSTR pmaxsb, sse4, 0, 0, 1
AVX_INSTR pmaxsw, mmx2, 0, 0, 1
AVX_INSTR pmaxsd, sse4, 0, 0, 1
AVX_INSTR pmaxub, mmx2, 0, 0, 1
AVX_INSTR pmaxuw, sse4, 0, 0, 1
AVX_INSTR pmaxud, sse4, 0, 0, 1
AVX_INSTR pminsb, sse4, 0, 0, 1
AVX_INSTR pminsw, mmx2, 0, 0, 1
AVX_INSTR pminsd, sse4, 0, 0, 1
AVX_INSTR pminub, mmx2, 0, 0, 1
AVX_INSTR pminuw, sse4, 0, 0, 1
AVX_INSTR pminud, sse4, 0, 0, 1
AVX_INSTR pmovmskb, mmx2
AVX_INSTR pmovsxbw, sse4
AVX_INSTR pmovsxbd, sse4
AVX_INSTR pmovsxbq, sse4
AVX_INSTR pmovsxwd, sse4
AVX_INSTR pmovsxwq, sse4
AVX_INSTR pmovsxdq, sse4
AVX_INSTR pmovzxbw, sse4
AVX_INSTR pmovzxbd, sse4
AVX_INSTR pmovzxbq, sse4
AVX_INSTR pmovzxwd, sse4
AVX_INSTR pmovzxwq, sse4
AVX_INSTR pmovzxdq, sse4
AVX_INSTR pmuldq, sse4, 0, 0, 1
AVX_INSTR pmulhrsw, ssse3, 0, 0, 1
AVX_INSTR pmulhuw, mmx2, 0, 0, 1
AVX_INSTR pmulhw, mmx, 0, 0, 1
AVX_INSTR pmullw, mmx, 0, 0, 1
AVX_INSTR pmulld, sse4, 0, 0, 1
AVX_INSTR pmuludq, sse2, 0, 0, 1
AVX_INSTR por, mmx, 0, 0, 1
AVX_INSTR psadbw, mmx2, 0, 0, 1
AVX_INSTR pshufb, ssse3, 0, 0, 0
AVX_INSTR pshufd, sse2
AVX_INSTR pshufhw, sse2
AVX_INSTR pshuflw, sse2
AVX_INSTR psignb, ssse3, 0, 0, 0
AVX_INSTR psignw, ssse3, 0, 0, 0
AVX_INSTR psignd, ssse3, 0, 0, 0
AVX_INSTR psllw, mmx, 0, 0, 0
AVX_INSTR pslld, mmx, 0, 0, 0
AVX_INSTR psllq, mmx, 0, 0, 0
AVX_INSTR pslldq, sse2, 0, 0, 0
AVX_INSTR psraw, mmx, 0, 0, 0
AVX_INSTR psrad, mmx, 0, 0, 0
AVX_INSTR psrlw, mmx, 0, 0, 0
AVX_INSTR psrld, mmx, 0, 0, 0
AVX_INSTR psrlq, mmx, 0, 0, 0
AVX_INSTR psrldq, sse2, 0, 0, 0
AVX_INSTR psubb, mmx, 0, 0, 0
AVX_INSTR psubw, mmx, 0, 0, 0
AVX_INSTR psubd, mmx, 0, 0, 0
AVX_INSTR psubq, sse2, 0, 0, 0
AVX_INSTR psubsb, mmx, 0, 0, 0
AVX_INSTR psubsw, mmx, 0, 0, 0
AVX_INSTR psubusb, mmx, 0, 0, 0
AVX_INSTR psubusw, mmx, 0, 0, 0
AVX_INSTR ptest, sse4
AVX_INSTR punpckhbw, mmx, 0, 0, 0
AVX_INSTR punpckhwd, mmx, 0, 0, 0
AVX_INSTR punpckhdq, mmx, 0, 0, 0
AVX_INSTR punpckhqdq, sse2, 0, 0, 0
AVX_INSTR punpcklbw, mmx, 0, 0, 0
AVX_INSTR punpcklwd, mmx, 0, 0, 0
AVX_INSTR punpckldq, mmx, 0, 0, 0
AVX_INSTR punpcklqdq, sse2, 0, 0, 0
AVX_INSTR pxor, mmx, 0, 0, 1
AVX_INSTR rcpps, sse, 1, 0, 0
AVX_INSTR rcpss, sse, 1, 0, 0
AVX_INSTR roundpd, sse4
AVX_INSTR roundps, sse4
AVX_INSTR roundsd, sse4
AVX_INSTR roundss, sse4
AVX_INSTR rsqrtps, sse, 1, 0, 0
AVX_INSTR rsqrtss, sse, 1, 0, 0
AVX_INSTR shufpd, sse2, 1, 1, 0
AVX_INSTR shufps, sse, 1, 1, 0
AVX_INSTR sqrtpd, sse2, 1, 0, 0
AVX_INSTR sqrtps, sse, 1, 0, 0
AVX_INSTR sqrtsd, sse2, 1, 0, 0
AVX_INSTR sqrtss, sse, 1, 0, 0
AVX_INSTR stmxcsr, sse
AVX_INSTR subpd, sse2, 1, 0, 0
AVX_INSTR subps, sse, 1, 0, 0
AVX_INSTR subsd, sse2, 1, 0, 0
AVX_INSTR subss, sse, 1, 0, 0
AVX_INSTR ucomisd, sse2
AVX_INSTR ucomiss, sse
AVX_INSTR unpckhpd, sse2, 1, 0, 0
AVX_INSTR unpckhps, sse, 1, 0, 0
AVX_INSTR unpcklpd, sse2, 1, 0, 0
AVX_INSTR unpcklps, sse, 1, 0, 0
AVX_INSTR xorpd, sse2, 1, 0, 1
AVX_INSTR xorps, sse, 1, 0, 1
; 3DNow instructions, for sharing code between AVX, SSE and 3DN
AVX_INSTR pfadd, 3dnow, 1, 0, 1
AVX_INSTR pfsub, 3dnow, 1, 0, 0
AVX_INSTR pfmul, 3dnow, 1, 0, 1
; base-4 constants for shuffles
%assign i 0
%rep 256
%assign j ((i>>6)&3)*1000 + ((i>>4)&3)*100 + ((i>>2)&3)*10 + (i&3)
%if j < 10
CAT_XDEFINE q000, j, i
%elif j < 100
CAT_XDEFINE q00, j, i
%elif j < 1000
CAT_XDEFINE q0, j, i
%else
CAT_XDEFINE q, j, i
%endif
%assign i i+1
%endrep
%undef i
%undef j
%macro FMA_INSTR 3
%macro %1 4-7 %1, %2, %3
%if cpuflag(xop)
v%5 %1, %2, %3, %4
%elifnidn %1, %4
%6 %1, %2, %3
%7 %1, %4
%else
%error non-xop emulation of ``%5 %1, %2, %3, %4'' is not supported
%endif
%endmacro
%endmacro
FMA_INSTR pmacsww, pmullw, paddw
FMA_INSTR pmacsdd, pmulld, paddd ; sse4 emulation
FMA_INSTR pmacsdql, pmuldq, paddq ; sse4 emulation
FMA_INSTR pmadcswd, pmaddwd, paddd
; convert FMA4 to FMA3 if possible
%macro FMA4_INSTR 4
%macro %1 4-8 %1, %2, %3, %4
%if cpuflag(fma4)
v%5 %1, %2, %3, %4
%elifidn %1, %2
v%6 %1, %4, %3 ; %1 = %1 * %3 + %4
%elifidn %1, %3
v%7 %1, %2, %4 ; %1 = %2 * %1 + %4
%elifidn %1, %4
v%8 %1, %2, %3 ; %1 = %2 * %3 + %1
%else
%error fma3 emulation of ``%5 %1, %2, %3, %4'' is not supported
%endif
%endmacro
%endmacro
FMA4_INSTR fmaddpd, fmadd132pd, fmadd213pd, fmadd231pd
FMA4_INSTR fmaddps, fmadd132ps, fmadd213ps, fmadd231ps
FMA4_INSTR fmaddsd, fmadd132sd, fmadd213sd, fmadd231sd
FMA4_INSTR fmaddss, fmadd132ss, fmadd213ss, fmadd231ss
FMA4_INSTR fmaddsubpd, fmaddsub132pd, fmaddsub213pd, fmaddsub231pd
FMA4_INSTR fmaddsubps, fmaddsub132ps, fmaddsub213ps, fmaddsub231ps
FMA4_INSTR fmsubaddpd, fmsubadd132pd, fmsubadd213pd, fmsubadd231pd
FMA4_INSTR fmsubaddps, fmsubadd132ps, fmsubadd213ps, fmsubadd231ps
FMA4_INSTR fmsubpd, fmsub132pd, fmsub213pd, fmsub231pd
FMA4_INSTR fmsubps, fmsub132ps, fmsub213ps, fmsub231ps
FMA4_INSTR fmsubsd, fmsub132sd, fmsub213sd, fmsub231sd
FMA4_INSTR fmsubss, fmsub132ss, fmsub213ss, fmsub231ss
FMA4_INSTR fnmaddpd, fnmadd132pd, fnmadd213pd, fnmadd231pd
FMA4_INSTR fnmaddps, fnmadd132ps, fnmadd213ps, fnmadd231ps
FMA4_INSTR fnmaddsd, fnmadd132sd, fnmadd213sd, fnmadd231sd
FMA4_INSTR fnmaddss, fnmadd132ss, fnmadd213ss, fnmadd231ss
FMA4_INSTR fnmsubpd, fnmsub132pd, fnmsub213pd, fnmsub231pd
FMA4_INSTR fnmsubps, fnmsub132ps, fnmsub213ps, fnmsub231ps
FMA4_INSTR fnmsubsd, fnmsub132sd, fnmsub213sd, fnmsub231sd
FMA4_INSTR fnmsubss, fnmsub132ss, fnmsub213ss, fnmsub231ss
; workaround: vpbroadcastq is broken in x86_32 due to a yasm bug
%if ARCH_X86_64 == 0
%macro vpbroadcastq 2
%if sizeof%1 == 16
movddup %1, %2
%else
vbroadcastsd %1, %2
%endif
%endmacro
%endif
| liqianggao/libvpx | third_party/x86inc/x86inc.asm | Assembly | bsd-3-clause | 45,789 |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Orchard.CodeGeneration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Orchard")]
[assembly: AssemblyCopyright("Copyright © .NET Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a5ae5869-1454-4fe8-a998-a3f2e79c91a3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.9.0")]
[assembly: AssemblyFileVersion("1.9.0")]
| smartnet-developers/Orchard | src/Orchard.Web/Modules/Orchard.CodeGeneration/Properties/AssemblyInfo.cs | C# | bsd-3-clause | 1,359 |
// Copyright (c) 2012 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 "chrome/browser/prefs/pref_service_syncable_builder.h"
#include "base/debug/trace_event.h"
#include "base/prefs/default_pref_store.h"
#include "base/prefs/pref_notifier_impl.h"
#include "base/prefs/pref_value_store.h"
#include "chrome/browser/policy/configuration_policy_pref_store.h"
#include "chrome/browser/policy/policy_service.h"
#include "chrome/browser/prefs/command_line_pref_store.h"
#include "chrome/browser/prefs/pref_service_syncable.h"
#include "components/user_prefs/pref_registry_syncable.h"
PrefServiceSyncableBuilder::PrefServiceSyncableBuilder() {
}
PrefServiceSyncableBuilder::~PrefServiceSyncableBuilder() {
}
#if defined(ENABLE_CONFIGURATION_POLICY)
PrefServiceSyncableBuilder& PrefServiceSyncableBuilder::WithManagedPolicies(
policy::PolicyService* service) {
WithManagedPrefs(new policy::ConfigurationPolicyPrefStore(
service, policy::POLICY_LEVEL_MANDATORY));
return *this;
}
PrefServiceSyncableBuilder& PrefServiceSyncableBuilder::WithRecommendedPolicies(
policy::PolicyService* service) {
WithRecommendedPrefs(new policy::ConfigurationPolicyPrefStore(
service, policy::POLICY_LEVEL_RECOMMENDED));
return *this;
}
#endif
PrefServiceSyncableBuilder&
PrefServiceSyncableBuilder::WithCommandLine(CommandLine* command_line) {
WithCommandLinePrefs(new CommandLinePrefStore(command_line));
return *this;
}
PrefServiceSyncable* PrefServiceSyncableBuilder::CreateSyncable(
user_prefs::PrefRegistrySyncable* pref_registry) {
TRACE_EVENT0("browser", "PrefServiceSyncableBuilder::CreateSyncable");
PrefNotifierImpl* pref_notifier = new PrefNotifierImpl();
PrefServiceSyncable* pref_service = new PrefServiceSyncable(
pref_notifier,
new PrefValueStore(managed_prefs_.get(),
extension_prefs_.get(),
command_line_prefs_.get(),
user_prefs_.get(),
recommended_prefs_.get(),
pref_registry->defaults().get(),
pref_notifier),
user_prefs_.get(),
pref_registry,
read_error_callback_,
async_);
ResetDefaultState();
return pref_service;
}
| espadrine/opera | chromium/src/chrome/browser/prefs/pref_service_syncable_builder.cc | C++ | bsd-3-clause | 2,359 |
<?php
/**
* YiiBase class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008-2013 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @package system
* @since 1.0
*/
/**
* Gets the application start timestamp.
*/
defined('YII_BEGIN_TIME') or define('YII_BEGIN_TIME',microtime(true));
/**
* This constant defines whether the application should be in debug mode or not. Defaults to false.
*/
defined('YII_DEBUG') or define('YII_DEBUG',false);
/**
* This constant defines how much call stack information (file name and line number) should be logged by Yii::trace().
* Defaults to 0, meaning no backtrace information. If it is greater than 0,
* at most that number of call stacks will be logged. Note, only user application call stacks are considered.
*/
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',0);
/**
* This constant defines whether exception handling should be enabled. Defaults to true.
*/
defined('YII_ENABLE_EXCEPTION_HANDLER') or define('YII_ENABLE_EXCEPTION_HANDLER',true);
/**
* This constant defines whether error handling should be enabled. Defaults to true.
*/
defined('YII_ENABLE_ERROR_HANDLER') or define('YII_ENABLE_ERROR_HANDLER',true);
/**
* Defines the Yii framework installation path.
*/
defined('YII_PATH') or define('YII_PATH',dirname(__FILE__));
/**
* Defines the Zii library installation path.
*/
defined('YII_ZII_PATH') or define('YII_ZII_PATH',YII_PATH.DIRECTORY_SEPARATOR.'zii');
/**
* YiiBase is a helper class serving common framework functionalities.
*
* Do not use YiiBase directly. Instead, use its child class {@link Yii} where
* you can customize methods of YiiBase.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @package system
* @since 1.0
*/
class YiiBase
{
/**
* @var array class map used by the Yii autoloading mechanism.
* The array keys are the class names and the array values are the corresponding class file paths.
* @since 1.1.5
*/
public static $classMap=array();
/**
* @var boolean whether to rely on PHP include path to autoload class files. Defaults to true.
* You may set this to be false if your hosting environment doesn't allow changing the PHP
* include path, or if you want to append additional autoloaders to the default Yii autoloader.
* @since 1.1.8
*/
public static $enableIncludePath=true;
private static $_aliases=array('system'=>YII_PATH,'zii'=>YII_ZII_PATH); // alias => path
private static $_imports=array(); // alias => class name or directory
private static $_includePaths; // list of include paths
private static $_app;
private static $_logger;
/**
* @return string the version of Yii framework
*/
public static function getVersion()
{
return '1.1.15-dev';
}
/**
* Creates a Web application instance.
* @param mixed $config application configuration.
* If a string, it is treated as the path of the file that contains the configuration;
* If an array, it is the actual configuration information.
* Please make sure you specify the {@link CApplication::basePath basePath} property in the configuration,
* which should point to the directory containing all application logic, template and data.
* If not, the directory will be defaulted to 'protected'.
* @return CWebApplication
*/
public static function createWebApplication($config=null)
{
return self::createApplication('CWebApplication',$config);
}
/**
* Creates a console application instance.
* @param mixed $config application configuration.
* If a string, it is treated as the path of the file that contains the configuration;
* If an array, it is the actual configuration information.
* Please make sure you specify the {@link CApplication::basePath basePath} property in the configuration,
* which should point to the directory containing all application logic, template and data.
* If not, the directory will be defaulted to 'protected'.
* @return CConsoleApplication
*/
public static function createConsoleApplication($config=null)
{
return self::createApplication('CConsoleApplication',$config);
}
/**
* Creates an application of the specified class.
* @param string $class the application class name
* @param mixed $config application configuration. This parameter will be passed as the parameter
* to the constructor of the application class.
* @return mixed the application instance
*/
public static function createApplication($class,$config=null)
{
return new $class($config);
}
/**
* Returns the application singleton or null if the singleton has not been created yet.
* @return CApplication the application singleton, null if the singleton has not been created yet.
*/
public static function app()
{
return self::$_app;
}
/**
* Stores the application instance in the class static member.
* This method helps implement a singleton pattern for CApplication.
* Repeated invocation of this method or the CApplication constructor
* will cause the throw of an exception.
* To retrieve the application instance, use {@link app()}.
* @param CApplication $app the application instance. If this is null, the existing
* application singleton will be removed.
* @throws CException if multiple application instances are registered.
*/
public static function setApplication($app)
{
if(self::$_app===null || $app===null)
self::$_app=$app;
else
throw new CException(Yii::t('yii','Yii application can only be created once.'));
}
/**
* @return string the path of the framework
*/
public static function getFrameworkPath()
{
return YII_PATH;
}
/**
* Creates an object and initializes it based on the given configuration.
*
* The specified configuration can be either a string or an array.
* If the former, the string is treated as the object type which can
* be either the class name or {@link YiiBase::getPathOfAlias class path alias}.
* If the latter, the 'class' element is treated as the object type,
* and the rest of the name-value pairs in the array are used to initialize
* the corresponding object properties.
*
* Any additional parameters passed to this method will be
* passed to the constructor of the object being created.
*
* @param mixed $config the configuration. It can be either a string or an array.
* @return mixed the created object
* @throws CException if the configuration does not have a 'class' element.
*/
public static function createComponent($config)
{
if(is_string($config))
{
$type=$config;
$config=array();
}
elseif(isset($config['class']))
{
$type=$config['class'];
unset($config['class']);
}
else
throw new CException(Yii::t('yii','Object configuration must be an array containing a "class" element.'));
if(!class_exists($type,false))
$type=Yii::import($type,true);
if(($n=func_num_args())>1)
{
$args=func_get_args();
if($n===2)
$object=new $type($args[1]);
elseif($n===3)
$object=new $type($args[1],$args[2]);
elseif($n===4)
$object=new $type($args[1],$args[2],$args[3]);
else
{
unset($args[0]);
$class=new ReflectionClass($type);
// Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+
// $object=$class->newInstanceArgs($args);
$object=call_user_func_array(array($class,'newInstance'),$args);
}
}
else
$object=new $type;
foreach($config as $key=>$value)
$object->$key=$value;
return $object;
}
/**
* Imports a class or a directory.
*
* Importing a class is like including the corresponding class file.
* The main difference is that importing a class is much lighter because it only
* includes the class file when the class is referenced the first time.
*
* Importing a directory is equivalent to adding a directory into the PHP include path.
* If multiple directories are imported, the directories imported later will take
* precedence in class file searching (i.e., they are added to the front of the PHP include path).
*
* Path aliases are used to import a class or directory. For example,
* <ul>
* <li><code>application.components.GoogleMap</code>: import the <code>GoogleMap</code> class.</li>
* <li><code>application.components.*</code>: import the <code>components</code> directory.</li>
* </ul>
*
* The same path alias can be imported multiple times, but only the first time is effective.
* Importing a directory does not import any of its subdirectories.
*
* Starting from version 1.1.5, this method can also be used to import a class in namespace format
* (available for PHP 5.3 or above only). It is similar to importing a class in path alias format,
* except that the dot separator is replaced by the backslash separator. For example, importing
* <code>application\components\GoogleMap</code> is similar to importing <code>application.components.GoogleMap</code>.
* The difference is that the former class is using qualified name, while the latter unqualified.
*
* Note, importing a class in namespace format requires that the namespace corresponds to
* a valid path alias once backslash characters are replaced with dot characters.
* For example, the namespace <code>application\components</code> must correspond to a valid
* path alias <code>application.components</code>.
*
* @param string $alias path alias to be imported
* @param boolean $forceInclude whether to include the class file immediately. If false, the class file
* will be included only when the class is being used. This parameter is used only when
* the path alias refers to a class.
* @return string the class name or the directory that this alias refers to
* @throws CException if the alias is invalid
*/
public static function import($alias,$forceInclude=false)
{
if(isset(self::$_imports[$alias])) // previously imported
return self::$_imports[$alias];
if(class_exists($alias,false) || interface_exists($alias,false))
return self::$_imports[$alias]=$alias;
if(($pos=strrpos($alias,'\\'))!==false) // a class name in PHP 5.3 namespace format
{
$namespace=str_replace('\\','.',ltrim(substr($alias,0,$pos),'\\'));
if(($path=self::getPathOfAlias($namespace))!==false)
{
$classFile=$path.DIRECTORY_SEPARATOR.substr($alias,$pos+1).'.php';
if($forceInclude)
{
if(is_file($classFile))
require($classFile);
else
throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
self::$_imports[$alias]=$alias;
}
else
self::$classMap[$alias]=$classFile;
return $alias;
}
else
{
// try to autoload the class with an autoloader
if (class_exists($alias,true))
return self::$_imports[$alias]=$alias;
else
throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
array('{alias}'=>$namespace)));
}
}
if(($pos=strrpos($alias,'.'))===false) // a simple class name
{
// try to autoload the class with an autoloader if $forceInclude is true
if($forceInclude && (Yii::autoload($alias,true) || class_exists($alias,true)))
self::$_imports[$alias]=$alias;
return $alias;
}
$className=(string)substr($alias,$pos+1);
$isClass=$className!=='*';
if($isClass && (class_exists($className,false) || interface_exists($className,false)))
return self::$_imports[$alias]=$className;
if(($path=self::getPathOfAlias($alias))!==false)
{
if($isClass)
{
if($forceInclude)
{
if(is_file($path.'.php'))
require($path.'.php');
else
throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing PHP file and the file is readable.',array('{alias}'=>$alias)));
self::$_imports[$alias]=$className;
}
else
self::$classMap[$className]=$path.'.php';
return $className;
}
else // a directory
{
if(self::$_includePaths===null)
{
self::$_includePaths=array_unique(explode(PATH_SEPARATOR,get_include_path()));
if(($pos=array_search('.',self::$_includePaths,true))!==false)
unset(self::$_includePaths[$pos]);
}
array_unshift(self::$_includePaths,$path);
if(self::$enableIncludePath && set_include_path('.'.PATH_SEPARATOR.implode(PATH_SEPARATOR,self::$_includePaths))===false)
self::$enableIncludePath=false;
return self::$_imports[$alias]=$path;
}
}
else
throw new CException(Yii::t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
array('{alias}'=>$alias)));
}
/**
* Translates an alias into a file path.
* Note, this method does not ensure the existence of the resulting file path.
* It only checks if the root alias is valid or not.
* @param string $alias alias (e.g. system.web.CController)
* @return mixed file path corresponding to the alias, false if the alias is invalid.
*/
public static function getPathOfAlias($alias)
{
if(isset(self::$_aliases[$alias]))
return self::$_aliases[$alias];
elseif(($pos=strpos($alias,'.'))!==false)
{
$rootAlias=substr($alias,0,$pos);
if(isset(self::$_aliases[$rootAlias]))
return self::$_aliases[$alias]=rtrim(self::$_aliases[$rootAlias].DIRECTORY_SEPARATOR.str_replace('.',DIRECTORY_SEPARATOR,substr($alias,$pos+1)),'*'.DIRECTORY_SEPARATOR);
elseif(self::$_app instanceof CWebApplication)
{
if(self::$_app->findModule($rootAlias)!==null)
return self::getPathOfAlias($alias);
}
}
return false;
}
/**
* Create a path alias.
* Note, this method neither checks the existence of the path nor normalizes the path.
* @param string $alias alias to the path
* @param string $path the path corresponding to the alias. If this is null, the corresponding
* path alias will be removed.
*/
public static function setPathOfAlias($alias,$path)
{
if(empty($path))
unset(self::$_aliases[$alias]);
else
self::$_aliases[$alias]=rtrim($path,'\\/');
}
/**
* Class autoload loader.
* This method is provided to be invoked within an __autoload() magic method.
* @param string $className class name
* @param bool $classMapOnly whether to load classes via classmap only
* @return boolean whether the class has been loaded successfully
* @throws CException When class name does not match class file in debug mode.
*/
public static function autoload($className,$classMapOnly=false)
{
// use include so that the error PHP file may appear
if(isset(self::$classMap[$className]))
include(self::$classMap[$className]);
elseif(isset(self::$_coreClasses[$className]))
include(YII_PATH.self::$_coreClasses[$className]);
elseif($classMapOnly)
return false;
else
{
// include class file relying on include_path
if(strpos($className,'\\')===false) // class without namespace
{
if(self::$enableIncludePath===false)
{
foreach(self::$_includePaths as $path)
{
$classFile=$path.DIRECTORY_SEPARATOR.$className.'.php';
if(is_file($classFile))
{
include($classFile);
if(YII_DEBUG && basename(realpath($classFile))!==$className.'.php')
throw new CException(Yii::t('yii','Class name "{class}" does not match class file "{file}".', array(
'{class}'=>$className,
'{file}'=>$classFile,
)));
break;
}
}
}
else
include($className.'.php');
}
else // class name with namespace in PHP 5.3
{
$namespace=str_replace('\\','.',ltrim($className,'\\'));
if(($path=self::getPathOfAlias($namespace))!==false)
include($path.'.php');
else
return false;
}
return class_exists($className,false) || interface_exists($className,false);
}
return true;
}
/**
* Writes a trace message.
* This method will only log a message when the application is in debug mode.
* @param string $msg message to be logged
* @param string $category category of the message
* @see log
*/
public static function trace($msg,$category='application')
{
if(YII_DEBUG)
self::log($msg,CLogger::LEVEL_TRACE,$category);
}
/**
* Logs a message.
* Messages logged by this method may be retrieved via {@link CLogger::getLogs}
* and may be recorded in different media, such as file, email, database, using
* {@link CLogRouter}.
* @param string $msg message to be logged
* @param string $level level of the message (e.g. 'trace', 'warning', 'error'). It is case-insensitive.
* @param string $category category of the message (e.g. 'system.web'). It is case-insensitive.
*/
public static function log($msg,$level=CLogger::LEVEL_INFO,$category='application')
{
if(self::$_logger===null)
self::$_logger=new CLogger;
if(YII_DEBUG && YII_TRACE_LEVEL>0 && $level!==CLogger::LEVEL_PROFILE)
{
$traces=debug_backtrace();
$count=0;
foreach($traces as $trace)
{
if(isset($trace['file'],$trace['line']) && strpos($trace['file'],YII_PATH)!==0)
{
$msg.="\nin ".$trace['file'].' ('.$trace['line'].')';
if(++$count>=YII_TRACE_LEVEL)
break;
}
}
}
self::$_logger->log($msg,$level,$category);
}
/**
* Marks the beginning of a code block for profiling.
* This has to be matched with a call to {@link endProfile()} with the same token.
* The begin- and end- calls must also be properly nested, e.g.,
* <pre>
* Yii::beginProfile('block1');
* Yii::beginProfile('block2');
* Yii::endProfile('block2');
* Yii::endProfile('block1');
* </pre>
* The following sequence is not valid:
* <pre>
* Yii::beginProfile('block1');
* Yii::beginProfile('block2');
* Yii::endProfile('block1');
* Yii::endProfile('block2');
* </pre>
* @param string $token token for the code block
* @param string $category the category of this log message
* @see endProfile
*/
public static function beginProfile($token,$category='application')
{
self::log('begin:'.$token,CLogger::LEVEL_PROFILE,$category);
}
/**
* Marks the end of a code block for profiling.
* This has to be matched with a previous call to {@link beginProfile()} with the same token.
* @param string $token token for the code block
* @param string $category the category of this log message
* @see beginProfile
*/
public static function endProfile($token,$category='application')
{
self::log('end:'.$token,CLogger::LEVEL_PROFILE,$category);
}
/**
* @return CLogger message logger
*/
public static function getLogger()
{
if(self::$_logger!==null)
return self::$_logger;
else
return self::$_logger=new CLogger;
}
/**
* Sets the logger object.
* @param CLogger $logger the logger object.
* @since 1.1.8
*/
public static function setLogger($logger)
{
self::$_logger=$logger;
}
/**
* Returns a string that can be displayed on your Web page showing Powered-by-Yii information
* @return string a string that can be displayed on your Web page showing Powered-by-Yii information
*/
public static function powered()
{
return Yii::t('yii','Powered by {yii}.', array('{yii}'=>'<a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>'));
}
/**
* Translates a message to the specified language.
* This method supports choice format (see {@link CChoiceFormat}),
* i.e., the message returned will be chosen from a few candidates according to the given
* number value. This feature is mainly used to solve plural format issue in case
* a message has different plural forms in some languages.
* @param string $category message category. Please use only word letters. Note, category 'yii' is
* reserved for Yii framework core code use. See {@link CPhpMessageSource} for
* more interpretation about message category.
* @param string $message the original message
* @param array $params parameters to be applied to the message using <code>strtr</code>.
* The first parameter can be a number without key.
* And in this case, the method will call {@link CChoiceFormat::format} to choose
* an appropriate message translation.
* Starting from version 1.1.6 you can pass parameter for {@link CChoiceFormat::format}
* or plural forms format without wrapping it with array.
* This parameter is then available as <code>{n}</code> in the message translation string.
* @param string $source which message source application component to use.
* Defaults to null, meaning using 'coreMessages' for messages belonging to
* the 'yii' category and using 'messages' for the rest messages.
* @param string $language the target language. If null (default), the {@link CApplication::getLanguage application language} will be used.
* @return string the translated message
* @see CMessageSource
*/
public static function t($category,$message,$params=array(),$source=null,$language=null)
{
if(self::$_app!==null)
{
if($source===null)
$source=($category==='yii'||$category==='zii')?'coreMessages':'messages';
if(($source=self::$_app->getComponent($source))!==null)
$message=$source->translate($category,$message,$language);
}
if($params===array())
return $message;
if(!is_array($params))
$params=array($params);
if(isset($params[0])) // number choice
{
if(strpos($message,'|')!==false)
{
if(strpos($message,'#')===false)
{
$chunks=explode('|',$message);
$expressions=self::$_app->getLocale($language)->getPluralRules();
if($n=min(count($chunks),count($expressions)))
{
for($i=0;$i<$n;$i++)
$chunks[$i]=$expressions[$i].'#'.$chunks[$i];
$message=implode('|',$chunks);
}
}
$message=CChoiceFormat::format($message,$params[0]);
}
if(!isset($params['{n}']))
$params['{n}']=$params[0];
unset($params[0]);
}
return $params!==array() ? strtr($message,$params) : $message;
}
/**
* Registers a new class autoloader.
* The new autoloader will be placed before {@link autoload} and after
* any other existing autoloaders.
* @param callback $callback a valid PHP callback (function name or array($className,$methodName)).
* @param boolean $append whether to append the new autoloader after the default Yii autoloader.
* Be careful using this option as it will disable {@link enableIncludePath autoloading via include path}
* when set to true. After this the Yii autoloader can not rely on loading classes via simple include anymore
* and you have to {@link import} all classes explicitly.
*/
public static function registerAutoloader($callback, $append=false)
{
if($append)
{
self::$enableIncludePath=false;
spl_autoload_register($callback);
}
else
{
spl_autoload_unregister(array('YiiBase','autoload'));
spl_autoload_register($callback);
spl_autoload_register(array('YiiBase','autoload'));
}
}
/**
* @var array class map for core Yii classes.
* NOTE, DO NOT MODIFY THIS ARRAY MANUALLY. IF YOU CHANGE OR ADD SOME CORE CLASSES,
* PLEASE RUN 'build autoload' COMMAND TO UPDATE THIS ARRAY.
*/
private static $_coreClasses=array(
'CApplication' => '/base/CApplication.php',
'CApplicationComponent' => '/base/CApplicationComponent.php',
'CBehavior' => '/base/CBehavior.php',
'CComponent' => '/base/CComponent.php',
'CErrorEvent' => '/base/CErrorEvent.php',
'CErrorHandler' => '/base/CErrorHandler.php',
'CException' => '/base/CException.php',
'CExceptionEvent' => '/base/CExceptionEvent.php',
'CHttpException' => '/base/CHttpException.php',
'CModel' => '/base/CModel.php',
'CModelBehavior' => '/base/CModelBehavior.php',
'CModelEvent' => '/base/CModelEvent.php',
'CModule' => '/base/CModule.php',
'CSecurityManager' => '/base/CSecurityManager.php',
'CStatePersister' => '/base/CStatePersister.php',
'CApcCache' => '/caching/CApcCache.php',
'CCache' => '/caching/CCache.php',
'CDbCache' => '/caching/CDbCache.php',
'CDummyCache' => '/caching/CDummyCache.php',
'CEAcceleratorCache' => '/caching/CEAcceleratorCache.php',
'CFileCache' => '/caching/CFileCache.php',
'CMemCache' => '/caching/CMemCache.php',
'CRedisCache' => '/caching/CRedisCache.php',
'CWinCache' => '/caching/CWinCache.php',
'CXCache' => '/caching/CXCache.php',
'CZendDataCache' => '/caching/CZendDataCache.php',
'CCacheDependency' => '/caching/dependencies/CCacheDependency.php',
'CChainedCacheDependency' => '/caching/dependencies/CChainedCacheDependency.php',
'CDbCacheDependency' => '/caching/dependencies/CDbCacheDependency.php',
'CDirectoryCacheDependency' => '/caching/dependencies/CDirectoryCacheDependency.php',
'CExpressionDependency' => '/caching/dependencies/CExpressionDependency.php',
'CFileCacheDependency' => '/caching/dependencies/CFileCacheDependency.php',
'CGlobalStateCacheDependency' => '/caching/dependencies/CGlobalStateCacheDependency.php',
'CAttributeCollection' => '/collections/CAttributeCollection.php',
'CConfiguration' => '/collections/CConfiguration.php',
'CList' => '/collections/CList.php',
'CListIterator' => '/collections/CListIterator.php',
'CMap' => '/collections/CMap.php',
'CMapIterator' => '/collections/CMapIterator.php',
'CQueue' => '/collections/CQueue.php',
'CQueueIterator' => '/collections/CQueueIterator.php',
'CStack' => '/collections/CStack.php',
'CStackIterator' => '/collections/CStackIterator.php',
'CTypedList' => '/collections/CTypedList.php',
'CTypedMap' => '/collections/CTypedMap.php',
'CConsoleApplication' => '/console/CConsoleApplication.php',
'CConsoleCommand' => '/console/CConsoleCommand.php',
'CConsoleCommandBehavior' => '/console/CConsoleCommandBehavior.php',
'CConsoleCommandEvent' => '/console/CConsoleCommandEvent.php',
'CConsoleCommandRunner' => '/console/CConsoleCommandRunner.php',
'CHelpCommand' => '/console/CHelpCommand.php',
'CDbCommand' => '/db/CDbCommand.php',
'CDbConnection' => '/db/CDbConnection.php',
'CDbDataReader' => '/db/CDbDataReader.php',
'CDbException' => '/db/CDbException.php',
'CDbMigration' => '/db/CDbMigration.php',
'CDbTransaction' => '/db/CDbTransaction.php',
'CActiveFinder' => '/db/ar/CActiveFinder.php',
'CActiveRecord' => '/db/ar/CActiveRecord.php',
'CActiveRecordBehavior' => '/db/ar/CActiveRecordBehavior.php',
'CDbColumnSchema' => '/db/schema/CDbColumnSchema.php',
'CDbCommandBuilder' => '/db/schema/CDbCommandBuilder.php',
'CDbCriteria' => '/db/schema/CDbCriteria.php',
'CDbExpression' => '/db/schema/CDbExpression.php',
'CDbSchema' => '/db/schema/CDbSchema.php',
'CDbTableSchema' => '/db/schema/CDbTableSchema.php',
'CMssqlColumnSchema' => '/db/schema/mssql/CMssqlColumnSchema.php',
'CMssqlCommandBuilder' => '/db/schema/mssql/CMssqlCommandBuilder.php',
'CMssqlPdoAdapter' => '/db/schema/mssql/CMssqlPdoAdapter.php',
'CMssqlSchema' => '/db/schema/mssql/CMssqlSchema.php',
'CMssqlSqlsrvPdoAdapter' => '/db/schema/mssql/CMssqlSqlsrvPdoAdapter.php',
'CMssqlTableSchema' => '/db/schema/mssql/CMssqlTableSchema.php',
'CMysqlColumnSchema' => '/db/schema/mysql/CMysqlColumnSchema.php',
'CMysqlCommandBuilder' => '/db/schema/mysql/CMysqlCommandBuilder.php',
'CMysqlSchema' => '/db/schema/mysql/CMysqlSchema.php',
'CMysqlTableSchema' => '/db/schema/mysql/CMysqlTableSchema.php',
'COciColumnSchema' => '/db/schema/oci/COciColumnSchema.php',
'COciCommandBuilder' => '/db/schema/oci/COciCommandBuilder.php',
'COciSchema' => '/db/schema/oci/COciSchema.php',
'COciTableSchema' => '/db/schema/oci/COciTableSchema.php',
'CPgsqlColumnSchema' => '/db/schema/pgsql/CPgsqlColumnSchema.php',
'CPgsqlCommandBuilder' => '/db/schema/pgsql/CPgsqlCommandBuilder.php',
'CPgsqlSchema' => '/db/schema/pgsql/CPgsqlSchema.php',
'CPgsqlTableSchema' => '/db/schema/pgsql/CPgsqlTableSchema.php',
'CSqliteColumnSchema' => '/db/schema/sqlite/CSqliteColumnSchema.php',
'CSqliteCommandBuilder' => '/db/schema/sqlite/CSqliteCommandBuilder.php',
'CSqliteSchema' => '/db/schema/sqlite/CSqliteSchema.php',
'CChoiceFormat' => '/i18n/CChoiceFormat.php',
'CDateFormatter' => '/i18n/CDateFormatter.php',
'CDbMessageSource' => '/i18n/CDbMessageSource.php',
'CGettextMessageSource' => '/i18n/CGettextMessageSource.php',
'CLocale' => '/i18n/CLocale.php',
'CMessageSource' => '/i18n/CMessageSource.php',
'CNumberFormatter' => '/i18n/CNumberFormatter.php',
'CPhpMessageSource' => '/i18n/CPhpMessageSource.php',
'CGettextFile' => '/i18n/gettext/CGettextFile.php',
'CGettextMoFile' => '/i18n/gettext/CGettextMoFile.php',
'CGettextPoFile' => '/i18n/gettext/CGettextPoFile.php',
'CChainedLogFilter' => '/logging/CChainedLogFilter.php',
'CDbLogRoute' => '/logging/CDbLogRoute.php',
'CEmailLogRoute' => '/logging/CEmailLogRoute.php',
'CFileLogRoute' => '/logging/CFileLogRoute.php',
'CLogFilter' => '/logging/CLogFilter.php',
'CLogRoute' => '/logging/CLogRoute.php',
'CLogRouter' => '/logging/CLogRouter.php',
'CLogger' => '/logging/CLogger.php',
'CProfileLogRoute' => '/logging/CProfileLogRoute.php',
'CWebLogRoute' => '/logging/CWebLogRoute.php',
'CDateTimeParser' => '/utils/CDateTimeParser.php',
'CFileHelper' => '/utils/CFileHelper.php',
'CFormatter' => '/utils/CFormatter.php',
'CLocalizedFormatter' => '/utils/CLocalizedFormatter.php',
'CMarkdownParser' => '/utils/CMarkdownParser.php',
'CPasswordHelper' => '/utils/CPasswordHelper.php',
'CPropertyValue' => '/utils/CPropertyValue.php',
'CTimestamp' => '/utils/CTimestamp.php',
'CVarDumper' => '/utils/CVarDumper.php',
'CBooleanValidator' => '/validators/CBooleanValidator.php',
'CCaptchaValidator' => '/validators/CCaptchaValidator.php',
'CCompareValidator' => '/validators/CCompareValidator.php',
'CDateValidator' => '/validators/CDateValidator.php',
'CDefaultValueValidator' => '/validators/CDefaultValueValidator.php',
'CEmailValidator' => '/validators/CEmailValidator.php',
'CExistValidator' => '/validators/CExistValidator.php',
'CFileValidator' => '/validators/CFileValidator.php',
'CFilterValidator' => '/validators/CFilterValidator.php',
'CInlineValidator' => '/validators/CInlineValidator.php',
'CNumberValidator' => '/validators/CNumberValidator.php',
'CRangeValidator' => '/validators/CRangeValidator.php',
'CRegularExpressionValidator' => '/validators/CRegularExpressionValidator.php',
'CRequiredValidator' => '/validators/CRequiredValidator.php',
'CSafeValidator' => '/validators/CSafeValidator.php',
'CStringValidator' => '/validators/CStringValidator.php',
'CTypeValidator' => '/validators/CTypeValidator.php',
'CUniqueValidator' => '/validators/CUniqueValidator.php',
'CUnsafeValidator' => '/validators/CUnsafeValidator.php',
'CUrlValidator' => '/validators/CUrlValidator.php',
'CValidator' => '/validators/CValidator.php',
'CActiveDataProvider' => '/web/CActiveDataProvider.php',
'CArrayDataProvider' => '/web/CArrayDataProvider.php',
'CAssetManager' => '/web/CAssetManager.php',
'CBaseController' => '/web/CBaseController.php',
'CCacheHttpSession' => '/web/CCacheHttpSession.php',
'CClientScript' => '/web/CClientScript.php',
'CController' => '/web/CController.php',
'CDataProvider' => '/web/CDataProvider.php',
'CDataProviderIterator' => '/web/CDataProviderIterator.php',
'CDbHttpSession' => '/web/CDbHttpSession.php',
'CExtController' => '/web/CExtController.php',
'CFormModel' => '/web/CFormModel.php',
'CHttpCookie' => '/web/CHttpCookie.php',
'CHttpRequest' => '/web/CHttpRequest.php',
'CHttpSession' => '/web/CHttpSession.php',
'CHttpSessionIterator' => '/web/CHttpSessionIterator.php',
'COutputEvent' => '/web/COutputEvent.php',
'CPagination' => '/web/CPagination.php',
'CSort' => '/web/CSort.php',
'CSqlDataProvider' => '/web/CSqlDataProvider.php',
'CTheme' => '/web/CTheme.php',
'CThemeManager' => '/web/CThemeManager.php',
'CUploadedFile' => '/web/CUploadedFile.php',
'CUrlManager' => '/web/CUrlManager.php',
'CWebApplication' => '/web/CWebApplication.php',
'CWebModule' => '/web/CWebModule.php',
'CWidgetFactory' => '/web/CWidgetFactory.php',
'CAction' => '/web/actions/CAction.php',
'CInlineAction' => '/web/actions/CInlineAction.php',
'CViewAction' => '/web/actions/CViewAction.php',
'CAccessControlFilter' => '/web/auth/CAccessControlFilter.php',
'CAuthAssignment' => '/web/auth/CAuthAssignment.php',
'CAuthItem' => '/web/auth/CAuthItem.php',
'CAuthManager' => '/web/auth/CAuthManager.php',
'CBaseUserIdentity' => '/web/auth/CBaseUserIdentity.php',
'CDbAuthManager' => '/web/auth/CDbAuthManager.php',
'CPhpAuthManager' => '/web/auth/CPhpAuthManager.php',
'CUserIdentity' => '/web/auth/CUserIdentity.php',
'CWebUser' => '/web/auth/CWebUser.php',
'CFilter' => '/web/filters/CFilter.php',
'CFilterChain' => '/web/filters/CFilterChain.php',
'CHttpCacheFilter' => '/web/filters/CHttpCacheFilter.php',
'CInlineFilter' => '/web/filters/CInlineFilter.php',
'CForm' => '/web/form/CForm.php',
'CFormButtonElement' => '/web/form/CFormButtonElement.php',
'CFormElement' => '/web/form/CFormElement.php',
'CFormElementCollection' => '/web/form/CFormElementCollection.php',
'CFormInputElement' => '/web/form/CFormInputElement.php',
'CFormStringElement' => '/web/form/CFormStringElement.php',
'CGoogleApi' => '/web/helpers/CGoogleApi.php',
'CHtml' => '/web/helpers/CHtml.php',
'CJSON' => '/web/helpers/CJSON.php',
'CJavaScript' => '/web/helpers/CJavaScript.php',
'CJavaScriptExpression' => '/web/helpers/CJavaScriptExpression.php',
'CPradoViewRenderer' => '/web/renderers/CPradoViewRenderer.php',
'CViewRenderer' => '/web/renderers/CViewRenderer.php',
'CWebService' => '/web/services/CWebService.php',
'CWebServiceAction' => '/web/services/CWebServiceAction.php',
'CWsdlGenerator' => '/web/services/CWsdlGenerator.php',
'CActiveForm' => '/web/widgets/CActiveForm.php',
'CAutoComplete' => '/web/widgets/CAutoComplete.php',
'CClipWidget' => '/web/widgets/CClipWidget.php',
'CContentDecorator' => '/web/widgets/CContentDecorator.php',
'CFilterWidget' => '/web/widgets/CFilterWidget.php',
'CFlexWidget' => '/web/widgets/CFlexWidget.php',
'CHtmlPurifier' => '/web/widgets/CHtmlPurifier.php',
'CInputWidget' => '/web/widgets/CInputWidget.php',
'CMarkdown' => '/web/widgets/CMarkdown.php',
'CMaskedTextField' => '/web/widgets/CMaskedTextField.php',
'CMultiFileUpload' => '/web/widgets/CMultiFileUpload.php',
'COutputCache' => '/web/widgets/COutputCache.php',
'COutputProcessor' => '/web/widgets/COutputProcessor.php',
'CStarRating' => '/web/widgets/CStarRating.php',
'CTabView' => '/web/widgets/CTabView.php',
'CTextHighlighter' => '/web/widgets/CTextHighlighter.php',
'CTreeView' => '/web/widgets/CTreeView.php',
'CWidget' => '/web/widgets/CWidget.php',
'CCaptcha' => '/web/widgets/captcha/CCaptcha.php',
'CCaptchaAction' => '/web/widgets/captcha/CCaptchaAction.php',
'CBasePager' => '/web/widgets/pagers/CBasePager.php',
'CLinkPager' => '/web/widgets/pagers/CLinkPager.php',
'CListPager' => '/web/widgets/pagers/CListPager.php',
);
}
spl_autoload_register(array('YiiBase','autoload'));
require(YII_PATH.'/base/interfaces.php');
| nekulin/ontico | framework/YiiBase.php | PHP | bsd-3-clause | 35,129 |
/* -*- mode: C -*- */
/*
IGraph library.
Copyright (C) 2012 Gabor Csardi <csardi.gabor@gmail.com>
334 Harvard st, Cambridge MA, 02139 USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include <igraph.h>
int main() {
igraph_t graph;
igraph_matrix_t coords;
int i;
igraph_matrix_init(&coords, 0, 0);
for (i=0; i<10; i++) {
igraph_erdos_renyi_game(&graph, IGRAPH_ERDOS_RENYI_GNP, /*n=*/ 100,
/*p=*/ 2.0/100, IGRAPH_UNDIRECTED, /*loops=*/ 0);
igraph_layout_mds(&graph, &coords, /*dist=*/ 0, /*dim=*/ 2,
/*options=*/ 0);
igraph_destroy(&graph);
}
igraph_matrix_destroy(&coords);
return 0;
}
| hlzz/dotfiles | science/igraph-0.7.1/examples/simple/igraph_layout_merge3.c | C | bsd-3-clause | 1,338 |
#!/usr/bin/env vpython
# Copyright 2016 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.
"""A script to recover devices in a known bad state."""
import argparse
import glob
import logging
import os
import signal
import sys
import psutil
if __name__ == '__main__':
sys.path.append(
os.path.abspath(
os.path.join(os.path.dirname(__file__), '..', '..', '..')))
from devil.android import device_denylist
from devil.android import device_errors
from devil.android import device_utils
from devil.android.sdk import adb_wrapper
from devil.android.tools import device_status
from devil.android.tools import script_common
from devil.utils import logging_common
from devil.utils import lsusb
# TODO(jbudorick): Resolve this after experimenting w/ disabling the USB reset.
from devil.utils import reset_usb # pylint: disable=unused-import
logger = logging.getLogger(__name__)
from py_utils import modules_util
# Script depends on features from psutil version 2.0 or higher.
modules_util.RequireVersion(psutil, '2.0')
def KillAllAdb():
def get_all_adb():
for p in psutil.process_iter():
try:
# Retrieve all required process infos at once.
pinfo = p.as_dict(attrs=['pid', 'name', 'cmdline'])
if pinfo['name'] == 'adb':
pinfo['cmdline'] = ' '.join(pinfo['cmdline'])
yield p, pinfo
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
for sig in [signal.SIGTERM, signal.SIGQUIT, signal.SIGKILL]:
for p, pinfo in get_all_adb():
try:
pinfo['signal'] = sig
logger.info('kill %(signal)s %(pid)s (%(name)s [%(cmdline)s])', pinfo)
p.send_signal(sig)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
for _, pinfo in get_all_adb():
try:
logger.error('Unable to kill %(pid)s (%(name)s [%(cmdline)s])', pinfo)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
def TryAuth(device):
"""Uses anything in ~/.android/ that looks like a key to auth with the device.
Args:
device: The DeviceUtils device to attempt to auth.
Returns:
True if device successfully authed.
"""
possible_keys = glob.glob(os.path.join(adb_wrapper.ADB_HOST_KEYS_DIR, '*key'))
if len(possible_keys) <= 1:
logger.warning('Only %d ADB keys available. Not forcing auth.',
len(possible_keys))
return False
KillAllAdb()
adb_wrapper.AdbWrapper.StartServer(keys=possible_keys)
new_state = device.adb.GetState()
if new_state != 'device':
logger.error('Auth failed. Device %s still stuck in %s.', str(device),
new_state)
return False
# It worked! Now register the host's default ADB key on the device so we don't
# have to do all that again.
pub_key = os.path.join(adb_wrapper.ADB_HOST_KEYS_DIR, 'adbkey.pub')
if not os.path.exists(pub_key): # This really shouldn't happen.
logger.error('Default ADB key not available at %s.', pub_key)
return False
with open(pub_key) as f:
pub_key_contents = f.read()
try:
device.WriteFile(adb_wrapper.ADB_KEYS_FILE, pub_key_contents, as_root=True)
except (device_errors.CommandTimeoutError, device_errors.CommandFailedError,
device_errors.DeviceUnreachableError):
logger.exception('Unable to write default ADB key to %s.', str(device))
return False
return True
def RecoverDevice(device, denylist, should_reboot=lambda device: True):
if device_status.IsDenylisted(device.adb.GetDeviceSerial(), denylist):
logger.debug('%s is denylisted, skipping recovery.', str(device))
return
if device.adb.GetState() == 'unauthorized' and TryAuth(device):
logger.info('Successfully authed device %s!', str(device))
return
if should_reboot(device):
should_restore_root = device.HasRoot()
try:
device.WaitUntilFullyBooted(retries=0)
except (device_errors.CommandTimeoutError, device_errors.CommandFailedError,
device_errors.DeviceUnreachableError):
logger.exception(
'Failure while waiting for %s. '
'Attempting to recover.', str(device))
try:
try:
device.Reboot(block=False, timeout=5, retries=0)
except device_errors.CommandTimeoutError:
logger.warning(
'Timed out while attempting to reboot %s normally.'
'Attempting alternative reboot.', str(device))
# The device drops offline before we can grab the exit code, so
# we don't check for status.
try:
device.adb.Root()
finally:
# We are already in a failure mode, attempt to reboot regardless of
# what device.adb.Root() returns. If the sysrq reboot fails an
# exception willbe thrown at that level.
device.adb.Shell(
'echo b > /proc/sysrq-trigger',
expect_status=None,
timeout=5,
retries=0)
except (device_errors.CommandFailedError,
device_errors.DeviceUnreachableError):
logger.exception('Failed to reboot %s.', str(device))
if denylist:
denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_failure')
except device_errors.CommandTimeoutError:
logger.exception('Timed out while rebooting %s.', str(device))
if denylist:
denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_timeout')
try:
device.WaitUntilFullyBooted(
retries=0, timeout=device.REBOOT_DEFAULT_TIMEOUT)
if should_restore_root:
device.EnableRoot()
except (device_errors.CommandFailedError,
device_errors.DeviceUnreachableError):
logger.exception('Failure while waiting for %s.', str(device))
if denylist:
denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_failure')
except device_errors.CommandTimeoutError:
logger.exception('Timed out while waiting for %s.', str(device))
if denylist:
denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_timeout')
def RecoverDevices(devices, denylist, enable_usb_reset=False):
"""Attempts to recover any inoperable devices in the provided list.
Args:
devices: The list of devices to attempt to recover.
denylist: The current device denylist, which will be used then
reset.
"""
statuses = device_status.DeviceStatus(devices, denylist)
should_restart_usb = set(
status['serial'] for status in statuses
if (not status['usb_status'] or status['adb_status'] in ('offline',
'missing')))
should_restart_adb = should_restart_usb.union(
set(status['serial'] for status in statuses
if status['adb_status'] == 'unauthorized'))
should_reboot_device = should_restart_usb.union(
set(status['serial'] for status in statuses if status['denylisted']))
logger.debug('Should restart USB for:')
for d in should_restart_usb:
logger.debug(' %s', d)
logger.debug('Should restart ADB for:')
for d in should_restart_adb:
logger.debug(' %s', d)
logger.debug('Should reboot:')
for d in should_reboot_device:
logger.debug(' %s', d)
if denylist:
denylist.Reset()
if should_restart_adb:
KillAllAdb()
adb_wrapper.AdbWrapper.StartServer()
for serial in should_restart_usb:
try:
# TODO(crbug.com/642194): Resetting may be causing more harm
# (specifically, kernel panics) than it does good.
if enable_usb_reset:
reset_usb.reset_android_usb(serial)
else:
logger.warning('USB reset disabled for %s (crbug.com/642914)', serial)
except IOError:
logger.exception('Unable to reset USB for %s.', serial)
if denylist:
denylist.Extend([serial], reason='USB failure')
except device_errors.DeviceUnreachableError:
logger.exception('Unable to reset USB for %s.', serial)
if denylist:
denylist.Extend([serial], reason='offline')
device_utils.DeviceUtils.parallel(devices).pMap(
RecoverDevice,
denylist,
should_reboot=lambda device: device.serial in should_reboot_device)
def main():
parser = argparse.ArgumentParser()
logging_common.AddLoggingArguments(parser)
script_common.AddEnvironmentArguments(parser)
parser.add_argument('--denylist-file', help='Device denylist JSON file.')
parser.add_argument(
'--known-devices-file',
action='append',
default=[],
dest='known_devices_files',
help='Path to known device lists.')
parser.add_argument(
'--enable-usb-reset', action='store_true', help='Reset USB if necessary.')
args = parser.parse_args()
logging_common.InitializeLogging(args)
script_common.InitializeEnvironment(args)
denylist = (device_denylist.Denylist(args.denylist_file)
if args.denylist_file else None)
expected_devices = device_status.GetExpectedDevices(args.known_devices_files)
usb_devices = set(lsusb.get_android_devices())
devices = [
device_utils.DeviceUtils(s) for s in expected_devices.union(usb_devices)
]
RecoverDevices(devices, denylist, enable_usb_reset=args.enable_usb_reset)
if __name__ == '__main__':
sys.exit(main())
| catapult-project/catapult | devil/devil/android/tools/device_recovery.py | Python | bsd-3-clause | 9,284 |
// Copyright (c) 2012 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.
#ifndef CONTENT_COMMON_GPU_CLIENT_GPU_CHANNEL_HOST_H_
#define CONTENT_COMMON_GPU_CLIENT_GPU_CHANNEL_HOST_H_
#include <string>
#include <vector>
#include "base/atomic_sequence_num.h"
#include "base/containers/hash_tables.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/process/process.h"
#include "base/synchronization/lock.h"
#include "content/common/content_export.h"
#include "content/common/gpu/gpu_process_launch_causes.h"
#include "content/common/gpu/gpu_result_codes.h"
#include "content/common/message_router.h"
#include "gpu/config/gpu_info.h"
#include "ipc/attachment_broker.h"
#include "ipc/ipc_channel_handle.h"
#include "ipc/ipc_sync_channel.h"
#include "ipc/message_filter.h"
#include "media/video/jpeg_decode_accelerator.h"
#include "ui/events/latency_info.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/gpu_memory_buffer.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gl/gpu_preference.h"
class GURL;
class TransportTextureService;
struct GPUCreateCommandBufferConfig;
namespace base {
class MessageLoop;
class WaitableEvent;
}
namespace IPC {
class SyncMessageFilter;
}
namespace media {
class JpegDecodeAccelerator;
class VideoDecodeAccelerator;
class VideoEncodeAccelerator;
}
namespace gpu {
class GpuMemoryBufferManager;
}
namespace content {
class CommandBufferProxyImpl;
class GpuChannelHost;
struct GpuListenerInfo {
GpuListenerInfo();
~GpuListenerInfo();
base::WeakPtr<IPC::Listener> listener;
scoped_refptr<base::SingleThreadTaskRunner> task_runner;
};
struct ProxyFlushInfo {
ProxyFlushInfo();
~ProxyFlushInfo();
bool flush_pending;
int route_id;
int32 put_offset;
unsigned int flush_count;
std::vector<ui::LatencyInfo> latency_info;
};
class CONTENT_EXPORT GpuChannelHostFactory
: virtual public IPC::SupportsAttachmentBrokering {
public:
virtual ~GpuChannelHostFactory() {}
virtual bool IsMainThread() = 0;
virtual scoped_refptr<base::SingleThreadTaskRunner>
GetIOThreadTaskRunner() = 0;
virtual scoped_ptr<base::SharedMemory> AllocateSharedMemory(size_t size) = 0;
virtual CreateCommandBufferResult CreateViewCommandBuffer(
int32 surface_id,
const GPUCreateCommandBufferConfig& init_params,
int32 route_id) = 0;
};
// Encapsulates an IPC channel between the client and one GPU process.
// On the GPU process side there's a corresponding GpuChannel.
// Every method can be called on any thread with a message loop, except for the
// IO thread.
class GpuChannelHost : public IPC::Sender,
public base::RefCountedThreadSafe<GpuChannelHost> {
public:
// Must be called on the main thread (as defined by the factory).
static scoped_refptr<GpuChannelHost> Create(
GpuChannelHostFactory* factory,
const gpu::GPUInfo& gpu_info,
const IPC::ChannelHandle& channel_handle,
base::WaitableEvent* shutdown_event,
gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager);
bool IsLost() const {
DCHECK(channel_filter_.get());
return channel_filter_->IsLost();
}
// The GPU stats reported by the GPU process.
const gpu::GPUInfo& gpu_info() const { return gpu_info_; }
// IPC::Sender implementation:
bool Send(IPC::Message* msg) override;
// Set an ordering barrier. AsyncFlushes any pending barriers on other
// routes. Combines multiple OrderingBarriers into a single AsyncFlush.
void OrderingBarrier(int route_id,
int32 put_offset,
unsigned int flush_count,
const std::vector<ui::LatencyInfo>& latency_info,
bool put_offset_changed,
bool do_flush);
// Create and connect to a command buffer in the GPU process.
CommandBufferProxyImpl* CreateViewCommandBuffer(
int32 surface_id,
CommandBufferProxyImpl* share_group,
const std::vector<int32>& attribs,
const GURL& active_url,
gfx::GpuPreference gpu_preference);
// Create and connect to a command buffer in the GPU process.
CommandBufferProxyImpl* CreateOffscreenCommandBuffer(
const gfx::Size& size,
CommandBufferProxyImpl* share_group,
const std::vector<int32>& attribs,
const GURL& active_url,
gfx::GpuPreference gpu_preference);
// Creates a video decoder in the GPU process.
scoped_ptr<media::VideoDecodeAccelerator> CreateVideoDecoder(
int command_buffer_route_id);
// Creates a video encoder in the GPU process.
scoped_ptr<media::VideoEncodeAccelerator> CreateVideoEncoder(
int command_buffer_route_id);
// Creates a JPEG decoder in the GPU process.
scoped_ptr<media::JpegDecodeAccelerator> CreateJpegDecoder(
media::JpegDecodeAccelerator::Client* client);
// Destroy a command buffer created by this channel.
void DestroyCommandBuffer(CommandBufferProxyImpl* command_buffer);
// Destroy this channel. Must be called on the main thread, before
// destruction.
void DestroyChannel();
// Add a route for the current message loop.
void AddRoute(int route_id, base::WeakPtr<IPC::Listener> listener);
void RemoveRoute(int route_id);
GpuChannelHostFactory* factory() const { return factory_; }
gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager() const {
return gpu_memory_buffer_manager_;
}
// Returns a handle to the shared memory that can be sent via IPC to the
// GPU process. The caller is responsible for ensuring it is closed. Returns
// an invalid handle on failure.
base::SharedMemoryHandle ShareToGpuProcess(
base::SharedMemoryHandle source_handle);
// Reserve one unused transfer buffer ID.
int32 ReserveTransferBufferId();
// Returns a GPU memory buffer handle to the buffer that can be sent via
// IPC to the GPU process. The caller is responsible for ensuring it is
// closed. Returns an invalid handle on failure.
gfx::GpuMemoryBufferHandle ShareGpuMemoryBufferToGpuProcess(
const gfx::GpuMemoryBufferHandle& source_handle,
bool* requires_sync_point);
// Reserve one unused image ID.
int32 ReserveImageId();
// Generate a route ID guaranteed to be unique for this channel.
int32 GenerateRouteID();
private:
friend class base::RefCountedThreadSafe<GpuChannelHost>;
GpuChannelHost(GpuChannelHostFactory* factory,
const gpu::GPUInfo& gpu_info,
gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager);
~GpuChannelHost() override;
void Connect(const IPC::ChannelHandle& channel_handle,
base::WaitableEvent* shutdown_event);
bool InternalSend(IPC::Message* msg);
void InternalFlush();
// A filter used internally to route incoming messages from the IO thread
// to the correct message loop. It also maintains some shared state between
// all the contexts.
class MessageFilter : public IPC::MessageFilter {
public:
MessageFilter();
// Called on the IO thread.
void AddRoute(int route_id,
base::WeakPtr<IPC::Listener> listener,
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
// Called on the IO thread.
void RemoveRoute(int route_id);
// IPC::MessageFilter implementation
// (called on the IO thread):
bool OnMessageReceived(const IPC::Message& msg) override;
void OnChannelError() override;
// The following methods can be called on any thread.
// Whether the channel is lost.
bool IsLost() const;
private:
~MessageFilter() override;
// Threading notes: |listeners_| is only accessed on the IO thread. Every
// other field is protected by |lock_|.
typedef base::hash_map<int, GpuListenerInfo> ListenerMap;
ListenerMap listeners_;
// Protects all fields below this one.
mutable base::Lock lock_;
// Whether the channel has been lost.
bool lost_;
};
// Threading notes: all fields are constant during the lifetime of |this|
// except:
// - |next_transfer_buffer_id_|, atomic type
// - |next_image_id_|, atomic type
// - |next_route_id_|, atomic type
// - |proxies_|, protected by |context_lock_|
GpuChannelHostFactory* const factory_;
const gpu::GPUInfo gpu_info_;
scoped_refptr<MessageFilter> channel_filter_;
gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager_;
// A filter for sending messages from thread other than the main thread.
scoped_refptr<IPC::SyncMessageFilter> sync_filter_;
// Transfer buffer IDs are allocated in sequence.
base::AtomicSequenceNumber next_transfer_buffer_id_;
// Image IDs are allocated in sequence.
base::AtomicSequenceNumber next_image_id_;
// Route IDs are allocated in sequence.
base::AtomicSequenceNumber next_route_id_;
// Protects channel_ and proxies_.
mutable base::Lock context_lock_;
scoped_ptr<IPC::SyncChannel> channel_;
// Used to look up a proxy from its routing id.
typedef base::hash_map<int, CommandBufferProxyImpl*> ProxyMap;
ProxyMap proxies_;
ProxyFlushInfo flush_info_;
DISALLOW_COPY_AND_ASSIGN(GpuChannelHost);
};
} // namespace content
#endif // CONTENT_COMMON_GPU_CLIENT_GPU_CHANNEL_HOST_H_
| SaschaMester/delicium | content/common/gpu/client/gpu_channel_host.h | C | bsd-3-clause | 9,332 |
// Copyright (c) 2012 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.
#ifndef CHROME_BROWSER_CHROMEOS_INPUT_METHOD_INPUT_METHOD_MANAGER_IMPL_H_
#define CHROME_BROWSER_CHROMEOS_INPUT_METHOD_INPUT_METHOD_MANAGER_IMPL_H_
#include <stddef.h>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/macros.h"
#include "base/observer_list.h"
#include "base/threading/thread_checker.h"
#include "chrome/browser/chromeos/input_method/candidate_window_controller.h"
#include "chrome/browser/chromeos/input_method/input_method_util.h"
#include "chrome/browser/chromeos/login/ui/user_adding_screen.h"
#include "chrome/browser/profiles/profile.h"
#include "ui/base/ime/chromeos/input_method_manager.h"
#include "ui/base/ime/chromeos/input_method_whitelist.h"
#include "ui/base/ime/ime_engine_handler_interface.h"
namespace ui {
class IMEEngineHandlerInterface;
} // namespace ui
namespace chromeos {
class ComponentExtensionIMEManager;
class ComponentExtensionIMEManagerDelegate;
class InputMethodEngine;
namespace input_method {
class InputMethodDelegate;
class ImeKeyboard;
// The implementation of InputMethodManager.
class InputMethodManagerImpl : public InputMethodManager,
public CandidateWindowController::Observer,
public UserAddingScreen::Observer {
public:
class StateImpl : public InputMethodManager::State {
public:
StateImpl(InputMethodManagerImpl* manager, Profile* profile);
// Init new state as a copy of other.
void InitFrom(const StateImpl& other);
// Returns true if (manager_->state_ == this).
bool IsActive() const;
// Returns human-readable dump (for debug).
std::string Dump() const;
// Adds new input method to given list if possible
bool EnableInputMethodImpl(
const std::string& input_method_id,
std::vector<std::string>* new_active_input_method_ids) const;
// Returns true if |input_method_id| is in |active_input_method_ids|.
bool InputMethodIsActivated(const std::string& input_method_id) const;
// If |current_input_methodid_| is not in |input_method_ids|, switch to
// input_method_ids[0]. If the ID is equal to input_method_ids[N], switch to
// input_method_ids[N+1].
void SwitchToNextInputMethodInternal(
const std::vector<std::string>& input_method_ids,
const std::string& current_input_methodid);
// Returns the IDs of the subset of input methods which are active and are
// associated with |accelerator|. For example,
// { "mozc-hangul", "xkb:kr:kr104:kor" } is returned for
// ui::VKEY_DBE_SBCSCHAR if the two input methods are active.
void GetCandidateInputMethodsForAccelerator(
const ui::Accelerator& accelerator,
std::vector<std::string>* out_candidate_ids);
// Returns true if given input method requires pending extension.
bool MethodAwaitsExtensionLoad(const std::string& input_method_id) const;
// InputMethodManager::State overrides.
scoped_refptr<InputMethodManager::State> Clone() const override;
void AddInputMethodExtension(
const std::string& extension_id,
const InputMethodDescriptors& descriptors,
ui::IMEEngineHandlerInterface* instance) override;
void RemoveInputMethodExtension(const std::string& extension_id) override;
void ChangeInputMethod(const std::string& input_method_id,
bool show_message) override;
bool EnableInputMethod(
const std::string& new_active_input_method_id) override;
void EnableLoginLayouts(
const std::string& language_code,
const std::vector<std::string>& initial_layouts) override;
void EnableLockScreenLayouts() override;
void GetInputMethodExtensions(InputMethodDescriptors* result) override;
std::unique_ptr<InputMethodDescriptors> GetActiveInputMethods()
const override;
const std::vector<std::string>& GetActiveInputMethodIds() const override;
const InputMethodDescriptor* GetInputMethodFromId(
const std::string& input_method_id) const override;
size_t GetNumActiveInputMethods() const override;
void SetEnabledExtensionImes(std::vector<std::string>* ids) override;
void SetInputMethodLoginDefault() override;
void SetInputMethodLoginDefaultFromVPD(const std::string& locale,
const std::string& layout) override;
bool CanCycleInputMethod() override;
void SwitchToNextInputMethod() override;
void SwitchToPreviousInputMethod() override;
bool CanSwitchInputMethod(const ui::Accelerator& accelerator) override;
void SwitchInputMethod(const ui::Accelerator& accelerator) override;
InputMethodDescriptor GetCurrentInputMethod() const override;
bool ReplaceEnabledInputMethods(
const std::vector<std::string>& new_active_input_method_ids) override;
// ------------------------- Data members.
Profile* const profile;
// The input method which was/is selected.
InputMethodDescriptor previous_input_method;
InputMethodDescriptor current_input_method;
// The active input method ids cache.
std::vector<std::string> active_input_method_ids;
// The pending input method id for delayed 3rd party IME enabling.
std::string pending_input_method_id;
// The list of enabled extension IMEs.
std::vector<std::string> enabled_extension_imes;
// Extra input methods that have been explicitly added to the menu, such as
// those created by extension.
std::map<std::string, InputMethodDescriptor> extra_input_methods;
InputMethodManagerImpl* const manager_;
protected:
friend base::RefCounted<chromeos::input_method::InputMethodManager::State>;
~StateImpl() override;
};
// Constructs an InputMethodManager instance. The client is responsible for
// calling |SetUISessionState| in response to relevant changes in browser
// state.
InputMethodManagerImpl(std::unique_ptr<InputMethodDelegate> delegate,
bool enable_extension_loading);
~InputMethodManagerImpl() override;
// Receives notification of an InputMethodManager::UISessionState transition.
void SetUISessionState(UISessionState new_ui_session);
// InputMethodManager override:
UISessionState GetUISessionState() override;
void AddObserver(InputMethodManager::Observer* observer) override;
void AddCandidateWindowObserver(
InputMethodManager::CandidateWindowObserver* observer) override;
void AddImeMenuObserver(
InputMethodManager::ImeMenuObserver* observer) override;
void RemoveObserver(InputMethodManager::Observer* observer) override;
void RemoveCandidateWindowObserver(
InputMethodManager::CandidateWindowObserver* observer) override;
void RemoveImeMenuObserver(
InputMethodManager::ImeMenuObserver* observer) override;
std::unique_ptr<InputMethodDescriptors> GetSupportedInputMethods()
const override;
void ActivateInputMethodMenuItem(const std::string& key) override;
bool IsISOLevel5ShiftUsedByCurrentInputMethod() const override;
bool IsAltGrUsedByCurrentInputMethod() const override;
void NotifyImeMenuItemsChanged(
const std::string& engine_id,
const std::vector<InputMethodManager::MenuItem>& items) override;
// chromeos::UserAddingScreen:
void OnUserAddingStarted() override;
void OnUserAddingFinished() override;
ImeKeyboard* GetImeKeyboard() override;
InputMethodUtil* GetInputMethodUtil() override;
ComponentExtensionIMEManager* GetComponentExtensionIMEManager() override;
bool IsLoginKeyboard(const std::string& layout) const override;
bool MigrateInputMethods(std::vector<std::string>* input_method_ids) override;
scoped_refptr<InputMethodManager::State> CreateNewState(
Profile* profile) override;
scoped_refptr<InputMethodManager::State> GetActiveIMEState() override;
void SetState(scoped_refptr<InputMethodManager::State> state) override;
void ImeMenuActivationChanged(bool is_active) override;
// Sets |candidate_window_controller_|.
void SetCandidateWindowControllerForTesting(
CandidateWindowController* candidate_window_controller);
// Sets |keyboard_|.
void SetImeKeyboardForTesting(ImeKeyboard* keyboard);
// Initialize |component_extension_manager_|.
void InitializeComponentExtensionForTesting(
std::unique_ptr<ComponentExtensionIMEManagerDelegate> delegate);
private:
friend class InputMethodManagerImplTest;
// CandidateWindowController::Observer overrides:
void CandidateClicked(int index) override;
void CandidateWindowOpened() override;
void CandidateWindowClosed() override;
// Temporarily deactivates all input methods (e.g. Chinese, Japanese, Arabic)
// since they are not necessary to input a login password. Users are still
// able to use/switch active keyboard layouts (e.g. US qwerty, US dvorak,
// French).
void OnScreenLocked();
// Resumes the original state by activating input methods and/or changing the
// current input method as needed.
void OnScreenUnlocked();
// Returns true if the given input method config value is a string list
// that only contains an input method ID of a keyboard layout.
bool ContainsOnlyKeyboardLayout(const std::vector<std::string>& value);
// Creates and initializes |candidate_window_controller_| if it hasn't been
// done.
void MaybeInitializeCandidateWindowController();
// Returns Input Method that best matches given id.
const InputMethodDescriptor* LookupInputMethod(
const std::string& input_method_id,
StateImpl* state);
// Change system input method.
void ChangeInputMethodInternal(const InputMethodDescriptor& descriptor,
Profile* profile,
bool show_message,
bool notify_menu);
// Loads necessary component extensions.
// TODO(nona): Support dynamical unloading.
void LoadNecessaryComponentExtensions(StateImpl* state);
// Starts or stops the system input method framework as needed.
// (after list of enabled input methods has been updated).
// If state is active, active input method is updated.
void ReconfigureIMFramework(StateImpl* state);
// Record input method usage histograms.
void RecordInputMethodUsage(const std::string& input_method_id);
// Notifies the current input method or the list of active input method IDs
// changed.
void NotifyImeMenuListChanged();
std::unique_ptr<InputMethodDelegate> delegate_;
// The current UI session status.
UISessionState ui_session_;
// A list of objects that monitor the manager.
base::ObserverList<InputMethodManager::Observer> observers_;
base::ObserverList<CandidateWindowObserver> candidate_window_observers_;
base::ObserverList<ImeMenuObserver> ime_menu_observers_;
scoped_refptr<StateImpl> state_;
// The candidate window. This will be deleted when the APP_TERMINATING
// message is sent.
std::unique_ptr<CandidateWindowController> candidate_window_controller_;
// An object which provides miscellaneous input method utility functions. Note
// that |util_| is required to initialize |keyboard_|.
InputMethodUtil util_;
// An object which provides component extension ime management functions.
std::unique_ptr<ComponentExtensionIMEManager>
component_extension_ime_manager_;
// An object for switching XKB layouts and keyboard status like caps lock and
// auto-repeat interval.
std::unique_ptr<ImeKeyboard> keyboard_;
// Whether load IME extensions.
bool enable_extension_loading_;
// Whether the expanded IME menu is activated.
bool is_ime_menu_activated_;
// The engine map from extension_id to an engine.
typedef std::map<std::string, ui::IMEEngineHandlerInterface*> EngineMap;
typedef std::map<Profile*, EngineMap, ProfileCompare> ProfileEngineMap;
ProfileEngineMap engine_map_;
DISALLOW_COPY_AND_ASSIGN(InputMethodManagerImpl);
};
} // namespace input_method
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_INPUT_METHOD_INPUT_METHOD_MANAGER_IMPL_H_
| danakj/chromium | chrome/browser/chromeos/input_method/input_method_manager_impl.h | C | bsd-3-clause | 12,223 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Rest
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Controller_Action */
require_once 'Zend/Controller/Action.php';
/**
* An abstract class to guide implementation of action controllers for use with
* Zend_Rest_Route.
*
* @category Zend
* @package Zend_Rest
* @see Zend_Rest_Route
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Rest_Controller extends Zend_Controller_Action
{
/**
* The index action handles index/list requests; it should respond with a
* list of the requested resources.
*/
abstract public function indexAction();
/**
* The get action handles GET requests and receives an 'id' parameter; it
* should respond with the server resource state of the resource identified
* by the 'id' value.
*/
abstract public function getAction();
/**
* The head action handles HEAD requests and receives an 'id' parameter; it
* should respond with the server resource state of the resource identified
* by the 'id' value.
*/
abstract public function headAction();
/**
* The post action handles POST requests; it should accept and digest a
* POSTed resource representation and persist the resource state.
*/
abstract public function postAction();
/**
* The put action handles PUT requests and receives an 'id' parameter; it
* should update the server resource state of the resource identified by
* the 'id' value.
*/
abstract public function putAction();
/**
* The delete action handles DELETE requests and receives an 'id'
* parameter; it should update the server resource state of the resource
* identified by the 'id' value.
*/
abstract public function deleteAction();
}
| sandsmedia/zf | library/Zend/Rest/Controller.php | PHP | bsd-3-clause | 2,542 |
/*
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
*/
YUI.add('CM_NewsBinderIndex', function(Y, NAME) {
/**
* The CM_NewsBinderIndex module.
*
* @module CM_NewsBinderIndex
*/
/**
* Constructor for the Binder class.
*
* @param mojitProxy {Object} The proxy to allow the binder to interact
* with its owning mojit.
*
* @class Binder
* @constructor
*/
Y.namespace('mojito.binders')[NAME] = {
/**
* Binder initialization method, invoked after all binders on the page
* have been constructed.
*/
init: function(mojitProxy) {
var self = this;
self.mojitProxy = mojitProxy;
self.id = mojitProxy.data.get('id');
//Y.log('init()', 'debug', NAME);
mojitProxy.listen('myClickEvent', function(evt) {
//Y.log(evt);
//Y.log(self.id + ' heard a click from ' + evt.data.mojitType);
if (self.node) {
self.node.append('<p id="click' + evt.data.clickCount + '">' + self.id + ' heard a click from ' + evt.data.config.id + ' (type: ' + evt.data.mojitType + ') with the data: <b>' + evt.data.message + '</b></p>');
}
}, this);
mojitProxy.listen('anchorClickEvent', function(evt) {
//Y.log(this.id + ' heard a click from ' + evt.source.id);
if (self.node) {
self.node.addClass('alert');
}
}, this);
},
/**
* The binder method, invoked to allow the mojit to attach DOM event
* handlers.
*
* @param node {Node} The DOM node to which this mojit is attached.
*/
bind: function(node) {
this.node = node;
}
};
}, '0.0.1', {requires: []});
| 1950195/mojito | tests/func/applications/frameworkapp/common/mojits_subdir1/other_mojits/CM_News/binders/index.js | JavaScript | bsd-3-clause | 1,853 |
// Copyright 2018 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 "mojo/public/cpp/platform/platform_channel.h"
#include <cstddef>
#include <cstdint>
#include <string>
#include <tuple>
#include <utility>
#include "base/logging.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "base/win/scoped_handle.h"
#elif BUILDFLAG(IS_FUCHSIA)
#include <lib/zx/channel.h>
#include <zircon/process.h>
#include <zircon/processargs.h>
#include "base/fuchsia/fuchsia_logging.h"
#elif BUILDFLAG(IS_POSIX)
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/files/scoped_file.h"
#include "base/posix/global_descriptors.h"
#endif
#if BUILDFLAG(IS_MAC)
#include <mach/port.h>
#include "base/mac/mach_logging.h"
#include "base/mac/scoped_mach_port.h"
#endif
#if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_NACL)
#include <sys/socket.h>
#elif BUILDFLAG(IS_NACL)
#include "native_client/src/public/imc_syscalls.h"
#endif
namespace mojo {
namespace {
#if BUILDFLAG(IS_WIN)
void CreateChannel(PlatformHandle* local_endpoint,
PlatformHandle* remote_endpoint) {
std::wstring pipe_name = base::StringPrintf(
L"\\\\.\\pipe\\mojo.%lu.%lu.%I64u", ::GetCurrentProcessId(),
::GetCurrentThreadId(), base::RandUint64());
DWORD kOpenMode =
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE;
const DWORD kPipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE;
*local_endpoint = PlatformHandle(base::win::ScopedHandle(
::CreateNamedPipeW(pipe_name.c_str(), kOpenMode, kPipeMode,
1, // Max instances.
4096, // Output buffer size.
4096, // Input buffer size.
5000, // Timeout in ms.
nullptr))); // Default security descriptor.
PCHECK(local_endpoint->is_valid());
const DWORD kDesiredAccess = GENERIC_READ | GENERIC_WRITE;
// The SECURITY_ANONYMOUS flag means that the server side cannot impersonate
// the client.
DWORD kFlags =
SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS | FILE_FLAG_OVERLAPPED;
// Allow the handle to be inherited by child processes.
SECURITY_ATTRIBUTES security_attributes = {sizeof(SECURITY_ATTRIBUTES),
nullptr, TRUE};
*remote_endpoint = PlatformHandle(base::win::ScopedHandle(
::CreateFileW(pipe_name.c_str(), kDesiredAccess, 0, &security_attributes,
OPEN_EXISTING, kFlags, nullptr)));
PCHECK(remote_endpoint->is_valid());
// Since a client has connected, ConnectNamedPipe() should return zero and
// GetLastError() should return ERROR_PIPE_CONNECTED.
CHECK(!::ConnectNamedPipe(local_endpoint->GetHandle().Get(), nullptr));
PCHECK(::GetLastError() == ERROR_PIPE_CONNECTED);
}
#elif BUILDFLAG(IS_FUCHSIA)
void CreateChannel(PlatformHandle* local_endpoint,
PlatformHandle* remote_endpoint) {
zx::channel handles[2];
zx_status_t result = zx::channel::create(0, &handles[0], &handles[1]);
ZX_CHECK(result == ZX_OK, result);
*local_endpoint = PlatformHandle(std::move(handles[0]));
*remote_endpoint = PlatformHandle(std::move(handles[1]));
DCHECK(local_endpoint->is_valid());
DCHECK(remote_endpoint->is_valid());
}
#elif BUILDFLAG(IS_MAC)
void CreateChannel(PlatformHandle* local_endpoint,
PlatformHandle* remote_endpoint) {
// Mach messaging is simplex; and in order to enable full-duplex
// communication, the Mojo channel implementation performs an internal
// handshake with its peer to establish two sets of Mach receive and send
// rights. The handshake process starts with the creation of one
// PlatformChannel endpoint.
base::mac::ScopedMachReceiveRight receive;
base::mac::ScopedMachSendRight send;
// The mpl_qlimit specified here should stay in sync with
// NamedPlatformChannel.
CHECK(base::mac::CreateMachPort(&receive, &send, MACH_PORT_QLIMIT_LARGE));
// In a reverse of Mach messaging semantics, in Mojo the "local" endpoint is
// the send right, while the "remote" end is the receive right.
*local_endpoint = PlatformHandle(std::move(send));
*remote_endpoint = PlatformHandle(std::move(receive));
}
#elif BUILDFLAG(IS_POSIX)
#if BUILDFLAG(IS_ANDROID)
// Leave room for any other descriptors defined in content for example.
// TODO(https://crbug.com/676442): Consider changing base::GlobalDescriptors to
// generate a key when setting the file descriptor.
constexpr int kAndroidClientHandleDescriptor =
base::GlobalDescriptors::kBaseDescriptor + 10000;
#else
bool IsTargetDescriptorUsed(const base::FileHandleMappingVector& mapping,
int target_fd) {
for (size_t i = 0; i < mapping.size(); ++i) {
if (mapping[i].second == target_fd)
return true;
}
return false;
}
#endif
void CreateChannel(PlatformHandle* local_endpoint,
PlatformHandle* remote_endpoint) {
int fds[2];
#if BUILDFLAG(IS_NACL)
PCHECK(imc_socketpair(fds) == 0);
#else
PCHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == 0);
// Set non-blocking on both ends.
PCHECK(fcntl(fds[0], F_SETFL, O_NONBLOCK) == 0);
PCHECK(fcntl(fds[1], F_SETFL, O_NONBLOCK) == 0);
#if BUILDFLAG(IS_APPLE)
// This turns off |SIGPIPE| when writing to a closed socket, causing the call
// to fail with |EPIPE| instead. On Linux we have to use |send...()| with
// |MSG_NOSIGNAL| instead, which is not supported on Mac.
int no_sigpipe = 1;
PCHECK(setsockopt(fds[0], SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe,
sizeof(no_sigpipe)) == 0);
PCHECK(setsockopt(fds[1], SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe,
sizeof(no_sigpipe)) == 0);
#endif // BUILDFLAG(IS_APPLE)
#endif // BUILDFLAG(IS_NACL)
*local_endpoint = PlatformHandle(base::ScopedFD(fds[0]));
*remote_endpoint = PlatformHandle(base::ScopedFD(fds[1]));
DCHECK(local_endpoint->is_valid());
DCHECK(remote_endpoint->is_valid());
}
#else
#error "Unsupported platform."
#endif
} // namespace
const char PlatformChannel::kHandleSwitch[] = "mojo-platform-channel-handle";
PlatformChannel::PlatformChannel() {
PlatformHandle local_handle;
PlatformHandle remote_handle;
CreateChannel(&local_handle, &remote_handle);
local_endpoint_ = PlatformChannelEndpoint(std::move(local_handle));
remote_endpoint_ = PlatformChannelEndpoint(std::move(remote_handle));
}
PlatformChannel::PlatformChannel(PlatformChannel&& other) = default;
PlatformChannel::~PlatformChannel() = default;
PlatformChannel& PlatformChannel::operator=(PlatformChannel&& other) = default;
void PlatformChannel::PrepareToPassRemoteEndpoint(HandlePassingInfo* info,
std::string* value) {
DCHECK(value);
DCHECK(remote_endpoint_.is_valid());
#if BUILDFLAG(IS_WIN)
info->push_back(remote_endpoint_.platform_handle().GetHandle().Get());
*value = base::NumberToString(
HandleToLong(remote_endpoint_.platform_handle().GetHandle().Get()));
#elif BUILDFLAG(IS_FUCHSIA)
const uint32_t id = base::LaunchOptions::AddHandleToTransfer(
info, remote_endpoint_.platform_handle().GetHandle().get());
*value = base::NumberToString(id);
#elif BUILDFLAG(IS_ANDROID)
int fd = remote_endpoint_.platform_handle().GetFD().get();
int mapped_fd = kAndroidClientHandleDescriptor + info->size();
info->emplace_back(fd, mapped_fd);
*value = base::NumberToString(mapped_fd);
#elif BUILDFLAG(IS_MAC)
DCHECK(remote_endpoint_.platform_handle().is_mach_receive());
base::mac::ScopedMachReceiveRight receive_right =
remote_endpoint_.TakePlatformHandle().TakeMachReceiveRight();
base::MachPortsForRendezvous::key_type rendezvous_key = 0;
do {
rendezvous_key = static_cast<decltype(rendezvous_key)>(base::RandUint64());
} while (info->find(rendezvous_key) != info->end());
auto it = info->insert(std::make_pair(
rendezvous_key, base::MachRendezvousPort(std::move(receive_right))));
DCHECK(it.second) << "Failed to insert port for rendezvous.";
*value = base::NumberToString(rendezvous_key);
#elif BUILDFLAG(IS_POSIX)
// Arbitrary sanity check to ensure the loop below terminates reasonably
// quickly.
CHECK_LT(info->size(), 1000u);
// Find a suitable FD to map the remote endpoint handle to in the child
// process. This has quadratic time complexity in the size of |*info|, but
// |*info| should be very small and is usually empty.
int target_fd = base::GlobalDescriptors::kBaseDescriptor;
while (IsTargetDescriptorUsed(*info, target_fd))
++target_fd;
info->emplace_back(remote_endpoint_.platform_handle().GetFD().get(),
target_fd);
*value = base::NumberToString(target_fd);
#endif
}
void PlatformChannel::PrepareToPassRemoteEndpoint(
HandlePassingInfo* info,
base::CommandLine* command_line) {
std::string value;
PrepareToPassRemoteEndpoint(info, &value);
if (!value.empty())
command_line->AppendSwitchASCII(kHandleSwitch, value);
}
void PlatformChannel::PrepareToPassRemoteEndpoint(
base::LaunchOptions* options,
base::CommandLine* command_line) {
#if BUILDFLAG(IS_WIN)
PrepareToPassRemoteEndpoint(&options->handles_to_inherit, command_line);
#elif BUILDFLAG(IS_FUCHSIA)
PrepareToPassRemoteEndpoint(&options->handles_to_transfer, command_line);
#elif BUILDFLAG(IS_MAC)
PrepareToPassRemoteEndpoint(&options->mach_ports_for_rendezvous,
command_line);
#elif BUILDFLAG(IS_POSIX)
PrepareToPassRemoteEndpoint(&options->fds_to_remap, command_line);
#else
#error "Platform not supported."
#endif
}
void PlatformChannel::RemoteProcessLaunchAttempted() {
#if BUILDFLAG(IS_FUCHSIA)
// Unlike other platforms, Fuchsia transfers handle ownership to the new
// process, rather than duplicating it. For consistency the process-launch
// call will have consumed the handle regardless of whether launch succeeded.
DCHECK(remote_endpoint_.platform_handle().is_valid_handle());
std::ignore = remote_endpoint_.TakePlatformHandle().ReleaseHandle();
#else
remote_endpoint_.reset();
#endif
}
// static
PlatformChannelEndpoint PlatformChannel::RecoverPassedEndpointFromString(
base::StringPiece value) {
#if BUILDFLAG(IS_WIN)
int handle_value = 0;
if (value.empty() || !base::StringToInt(value, &handle_value)) {
DLOG(ERROR) << "Invalid PlatformChannel endpoint string.";
return PlatformChannelEndpoint();
}
return PlatformChannelEndpoint(
PlatformHandle(base::win::ScopedHandle(LongToHandle(handle_value))));
#elif BUILDFLAG(IS_FUCHSIA)
unsigned int handle_value = 0;
if (value.empty() || !base::StringToUint(value, &handle_value)) {
DLOG(ERROR) << "Invalid PlatformChannel endpoint string.";
return PlatformChannelEndpoint();
}
return PlatformChannelEndpoint(PlatformHandle(zx::handle(
zx_take_startup_handle(base::checked_cast<uint32_t>(handle_value)))));
#elif BUILDFLAG(IS_ANDROID)
base::GlobalDescriptors::Key key = -1;
if (value.empty() || !base::StringToUint(value, &key)) {
DLOG(ERROR) << "Invalid PlatformChannel endpoint string.";
return PlatformChannelEndpoint();
}
return PlatformChannelEndpoint(PlatformHandle(
base::ScopedFD(base::GlobalDescriptors::GetInstance()->Get(key))));
#elif BUILDFLAG(IS_MAC)
auto* client = base::MachPortRendezvousClient::GetInstance();
if (!client) {
DLOG(ERROR) << "Mach rendezvous failed.";
return PlatformChannelEndpoint();
}
uint32_t rendezvous_key = 0;
if (value.empty() || !base::StringToUint(value, &rendezvous_key)) {
DLOG(ERROR) << "Invalid PlatformChannel rendezvous key.";
return PlatformChannelEndpoint();
}
auto receive = client->TakeReceiveRight(rendezvous_key);
if (!receive.is_valid()) {
DLOG(ERROR) << "Invalid PlatformChannel receive right.";
return PlatformChannelEndpoint();
}
return PlatformChannelEndpoint(PlatformHandle(std::move(receive)));
#elif BUILDFLAG(IS_POSIX)
int fd = -1;
if (value.empty() || !base::StringToInt(value, &fd) ||
fd < base::GlobalDescriptors::kBaseDescriptor) {
DLOG(ERROR) << "Invalid PlatformChannel endpoint string.";
return PlatformChannelEndpoint();
}
return PlatformChannelEndpoint(PlatformHandle(base::ScopedFD(fd)));
#endif
}
// static
PlatformChannelEndpoint PlatformChannel::RecoverPassedEndpointFromCommandLine(
const base::CommandLine& command_line) {
return RecoverPassedEndpointFromString(
command_line.GetSwitchValueASCII(kHandleSwitch));
}
// static
bool PlatformChannel::CommandLineHasPassedEndpoint(
const base::CommandLine& command_line) {
return command_line.HasSwitch(kHandleSwitch);
}
} // namespace mojo
| chromium/chromium | mojo/public/cpp/platform/platform_channel.cc | C++ | bsd-3-clause | 13,042 |
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* Copyright (C) 2000 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) Research In Motion Limited 2011-2012. All rights reserved.
*
* 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 "core/layout/LayoutReplaced.h"
#include "core/editing/PositionWithAffinity.h"
#include "core/layout/LayoutAnalyzer.h"
#include "core/layout/LayoutBlock.h"
#include "core/layout/LayoutImage.h"
#include "core/layout/LayoutView.h"
#include "core/paint/PaintInfo.h"
#include "core/paint/PaintLayer.h"
#include "core/paint/ReplacedPainter.h"
#include "platform/LengthFunctions.h"
namespace blink {
const int LayoutReplaced::defaultWidth = 300;
const int LayoutReplaced::defaultHeight = 150;
LayoutReplaced::LayoutReplaced(Element* element)
: LayoutBox(element)
, m_intrinsicSize(defaultWidth, defaultHeight)
{
// TODO(jchaffraix): We should not set this boolean for block-level
// replaced elements (crbug.com/567964).
setIsAtomicInlineLevel(true);
}
LayoutReplaced::LayoutReplaced(Element* element, const LayoutSize& intrinsicSize)
: LayoutBox(element)
, m_intrinsicSize(intrinsicSize)
{
// TODO(jchaffraix): We should not set this boolean for block-level
// replaced elements (crbug.com/567964).
setIsAtomicInlineLevel(true);
}
LayoutReplaced::~LayoutReplaced()
{
}
void LayoutReplaced::willBeDestroyed()
{
if (!documentBeingDestroyed() && parent())
parent()->dirtyLinesFromChangedChild(this);
LayoutBox::willBeDestroyed();
}
void LayoutReplaced::styleDidChange(StyleDifference diff, const ComputedStyle* oldStyle)
{
LayoutBox::styleDidChange(diff, oldStyle);
bool hadStyle = (oldStyle != 0);
float oldZoom = hadStyle ? oldStyle->effectiveZoom() : ComputedStyle::initialZoom();
if (style() && style()->effectiveZoom() != oldZoom)
intrinsicSizeChanged();
}
void LayoutReplaced::layout()
{
ASSERT(needsLayout());
LayoutAnalyzer::Scope analyzer(*this);
LayoutRect oldContentRect = replacedContentRect();
setHeight(minimumReplacedHeight());
updateLogicalWidth();
updateLogicalHeight();
m_overflow.clear();
addVisualEffectOverflow();
updateLayerTransformAfterLayout();
invalidateBackgroundObscurationStatus();
clearNeedsLayout();
if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled() && replacedContentRect() != oldContentRect)
setShouldDoFullPaintInvalidation();
}
void LayoutReplaced::intrinsicSizeChanged()
{
int scaledWidth = static_cast<int>(defaultWidth * style()->effectiveZoom());
int scaledHeight = static_cast<int>(defaultHeight * style()->effectiveZoom());
m_intrinsicSize = LayoutSize(scaledWidth, scaledHeight);
setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(LayoutInvalidationReason::SizeChanged);
}
void LayoutReplaced::paint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset) const
{
ReplacedPainter(*this).paint(paintInfo, paintOffset);
}
bool LayoutReplaced::shouldPaint(const PaintInfo& paintInfo, const LayoutPoint& paintOffset) const
{
if (paintInfo.phase != PaintPhaseForeground && !shouldPaintSelfOutline(paintInfo.phase)
&& paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseMask && paintInfo.phase != PaintPhaseClippingMask)
return false;
if (!paintInfo.shouldPaintWithinRoot(this))
return false;
// if we're invisible or haven't received a layout yet, then just bail.
if (style()->visibility() != VISIBLE)
return false;
LayoutRect paintRect(visualOverflowRect());
paintRect.unite(localSelectionRect());
paintRect.moveBy(paintOffset + location());
if (!paintInfo.cullRect().intersectsCullRect(paintRect))
return false;
return true;
}
bool LayoutReplaced::hasReplacedLogicalHeight() const
{
if (style()->logicalHeight().isAuto())
return false;
if (style()->logicalHeight().isSpecified()) {
if (hasAutoHeightOrContainingBlockWithAutoHeight())
return false;
return true;
}
if (style()->logicalHeight().isIntrinsic())
return true;
return false;
}
bool LayoutReplaced::needsPreferredWidthsRecalculation() const
{
// If the height is a percentage and the width is auto, then the containingBlocks's height changing can cause
// this node to change it's preferred width because it maintains aspect ratio.
return hasRelativeLogicalHeight() && style()->logicalWidth().isAuto() && !hasAutoHeightOrContainingBlockWithAutoHeight();
}
static inline bool layoutObjectHasAspectRatio(const LayoutObject* layoutObject)
{
ASSERT(layoutObject);
return layoutObject->isImage() || layoutObject->isCanvas() || layoutObject->isVideo();
}
void LayoutReplaced::computeAspectRatioInformationForLayoutBox(LayoutBox* contentLayoutObject, FloatSize& constrainedSize, double& intrinsicRatio) const
{
FloatSize intrinsicSize;
if (contentLayoutObject) {
contentLayoutObject->computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
// Handle zoom & vertical writing modes here, as the embedded document doesn't know about them.
intrinsicSize.scale(style()->effectiveZoom());
if (isLayoutImage())
intrinsicSize.scale(toLayoutImage(this)->imageDevicePixelRatio());
// Update our intrinsic size to match what the content layoutObject has computed, so that when we
// constrain the size below, the correct intrinsic size will be obtained for comparison against
// min and max widths.
if (intrinsicRatio && !intrinsicSize.isEmpty())
m_intrinsicSize = LayoutSize(intrinsicSize);
if (!isHorizontalWritingMode()) {
if (intrinsicRatio)
intrinsicRatio = 1 / intrinsicRatio;
intrinsicSize = intrinsicSize.transposedSize();
}
} else {
computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio);
if (intrinsicRatio && !intrinsicSize.isEmpty())
m_intrinsicSize = LayoutSize(isHorizontalWritingMode() ? intrinsicSize : intrinsicSize.transposedSize());
}
// Now constrain the intrinsic size along each axis according to minimum and maximum width/heights along the
// opposite axis. So for example a maximum width that shrinks our width will result in the height we compute here
// having to shrink in order to preserve the aspect ratio. Because we compute these values independently along
// each axis, the final returned size may in fact not preserve the aspect ratio.
// FIXME: In the long term, it might be better to just return this code more to the way it used to be before this
// function was added, since all it has done is make the code more unclear.
constrainedSize = intrinsicSize;
if (intrinsicRatio && !intrinsicSize.isEmpty() && style()->logicalWidth().isAuto() && style()->logicalHeight().isAuto()) {
// We can't multiply or divide by 'intrinsicRatio' here, it breaks tests, like fast/images/zoomed-img-size.html, which
// can only be fixed once subpixel precision is available for things like intrinsicWidth/Height - which include zoom!
constrainedSize.setWidth(LayoutBox::computeReplacedLogicalHeight() * intrinsicSize.width() / intrinsicSize.height());
constrainedSize.setHeight(LayoutBox::computeReplacedLogicalWidth() * intrinsicSize.height() / intrinsicSize.width());
}
}
LayoutRect LayoutReplaced::replacedContentRect(const LayoutSize* overriddenIntrinsicSize) const
{
LayoutRect contentRect = contentBoxRect();
ObjectFit objectFit = style()->objectFit();
if (objectFit == ObjectFitFill && style()->objectPosition() == ComputedStyle::initialObjectPosition()) {
return contentRect;
}
// TODO(davve): intrinsicSize doubles as both intrinsic size and intrinsic ratio. In the case of
// SVG images this isn't correct since they can have intrinsic ratio but no intrinsic size. In
// order to maintain aspect ratio, the intrinsic size for SVG might be faked from the aspect
// ratio, see SVGImage::containerSize().
LayoutSize intrinsicSize = overriddenIntrinsicSize ? *overriddenIntrinsicSize : this->intrinsicSize();
if (!intrinsicSize.width() || !intrinsicSize.height())
return contentRect;
LayoutRect finalRect = contentRect;
switch (objectFit) {
case ObjectFitContain:
case ObjectFitScaleDown:
case ObjectFitCover:
finalRect.setSize(finalRect.size().fitToAspectRatio(intrinsicSize, objectFit == ObjectFitCover ? AspectRatioFitGrow : AspectRatioFitShrink));
if (objectFit != ObjectFitScaleDown || finalRect.width() <= intrinsicSize.width())
break;
// fall through
case ObjectFitNone:
finalRect.setSize(intrinsicSize);
break;
case ObjectFitFill:
break;
default:
ASSERT_NOT_REACHED();
}
LayoutUnit xOffset = minimumValueForLength(style()->objectPosition().x(), contentRect.width() - finalRect.width());
LayoutUnit yOffset = minimumValueForLength(style()->objectPosition().y(), contentRect.height() - finalRect.height());
finalRect.move(xOffset, yOffset);
return finalRect;
}
void LayoutReplaced::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
{
// If there's an embeddedContentBox() of a remote, referenced document available, this code-path should never be used.
ASSERT(!embeddedContentBox());
intrinsicSize = FloatSize(intrinsicLogicalWidth().toFloat(), intrinsicLogicalHeight().toFloat());
// Figure out if we need to compute an intrinsic ratio.
if (intrinsicSize.isEmpty() || !layoutObjectHasAspectRatio(this))
return;
intrinsicRatio = intrinsicSize.width() / intrinsicSize.height();
}
LayoutUnit LayoutReplaced::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
{
if (style()->logicalWidth().isSpecified() || style()->logicalWidth().isIntrinsic())
return computeReplacedLogicalWidthRespectingMinMaxWidth(computeReplacedLogicalWidthUsing(MainOrPreferredSize, style()->logicalWidth()), shouldComputePreferred);
LayoutBox* contentLayoutObject = embeddedContentBox();
// 10.3.2 Inline, replaced elements: http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width
double intrinsicRatio = 0;
FloatSize constrainedSize;
computeAspectRatioInformationForLayoutBox(contentLayoutObject, constrainedSize, intrinsicRatio);
if (style()->logicalWidth().isAuto()) {
bool computedHeightIsAuto = hasAutoHeightOrContainingBlockWithAutoHeight();
bool hasIntrinsicWidth = constrainedSize.width() > 0;
// If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic width, then that intrinsic width is the used value of 'width'.
if (computedHeightIsAuto && hasIntrinsicWidth)
return computeReplacedLogicalWidthRespectingMinMaxWidth(constrainedSize.width(), shouldComputePreferred);
bool hasIntrinsicHeight = constrainedSize.height() > 0;
if (intrinsicRatio) {
// If 'height' and 'width' both have computed values of 'auto' and the element has no intrinsic width, but does have an intrinsic height and intrinsic ratio;
// or if 'width' has a computed value of 'auto', 'height' has some other computed value, and the element does have an intrinsic ratio; then the used value
// of 'width' is: (used height) * (intrinsic ratio)
if (intrinsicRatio && ((computedHeightIsAuto && !hasIntrinsicWidth && hasIntrinsicHeight) || !computedHeightIsAuto)) {
LayoutUnit logicalHeight = computeReplacedLogicalHeight();
return computeReplacedLogicalWidthRespectingMinMaxWidth(logicalHeight * intrinsicRatio, shouldComputePreferred);
}
// If 'height' and 'width' both have computed values of 'auto' and the element has an intrinsic ratio but no intrinsic height or width, then the used value of
// 'width' is undefined in CSS 2.1. However, it is suggested that, if the containing block's width does not itself depend on the replaced element's width, then
// the used value of 'width' is calculated from the constraint equation used for block-level, non-replaced elements in normal flow.
if (computedHeightIsAuto && !hasIntrinsicWidth && !hasIntrinsicHeight) {
if (shouldComputePreferred == ComputePreferred)
return 0;
// The aforementioned 'constraint equation' used for block-level, non-replaced elements in normal flow:
// 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
LayoutUnit logicalWidth = containingBlock()->availableLogicalWidth();
// This solves above equation for 'width' (== logicalWidth).
LayoutUnit marginStart = minimumValueForLength(style()->marginStart(), logicalWidth);
LayoutUnit marginEnd = minimumValueForLength(style()->marginEnd(), logicalWidth);
logicalWidth = std::max<LayoutUnit>(0, logicalWidth - (marginStart + marginEnd + (size().width() - clientWidth())));
return computeReplacedLogicalWidthRespectingMinMaxWidth(logicalWidth, shouldComputePreferred);
}
}
// Otherwise, if 'width' has a computed value of 'auto', and the element has an intrinsic width, then that intrinsic width is the used value of 'width'.
if (hasIntrinsicWidth)
return computeReplacedLogicalWidthRespectingMinMaxWidth(constrainedSize.width(), shouldComputePreferred);
// Otherwise, if 'width' has a computed value of 'auto', but none of the conditions above are met, then the used value of 'width' becomes 300px. If 300px is too
// wide to fit the device, UAs should use the width of the largest rectangle that has a 2:1 ratio and fits the device instead.
// Note: We fall through and instead return intrinsicLogicalWidth() here - to preserve existing WebKit behavior, which might or might not be correct, or desired.
// Changing this to return cDefaultWidth, will affect lots of test results. Eg. some tests assume that a blank <img> tag (which implies width/height=auto)
// has no intrinsic size, which is wrong per CSS 2.1, but matches our behavior since a long time.
}
return computeReplacedLogicalWidthRespectingMinMaxWidth(intrinsicLogicalWidth(), shouldComputePreferred);
}
LayoutUnit LayoutReplaced::computeReplacedLogicalHeight() const
{
// 10.5 Content height: the 'height' property: http://www.w3.org/TR/CSS21/visudet.html#propdef-height
if (hasReplacedLogicalHeight())
return computeReplacedLogicalHeightRespectingMinMaxHeight(computeReplacedLogicalHeightUsing(MainOrPreferredSize, style()->logicalHeight()));
LayoutBox* contentLayoutObject = embeddedContentBox();
// 10.6.2 Inline, replaced elements: http://www.w3.org/TR/CSS21/visudet.html#inline-replaced-height
double intrinsicRatio = 0;
FloatSize constrainedSize;
computeAspectRatioInformationForLayoutBox(contentLayoutObject, constrainedSize, intrinsicRatio);
bool widthIsAuto = style()->logicalWidth().isAuto();
bool hasIntrinsicHeight = constrainedSize.height() > 0;
// If 'height' and 'width' both have computed values of 'auto' and the element also has an intrinsic height, then that intrinsic height is the used value of 'height'.
if (widthIsAuto && hasIntrinsicHeight)
return computeReplacedLogicalHeightRespectingMinMaxHeight(constrainedSize.height());
// Otherwise, if 'height' has a computed value of 'auto', and the element has an intrinsic ratio then the used value of 'height' is:
// (used width) / (intrinsic ratio)
if (intrinsicRatio)
return computeReplacedLogicalHeightRespectingMinMaxHeight(availableLogicalWidth() / intrinsicRatio);
// Otherwise, if 'height' has a computed value of 'auto', and the element has an intrinsic height, then that intrinsic height is the used value of 'height'.
if (hasIntrinsicHeight)
return computeReplacedLogicalHeightRespectingMinMaxHeight(constrainedSize.height());
// Otherwise, if 'height' has a computed value of 'auto', but none of the conditions above are met, then the used value of 'height' must be set to the height
// of the largest rectangle that has a 2:1 ratio, has a height not greater than 150px, and has a width not greater than the device width.
return computeReplacedLogicalHeightRespectingMinMaxHeight(intrinsicLogicalHeight());
}
void LayoutReplaced::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
{
minLogicalWidth = maxLogicalWidth = intrinsicLogicalWidth();
}
void LayoutReplaced::computePreferredLogicalWidths()
{
ASSERT(preferredLogicalWidthsDirty());
// We cannot resolve some logical width here (i.e. percent, fill-available or fit-content)
// as the available logical width may not be set on our containing block.
const Length& logicalWidth = style()->logicalWidth();
if (logicalWidth.hasPercent() || logicalWidth.isFillAvailable() || logicalWidth.isFitContent())
computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
else
m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = computeReplacedLogicalWidth(ComputePreferred);
const ComputedStyle& styleToUse = styleRef();
if (styleToUse.logicalWidth().hasPercent() || styleToUse.logicalMaxWidth().hasPercent())
m_minPreferredLogicalWidth = 0;
if (styleToUse.logicalMinWidth().isFixed() && styleToUse.logicalMinWidth().value() > 0) {
m_maxPreferredLogicalWidth = std::max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMinWidth().value()));
m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMinWidth().value()));
}
if (styleToUse.logicalMaxWidth().isFixed()) {
m_maxPreferredLogicalWidth = std::min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMaxWidth().value()));
m_minPreferredLogicalWidth = std::min(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMaxWidth().value()));
}
LayoutUnit borderAndPadding = borderAndPaddingLogicalWidth();
m_minPreferredLogicalWidth += borderAndPadding;
m_maxPreferredLogicalWidth += borderAndPadding;
clearPreferredLogicalWidthsDirty();
}
PositionWithAffinity LayoutReplaced::positionForPoint(const LayoutPoint& point)
{
// FIXME: This code is buggy if the replaced element is relative positioned.
InlineBox* box = inlineBoxWrapper();
RootInlineBox* rootBox = box ? &box->root() : 0;
LayoutUnit top = rootBox ? rootBox->selectionTop() : logicalTop();
LayoutUnit bottom = rootBox ? rootBox->selectionBottom() : logicalBottom();
LayoutUnit blockDirectionPosition = isHorizontalWritingMode() ? point.y() + location().y() : point.x() + location().x();
LayoutUnit lineDirectionPosition = isHorizontalWritingMode() ? point.x() + location().x() : point.y() + location().y();
if (blockDirectionPosition < top)
return createPositionWithAffinity(caretMinOffset()); // coordinates are above
if (blockDirectionPosition >= bottom)
return createPositionWithAffinity(caretMaxOffset()); // coordinates are below
if (node()) {
if (lineDirectionPosition <= logicalLeft() + (logicalWidth() / 2))
return createPositionWithAffinity(0);
return createPositionWithAffinity(1);
}
return LayoutBox::positionForPoint(point);
}
LayoutRect LayoutReplaced::selectionRectForPaintInvalidation(const LayoutBoxModelObject* paintInvalidationContainer) const
{
ASSERT(!needsLayout());
LayoutRect rect = localSelectionRect();
if (rect.isEmpty())
return rect;
mapToVisibleRectInAncestorSpace(paintInvalidationContainer, rect, 0);
// FIXME: groupedMapping() leaks the squashing abstraction.
if (paintInvalidationContainer->layer()->groupedMapping())
PaintLayer::mapRectToPaintBackingCoordinates(paintInvalidationContainer, rect);
return rect;
}
LayoutRect LayoutReplaced::localSelectionRect() const
{
if (selectionState() == SelectionNone)
return LayoutRect();
if (!inlineBoxWrapper()) {
// We're a block-level replaced element. Just return our own dimensions.
return LayoutRect(LayoutPoint(), size());
}
RootInlineBox& root = inlineBoxWrapper()->root();
LayoutUnit newLogicalTop = root.block().style()->isFlippedBlocksWritingMode() ? inlineBoxWrapper()->logicalBottom() - root.selectionBottom() : root.selectionTop() - inlineBoxWrapper()->logicalTop();
if (root.block().style()->isHorizontalWritingMode())
return LayoutRect(0, newLogicalTop, size().width(), root.selectionHeight());
return LayoutRect(newLogicalTop, 0, root.selectionHeight(), size().height());
}
void LayoutReplaced::setSelectionState(SelectionState state)
{
// The selection state for our containing block hierarchy is updated by the base class call.
LayoutBox::setSelectionState(state);
if (!inlineBoxWrapper())
return;
// We only include the space below the baseline in our layer's cached paint invalidation rect if the
// image is selected. Since the selection state has changed update the rect.
if (hasLayer())
setPreviousPaintInvalidationRect(boundsRectForPaintInvalidation(containerForPaintInvalidation()));
if (canUpdateSelectionOnRootLineBoxes())
inlineBoxWrapper()->root().setHasSelectedChildren(state != SelectionNone);
}
}
| js0701/chromium-crosswalk | third_party/WebKit/Source/core/layout/LayoutReplaced.cpp | C++ | bsd-3-clause | 22,775 |
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRWBuffer.h"
#include "SkMakeUnique.h"
#include "SkMalloc.h"
#include "SkStream.h"
#include "SkTo.h"
#include <atomic>
#include <new>
// Force small chunks to be a page's worth
static const size_t kMinAllocSize = 4096;
struct SkBufferBlock {
SkBufferBlock* fNext; // updated by the writer
size_t fUsed; // updated by the writer
const size_t fCapacity;
SkBufferBlock(size_t capacity) : fNext(nullptr), fUsed(0), fCapacity(capacity) {}
const void* startData() const { return this + 1; }
size_t avail() const { return fCapacity - fUsed; }
void* availData() { return (char*)this->startData() + fUsed; }
static SkBufferBlock* Alloc(size_t length) {
size_t capacity = LengthToCapacity(length);
void* buffer = sk_malloc_throw(sizeof(SkBufferBlock) + capacity);
return new (buffer) SkBufferBlock(capacity);
}
// Return number of bytes actually appended. Important that we always completely this block
// before spilling into the next, since the reader uses fCapacity to know how many it can read.
//
size_t append(const void* src, size_t length) {
this->validate();
size_t amount = SkTMin(this->avail(), length);
memcpy(this->availData(), src, amount);
fUsed += amount;
this->validate();
return amount;
}
// Do not call in the reader thread, since the writer may be updating fUsed.
// (The assertion is still true, but TSAN still may complain about its raciness.)
void validate() const {
#ifdef SK_DEBUG
SkASSERT(fCapacity > 0);
SkASSERT(fUsed <= fCapacity);
#endif
}
private:
static size_t LengthToCapacity(size_t length) {
const size_t minSize = kMinAllocSize - sizeof(SkBufferBlock);
return SkTMax(length, minSize);
}
};
struct SkBufferHead {
mutable std::atomic<int32_t> fRefCnt;
SkBufferBlock fBlock;
SkBufferHead(size_t capacity) : fRefCnt(1), fBlock(capacity) {}
static size_t LengthToCapacity(size_t length) {
const size_t minSize = kMinAllocSize - sizeof(SkBufferHead);
return SkTMax(length, minSize);
}
static SkBufferHead* Alloc(size_t length) {
size_t capacity = LengthToCapacity(length);
size_t size = sizeof(SkBufferHead) + capacity;
void* buffer = sk_malloc_throw(size);
return new (buffer) SkBufferHead(capacity);
}
void ref() const {
SkAssertResult(fRefCnt.fetch_add(+1, std::memory_order_relaxed));
}
void unref() const {
// A release here acts in place of all releases we "should" have been doing in ref().
int32_t oldRefCnt = fRefCnt.fetch_add(-1, std::memory_order_acq_rel);
SkASSERT(oldRefCnt);
if (1 == oldRefCnt) {
// Like unique(), the acquire is only needed on success.
SkBufferBlock* block = fBlock.fNext;
sk_free((void*)this);
while (block) {
SkBufferBlock* next = block->fNext;
sk_free(block);
block = next;
}
}
}
void validate(size_t minUsed, const SkBufferBlock* tail = nullptr) const {
#ifdef SK_DEBUG
SkASSERT(fRefCnt.load(std::memory_order_relaxed) > 0);
size_t totalUsed = 0;
const SkBufferBlock* block = &fBlock;
const SkBufferBlock* lastBlock = block;
while (block) {
block->validate();
totalUsed += block->fUsed;
lastBlock = block;
block = block->fNext;
}
SkASSERT(minUsed <= totalUsed);
if (tail) {
SkASSERT(tail == lastBlock);
}
#endif
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////
// The reader can only access block.fCapacity (which never changes), and cannot access
// block.fUsed, which may be updated by the writer.
//
SkROBuffer::SkROBuffer(const SkBufferHead* head, size_t available, const SkBufferBlock* tail)
: fHead(head), fAvailable(available), fTail(tail)
{
if (head) {
fHead->ref();
SkASSERT(available > 0);
head->validate(available, tail);
} else {
SkASSERT(0 == available);
SkASSERT(!tail);
}
}
SkROBuffer::~SkROBuffer() {
if (fHead) {
fHead->unref();
}
}
SkROBuffer::Iter::Iter(const SkROBuffer* buffer) {
this->reset(buffer);
}
SkROBuffer::Iter::Iter(const sk_sp<SkROBuffer>& buffer) {
this->reset(buffer.get());
}
void SkROBuffer::Iter::reset(const SkROBuffer* buffer) {
fBuffer = buffer;
if (buffer && buffer->fHead) {
fBlock = &buffer->fHead->fBlock;
fRemaining = buffer->fAvailable;
} else {
fBlock = nullptr;
fRemaining = 0;
}
}
const void* SkROBuffer::Iter::data() const {
return fRemaining ? fBlock->startData() : nullptr;
}
size_t SkROBuffer::Iter::size() const {
if (!fBlock) {
return 0;
}
return SkTMin(fBlock->fCapacity, fRemaining);
}
bool SkROBuffer::Iter::next() {
if (fRemaining) {
fRemaining -= this->size();
if (fBuffer->fTail == fBlock) {
// There are more blocks, but fBuffer does not know about them.
SkASSERT(0 == fRemaining);
fBlock = nullptr;
} else {
fBlock = fBlock->fNext;
}
}
return fRemaining != 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
SkRWBuffer::SkRWBuffer(size_t initialCapacity) : fHead(nullptr), fTail(nullptr), fTotalUsed(0) {
if (initialCapacity) {
fHead = SkBufferHead::Alloc(initialCapacity);
fTail = &fHead->fBlock;
}
}
SkRWBuffer::~SkRWBuffer() {
this->validate();
if (fHead) {
fHead->unref();
}
}
// It is important that we always completely fill the current block before spilling over to the
// next, since our reader will be using fCapacity (min'd against its total available) to know how
// many bytes to read from a given block.
//
void SkRWBuffer::append(const void* src, size_t length, size_t reserve) {
this->validate();
if (0 == length) {
return;
}
fTotalUsed += length;
if (nullptr == fHead) {
fHead = SkBufferHead::Alloc(length + reserve);
fTail = &fHead->fBlock;
}
size_t written = fTail->append(src, length);
SkASSERT(written <= length);
src = (const char*)src + written;
length -= written;
if (length) {
SkBufferBlock* block = SkBufferBlock::Alloc(length + reserve);
fTail->fNext = block;
fTail = block;
written = fTail->append(src, length);
SkASSERT(written == length);
}
this->validate();
}
#ifdef SK_DEBUG
void SkRWBuffer::validate() const {
if (fHead) {
fHead->validate(fTotalUsed, fTail);
} else {
SkASSERT(nullptr == fTail);
SkASSERT(0 == fTotalUsed);
}
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////
class SkROBufferStreamAsset : public SkStreamAsset {
void validate() const {
#ifdef SK_DEBUG
SkASSERT(fGlobalOffset <= fBuffer->size());
SkASSERT(fLocalOffset <= fIter.size());
SkASSERT(fLocalOffset <= fGlobalOffset);
#endif
}
#ifdef SK_DEBUG
class AutoValidate {
SkROBufferStreamAsset* fStream;
public:
AutoValidate(SkROBufferStreamAsset* stream) : fStream(stream) { stream->validate(); }
~AutoValidate() { fStream->validate(); }
};
#define AUTO_VALIDATE AutoValidate av(this);
#else
#define AUTO_VALIDATE
#endif
public:
SkROBufferStreamAsset(sk_sp<SkROBuffer> buffer) : fBuffer(std::move(buffer)), fIter(fBuffer) {
fGlobalOffset = fLocalOffset = 0;
}
size_t getLength() const override { return fBuffer->size(); }
bool rewind() override {
AUTO_VALIDATE
fIter.reset(fBuffer.get());
fGlobalOffset = fLocalOffset = 0;
return true;
}
size_t read(void* dst, size_t request) override {
AUTO_VALIDATE
size_t bytesRead = 0;
for (;;) {
size_t size = fIter.size();
SkASSERT(fLocalOffset <= size);
size_t avail = SkTMin(size - fLocalOffset, request - bytesRead);
if (dst) {
memcpy(dst, (const char*)fIter.data() + fLocalOffset, avail);
dst = (char*)dst + avail;
}
bytesRead += avail;
fLocalOffset += avail;
SkASSERT(bytesRead <= request);
if (bytesRead == request) {
break;
}
// If we get here, we've exhausted the current iter
SkASSERT(fLocalOffset == size);
fLocalOffset = 0;
if (!fIter.next()) {
break; // ran out of data
}
}
fGlobalOffset += bytesRead;
SkASSERT(fGlobalOffset <= fBuffer->size());
return bytesRead;
}
bool isAtEnd() const override {
return fBuffer->size() == fGlobalOffset;
}
size_t getPosition() const override {
return fGlobalOffset;
}
bool seek(size_t position) override {
AUTO_VALIDATE
if (position < fGlobalOffset) {
this->rewind();
}
(void)this->skip(position - fGlobalOffset);
return true;
}
bool move(long offset) override{
AUTO_VALIDATE
offset += fGlobalOffset;
if (offset <= 0) {
this->rewind();
} else {
(void)this->seek(SkToSizeT(offset));
}
return true;
}
private:
SkStreamAsset* onDuplicate() const override {
return new SkROBufferStreamAsset(fBuffer);
}
SkStreamAsset* onFork() const override {
auto clone = this->duplicate();
clone->seek(this->getPosition());
return clone.release();
}
sk_sp<SkROBuffer> fBuffer;
SkROBuffer::Iter fIter;
size_t fLocalOffset;
size_t fGlobalOffset;
};
std::unique_ptr<SkStreamAsset> SkRWBuffer::makeStreamSnapshot() const {
return skstd::make_unique<SkROBufferStreamAsset>(this->makeROBufferSnapshot());
}
| Hikari-no-Tenshi/android_external_skia | src/core/SkRWBuffer.cpp | C++ | bsd-3-clause | 10,413 |