Пример #1
0
Mutex::Mutex() {
  hMutex = CreateEvent(NULL, FALSE, TRUE, NULL);
  if (hMutex == NULL) {
    throw Exception();
  }
}
Пример #2
0
/** get the acceleration value of the MarkersReference */
void MarkersReference::getAccelerationValues(const SimTK::State &s, SimTK::Array_<Vec3> &accValues) const
{
    throw Exception("MarkersReference: getAccelerationValues not implemented.");
}
Пример #3
0
static bool HHVM_METHOD(Collator, sortWithSortKeys, VRefParam arr) {
  FETCH_COL(data, this_, false);
  data->clearError();

  if (!arr.isArray()) {
    return true;
  }

  Array hash = arr.toArray();
  if (hash.size() == 0) {
    return true;
  }

  // Preallocate sort keys buffer
  size_t sortKeysOffset = 0;
  size_t sortKeysLength = DEF_SORT_KEYS_BUF_SIZE;
  char*  sortKeys = (char*)req::malloc(sortKeysLength);
  if (!sortKeys) {
    throw Exception("Out of memory");
  }
  SCOPE_EXIT{ req::free(sortKeys); };

  // Preallocate index buffer
  size_t sortIndexPos = 0;
  size_t sortIndexLength = DEF_SORT_KEYS_INDX_BUF_SIZE;
  auto   sortIndex = (collator_sort_key_index_t*)req::malloc(
                  sortIndexLength * sizeof(collator_sort_key_index_t));
  if (!sortIndex) {
    throw Exception("Out of memory");
  }
  SCOPE_EXIT{ req::free(sortIndex); };

  // Translate input hash to sortable index
  auto pos_limit = hash->iter_end();
  for (ssize_t pos = hash->iter_begin(); pos != pos_limit;
       pos = hash->iter_advance(pos)) {
    Variant val(hash->getValue(pos));

    // Convert to UTF16
    icu::UnicodeString strval;
    if (val.isString()) {
      UErrorCode error = U_ZERO_ERROR;
      strval = u16(val.toString(), error);
      if (U_FAILURE(error)) {
        return false;
      }
     }

    // Generate sort key
    int sortkey_len =
      ucol_getSortKey(data->collator(),
                      strval.getBuffer(), strval.length(),
                      (uint8_t*)(sortKeys + sortKeysOffset),
                      sortKeysLength - sortKeysOffset);

    // Check for key buffer overflow
    if (sortkey_len > (sortKeysLength - sortKeysOffset)) {
      int32_t inc = (sortkey_len > DEF_SORT_KEYS_BUF_INCREMENT)
                  ?  sortkey_len : DEF_SORT_KEYS_BUF_INCREMENT;
      sortKeysLength += inc;
      sortKeys = (char*)req::realloc(sortKeys, sortKeysLength);
      if (!sortKeys) {
        throw Exception("Out of memory");
      }
      sortkey_len =
        ucol_getSortKey(data->collator(),
                        strval.getBuffer(), strval.length(),
                        (uint8_t*)(sortKeys + sortKeysOffset),
                        sortKeysLength - sortKeysOffset);
      assert(sortkey_len <= (sortKeysLength - sortKeysOffset));
    }

    // Check for index buffer overflow
    if ((sortIndexPos + 1) > sortIndexLength) {
      sortIndexLength += DEF_SORT_KEYS_INDX_BUF_INCREMENT;
      sortIndex = (collator_sort_key_index_t*)req::realloc(sortIndex,
                      sortIndexLength * sizeof(collator_sort_key_index_t));
      if (!sortIndex) {
        throw Exception("Out of memory");
      }
    }

    // Initially store offset into buffer, update later to deal with reallocs
    sortIndex[sortIndexPos].key = (char*)sortKeysOffset;
    sortKeysOffset += sortkey_len;

    sortIndex[sortIndexPos].valPos = pos;
    ++sortIndexPos;
  }

  // Update keys to location in realloc'd buffer
  for (int i = 0; i < sortIndexPos; ++i) {
    sortIndex[i].key = sortKeys + (ptrdiff_t)sortIndex[i].key;
  }

  zend_qsort(sortIndex, sortIndexPos,
             sizeof(collator_sort_key_index_t),
             collator_cmp_sort_keys, nullptr);

  Array ret = Array::Create();
  for (int i = 0; i < sortIndexPos; ++i) {
    ret.append(hash->getValue(sortIndex[i].valPos));
  }
  arr.assignIfRef(ret);
  return true;
}
Пример #4
0
void __fastcall TformEnterResults::btnOKClick(TObject *Sender)
{
	// TODO
	pResult result = new Result;
	VecpResult results;

	if (NULL == lines) {
		Application->MessageBox("No file loaded", "Error", MB_OK);
		return;
	}

	// parse
//	int 		patientID;
//	String		barcode;
//	TDateTime	startDate;
//	String		sampleType;
//	int			testID;
//	String		unit;
//	String		result;
//	TDateTime	dateAnalysed;
//	String		cuvetteType;
//	int			reagentID;
//	String		reagentLot;
//	String		notes;

	// following code copied from EditFormat - needs adapting or merging
	LQuery qc(frmBuddyLogin->qCentral);
	qc.setSQL("SELECT"
		" field_cid,"
		" filetype_cid,"
		" tag,"
		" tagcol,"
		" valcol,"
		" subcol,"
		" type,"
		" pos"
		" FROM g_comms_field WHERE id_filetype = :idfiletype"
		" AND status = 0"
		" ORDER BY pos"); // XXX
	qc.setParam("idfiletype", format->id);
	int count = qc.open();
	if (!MYDEBUG) {
		assert(count > 1);
	}
	VecpDatum vecpDatum;
	while (!qc.eof()) {
		Datum *newdatum = new Datum;
		newdatum->datumType     = (Datum::DatumType)qc.readInt("type");
		newdatum->id            = qc.readInt("field_cid");
		newdatum->id_filetype   = qc.readInt("filetype_cid");
		//newdatum->name          = qc.readString("name");
		newdatum->tag           = qc.readString("tag");
		newdatum->tagCol        = qc.readInt("tagcol");
		newdatum->valCol        = qc.readInt("valcol");
		newdatum->valSubCol     = qc.readInt("subcol");
		newdatum->pos     		= qc.readInt("pos");
		vecpDatum.push_back(newdatum);
		qc.next();
	}

//	TTreeNode * rootNode = NULL;
//	TTreeNode * resultNode = NULL;
//	TTreeNode * reagentNode = NULL;
	Datum * curdatum = new Datum;
	for (VecpDatum::const_iterator it = vecpDatum.begin(); it != vecpDatum.end(); it++) {
		// save the current node if it is a container node
		Datum * datum = *it;
		switch (datum->datumType) {
			case Datum::DATUM_ROOT:
				//rootNode = curNode;
				break;
			case Datum::DATUM_RESULT:
				//resultNode = curNode;
				break;
			case Datum::DATUM_REAGENT:
				//reagentNode = curNode;
				break;
			case Datum::DATUM_PID:
			case Datum::DATUM_BARCODE:
			case Datum::DATUM_STARTDATE:
			case Datum::DATUM_SAMPLETYPE:
			case Datum::DATUM_TID:
			case Datum::DATUM_UNIT:
			case Datum::DATUM_RESULTSTRING:
			case Datum::DATUM_DATEANALYSED:
			case Datum::DATUM_CUVETTE:
			case Datum::DATUM_REAGENTID:
			case Datum::DATUM_REAGENTLOT:
			case Datum::DATUM_NOTES:
				// do nothing
				break;
			default:
				throw Exception("Invalid datum type");
		}

		// and add next it to appropriate saved node
		curdatum = *it;
		switch (curdatum->datumType) {
			case Datum::DATUM_ROOT:
				throw "DATUM_ROOT should not be stored in database";
			case Datum::DATUM_PID:
			case Datum::DATUM_BARCODE:
			case Datum::DATUM_STARTDATE:
			case Datum::DATUM_SAMPLETYPE:
			case Datum::DATUM_RESULT:
			case Datum::DATUM_NOTES:
				 //curNode = addDatum(curdatum, rootNode);
				break;
			case Datum::DATUM_TID:
			case Datum::DATUM_UNIT:
			case Datum::DATUM_RESULTSTRING:
			case Datum::DATUM_DATEANALYSED:
			case Datum::DATUM_CUVETTE:
			case Datum::DATUM_REAGENT:
				//curNode = addDatum(curdatum, resultNode);
				break;
			case Datum::DATUM_REAGENTID:
			case Datum::DATUM_REAGENTLOT:
				//curNode = addDatum(curdatum, reagentNode);
				break;
			default:
				throw Exception("Invalid datum type");
		}
	} // for vecpDatum

	// display the records
	for (VecpResult::const_iterator it = results.begin(); it != results.end(); it++) {
		result = *it;
		if (!cbDummyRun->Checked) {
			// actually store the records
		}

		if (cbGenerate->Checked) {
			// generate a CSV file
		}
	}

	// clean up
	delete_referenced< VecpResult > (results);
}
  ConfigDocument::ConfigDocument(int& argc, 
				 char * argv[], 
				 const std::string& defaultname, 
				 const std::string& documentname,
				 const std::vector<std::string> &userPath ) :
    document_( new QDomDocument(documentname.c_str()) )
  {

    const char *name;
    char host[256];
    if (defaultname == "") {
      // determine the name of the config file
      ACE_OS::hostname(host, 256);
      name = host;
    } else {
      name = defaultname.c_str();
    }

    ACE_Arg_Shifter arg_shifter (argc, argv);
    while (arg_shifter.is_anything_left ()) {
//      char *current_arg = arg_shifter.get_current ();
      const ACE_TCHAR *current_arg = arg_shifter.get_current ();

      const char configFileOpt[] = "-MiroConfigFile";
      const int optLen = sizeof(configFileOpt) - 1;
      if (ACE_OS::strcasecmp(current_arg, configFileOpt) == 0) {
	arg_shifter.consume_arg();
	if (arg_shifter.is_parameter_next()) {
	  name = arg_shifter.get_current ();
	  arg_shifter.consume_arg();
	}
      }
      else if (ACE_OS::strncasecmp(current_arg, configFileOpt, optLen) == 0) {
	arg_shifter.consume_arg();
	// The rest of the argument is the ORB id...
        name = current_arg + optLen;
	// but we should skip an optional space...
	if (name[0] == ' ')
	  name++;
      }
      else
	arg_shifter.ignore_arg ();
    }

    std::string fileName = name;
    if (name == host)
      fileName += std::string(".xml");
    std::string fullName = Miro::findFile(fileName, userPath );

    if (fullName.length() == 0) {
      std::cerr << "File not found: " << fileName << std::endl;
      std::cerr << "No config file processing." << std::endl;
    } 
    else {
      QFile f(fullName.c_str());

      if (!f.open(IO_ReadOnly)) {
	std::cout << "error on open" << std::endl;
	throw CException(errno, std::strerror(errno));
      }
      QString parsingError;
      int line = 0;
      int column = 0;
      if (!document_->setContent(&f/*, &parsingError, &line, &column*/)) {
	f.close();
	std::stringstream ostr;
	ostr << "error parsing " << fullName << std::endl
	     << " in line " << line << " "
	     << ", column " << column << std::endl
	     << parsingError << std::endl;
	throw Exception(ostr.str());
      }
      f.close();
    }
  }
Пример #6
0
void GL1TextureProvider::transform_coordinate(const PrimitivesArrayProvider::VertexData &attribute, std::vector<float> &transformed_data, int vertex_offset, int num_vertices, int total_vertices)
{
	if (attribute.type != type_float)
	{
		throw Exception("Implement me: Texture coord npot transformation (not float) (GL1 target)");
	}

	int desired_size = attribute.size * (total_vertices);
	if (transformed_data.size() < desired_size)
		transformed_data.resize(desired_size);

	int size = attribute.size;

	int stride_float;
	if (attribute.stride)
	{
		stride_float = (attribute.stride / sizeof(float));
	}
	else
	{
		stride_float = size;
	}

	int source_position = vertex_offset * stride_float;

	GL1VertexArrayBufferProvider *vertex_array_ptr = static_cast<GL1VertexArrayBufferProvider *>(attribute.array_provider);
	if (!vertex_array_ptr)
		throw Exception("Invalid BindBuffer Provider");

	const char *data_ptr = ((const char *) vertex_array_ptr->get_data()) + attribute.offset;

	float *src = (float *) data_ptr;
	float *dest = &transformed_data[vertex_offset * size];

	stride_float -= size;

	if (size==1)
	{
		for (int vertex_count=0; vertex_count < num_vertices; vertex_count++, source_position += stride_float)
		{
			*(dest++) = src[source_position++] * pot_ratio_width;
		}
	}
	else if (size==2)
	{
		for (int vertex_count=0; vertex_count < num_vertices; vertex_count++, source_position += stride_float)
		{
			*(dest++) = src[source_position++] * pot_ratio_width;
			*(dest++) = src[source_position++] * pot_ratio_height;
		}
	}
	else if (size==3)
	{
		for (int vertex_count=0; vertex_count < num_vertices; vertex_count++, source_position += stride_float)
		{
			*(dest++) = src[source_position++] * pot_ratio_width;
			*(dest++) = src[source_position++] * pot_ratio_height;
			*(dest++) = src[source_position++] * pot_ratio_depth;
		}
	}
}
Пример #7
0
void GL1TextureProvider::to_opengl_textureformat(TextureFormat format, GLint &gl_internal_format, GLenum &gl_pixel_format)
{
	switch (format)
	{
	// base internal format

	// sized internal format

		// TODO: Should this really be here?
		case tf_stencil_index1: gl_internal_format = GL_STENCIL_INDEX1; gl_pixel_format = GL_STENCIL_INDEX; break;
		case tf_stencil_index4: gl_internal_format = GL_STENCIL_INDEX4; gl_pixel_format = GL_STENCIL_INDEX; break;
		case tf_stencil_index8: gl_internal_format = GL_STENCIL_INDEX8; gl_pixel_format = GL_STENCIL_INDEX; break;
		case tf_stencil_index16: gl_internal_format = GL_STENCIL_INDEX16; gl_pixel_format = GL_STENCIL_INDEX; break;

		//case tf_r8: gl_internal_format = GL_R8; gl_pixel_format = GL_RED; break;
		//case tf_r8_snorm: gl_internal_format = GL_R8_SNORM; gl_pixel_format = GL_RED; break;
		//case tf_r16: gl_internal_format = GL_R16; gl_pixel_format = GL_RED; break;
		//case tf_r16_snorm: gl_internal_format = GL_R16_SNORM; gl_pixel_format = GL_RED; break;
		//case tf_rg8: gl_internal_format = GL_RG8; gl_pixel_format = GL_RG; break;
		//case tf_rg8_snorm: gl_internal_format = GL_RG8_SNORM; gl_pixel_format = GL_RG; break;
		//case tf_rg16: gl_internal_format = GL_RG16; gl_pixel_format = GL_RG; break;
		//case tf_rg16_snorm: gl_internal_format = GL_RG16_SNORM; gl_pixel_format = GL_RG; break;
		case tf_r3_g3_b2: gl_internal_format = GL_R3_G3_B2; gl_pixel_format = GL_RGB; break;
		case tf_rgb4: gl_internal_format = GL_RGB4; gl_pixel_format = GL_RGB; break;
		case tf_rgb5: gl_internal_format = GL_RGB5; gl_pixel_format = GL_RGB; break;
		case tf_rgb8: gl_internal_format = GL_RGB8; gl_pixel_format = GL_RGB; break;
		case tf_rgb10: gl_internal_format = GL_RGB10; gl_pixel_format = GL_RGB; break;
		case tf_rgb12: gl_internal_format = GL_RGB12; gl_pixel_format = GL_RGB; break;
		case tf_rgb16: gl_internal_format = GL_RGB16; gl_pixel_format = GL_RGB; break;
		//case tf_rgb16_snorm: gl_internal_format = GL_RGB16_SNORM; gl_pixel_format = GL_RGB; break;
		case tf_rgba2: gl_internal_format = GL_RGBA2; gl_pixel_format = GL_RGBA; break;
		case tf_rgba4: gl_internal_format = GL_RGBA4; gl_pixel_format = GL_RGBA; break;
		case tf_rgb5_a1: gl_internal_format = GL_RGB5_A1; gl_pixel_format = GL_RGBA; break;
		case tf_rgba8: gl_internal_format = GL_RGBA8; gl_pixel_format = GL_RGBA; break;
		case tf_bgra8: gl_internal_format = GL_RGBA8; gl_pixel_format = GL_BGRA; break;
		case tf_bgr8: gl_internal_format = GL_RGB8; gl_pixel_format = GL_BGR; break;
		//case tf_rgba8_snorm: gl_internal_format = GL_RGBA8_SNORM; gl_pixel_format = GL_RGBA; break;
		case tf_rgb10_a2: gl_internal_format = GL_RGB10_A2; gl_pixel_format = GL_RGBA; break;
		case tf_rgba12: gl_internal_format = GL_RGBA12; gl_pixel_format = GL_RGBA; break;
		case tf_rgba16: gl_internal_format = GL_RGBA16; gl_pixel_format = GL_RGBA; break;
		//case tf_rgba16_snorm: gl_internal_format = GL_RGBA16_SNORM; gl_pixel_format = GL_RGBA; break;
		//case tf_srgb8: gl_internal_format = GL_SRGB8; gl_pixel_format = GL_RGB; break;
		//case tf_srgb8_alpha8: gl_internal_format = GL_SRGB8_ALPHA8; gl_pixel_format = GL_RGBA; break;
		//case tf_r16f: gl_internal_format = GL_R16F; gl_pixel_format = GL_RED; break;
		//case tf_rg16f: gl_internal_format = GL_RG16F; gl_pixel_format = GL_RG; break;
		//case tf_rgb16f: gl_internal_format = GL_RGB16F; gl_pixel_format = GL_RGB; break;
		//case tf_rgba16f: gl_internal_format = GL_RGBA16F; gl_pixel_format = GL_RGBA; break;
		//case tf_r32f: gl_internal_format = GL_R32F; gl_pixel_format = GL_RED; break;
		//case tf_rg32f: gl_internal_format = GL_RG32F; gl_pixel_format = GL_RG; break;
		//case tf_rgb32f: gl_internal_format = GL_RGB32F; gl_pixel_format = GL_RGB; break;
		//case tf_rgba32f: gl_internal_format = GL_RGBA32F; gl_pixel_format = GL_RGBA; break;
		//case tf_r11f_g11f_b10f: gl_internal_format = GL_R11F_G11F_B10F; gl_pixel_format = GL_RGB; break;
		//case tf_rgb9_e5: gl_internal_format = GL_RGB9_E5; gl_pixel_format = GL_RGB; break;
		//case tf_r8i: gl_internal_format = GL_R8I; gl_pixel_format = GL_RED; break;
		//case tf_r8ui: gl_internal_format = GL_R8UI; gl_pixel_format = GL_RED; break;
		//case tf_r16i: gl_internal_format = GL_R16I; gl_pixel_format = GL_RED; break;
		//case tf_r16ui: gl_internal_format = GL_R16UI; gl_pixel_format = GL_RED; break;
		//case tf_r32i: gl_internal_format = GL_R32I; gl_pixel_format = GL_RED; break;
		//case tf_r32ui: gl_internal_format = GL_R32UI; gl_pixel_format = GL_RED; break;
		//case tf_rg8i: gl_internal_format = GL_RG8I; gl_pixel_format = GL_RG; break;
		//case tf_rg8ui: gl_internal_format = GL_RG8UI; gl_pixel_format = GL_RG; break;
		//case tf_rg16i: gl_internal_format = GL_RG16I; gl_pixel_format = GL_RG; break;
		//case tf_rg16ui: gl_internal_format = GL_RG16UI; gl_pixel_format = GL_RG; break;
		//case tf_rg32i: gl_internal_format = GL_RG32I; gl_pixel_format = GL_RG; break;
		//case tf_rg32ui: gl_internal_format = GL_RG32UI; gl_pixel_format = GL_RG; break;
		//case tf_rgb8i: gl_internal_format = GL_RGB8I; gl_pixel_format = GL_RGB; break;
		//case tf_rgb8ui: gl_internal_format = GL_RGB8UI; gl_pixel_format = GL_RGB; break;
		//case tf_rgb16i: gl_internal_format = GL_RGB16I; gl_pixel_format = GL_RGB; break;
		//case tf_rgb16ui: gl_internal_format = GL_RGB16UI; gl_pixel_format = GL_RGB; break;
		//case tf_rgb32i: gl_internal_format = GL_RGB32I; gl_pixel_format = GL_RGB; break;
		//case tf_rgb32ui: gl_internal_format = GL_RGB32UI; gl_pixel_format = GL_RGB; break;
		//case tf_rgba8i: gl_internal_format = GL_RGBA8I; gl_pixel_format = GL_RGBA; break;
		//case tf_rgba8ui: gl_internal_format = GL_RGBA8UI; gl_pixel_format = GL_RGBA; break;
		//case tf_rgba16i: gl_internal_format = GL_RGBA16I; gl_pixel_format = GL_RGBA; break;
		//case tf_rgba16ui: gl_internal_format = GL_RGBA16UI; gl_pixel_format = GL_RGBA; break;
		//case tf_rgba32i: gl_internal_format = GL_RGBA32I; gl_pixel_format = GL_RGBA; break;
		//case tf_rgba32ui: gl_internal_format = GL_RGBA32UI; gl_pixel_format = GL_RGBA; break;
		case tf_depth_component16: gl_internal_format = GL_DEPTH_COMPONENT16; gl_pixel_format = GL_DEPTH_COMPONENT; break;
		case tf_depth_component24: gl_internal_format = GL_DEPTH_COMPONENT24; gl_pixel_format = GL_DEPTH_COMPONENT; break;
		case tf_depth_component32: gl_internal_format = GL_DEPTH_COMPONENT32; gl_pixel_format = GL_DEPTH_COMPONENT; break;
		//case tf_depth_component32f: gl_internal_format = GL_DEPTH_COMPONENT32F; gl_pixel_format = GL_DEPTH_COMPONENT; break;
		//case tf_depth24_stencil8: gl_internal_format = GL_DEPTH24_STENCIL8; gl_pixel_format = GL_DEPTH_STENCIL; break;
		//case tf_depth32f_stencil8: gl_internal_format = GL_DEPTH32F_STENCIL8; gl_pixel_format = GL_DEPTH_STENCIL; break;

		//case tf_compressed_red: gl_internal_format = GL_COMPRESSED_RED; gl_pixel_format = GL_RED; break;
		//case tf_compressed_rg: gl_internal_format = GL_COMPRESSED_RG; gl_pixel_format = GL_RG; break;
		case tf_compressed_rgb: gl_internal_format = GL_COMPRESSED_RGB; gl_pixel_format = GL_RGB; break;
		case tf_compressed_rgba: gl_internal_format = GL_COMPRESSED_RGBA; gl_pixel_format = GL_RGBA; break;
		//case tf_compressed_srgb: gl_internal_format = GL_COMPRESSED_SRGB; gl_pixel_format = GL_RGB; break;
		//case tf_compressed_srgb_alpha: gl_internal_format = GL_COMPRESSED_SRGB_ALPHA; gl_pixel_format = GL_RGBA; break;
		//case tf_compressed_red_rgtc1: gl_internal_format = GL_COMPRESSED_RED_RGTC1; gl_pixel_format = GL_RED; break;
		//case tf_compressed_signed_red_rgtc1: gl_internal_format = GL_COMPRESSED_SIGNED_RED_RGTC1; gl_pixel_format = GL_RED; break;
		//case tf_compressed_rg_rgtc2: gl_internal_format = GL_COMPRESSED_RG_RGTC2; gl_pixel_format = GL_RG; break;
		//case tf_compressed_signed_rg_rgtc2: gl_internal_format = GL_COMPRESSED_SIGNED_RG_RGTC2; gl_pixel_format = GL_RG; break;

		case tf_compressed_rgb_s3tc_dxt1: gl_internal_format = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; gl_pixel_format = GL_RGB; break;
		case tf_compressed_rgba_s3tc_dxt1: gl_internal_format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; gl_pixel_format = GL_RGBA; break;
		case tf_compressed_rgba_s3tc_dxt3: gl_internal_format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; gl_pixel_format = GL_RGBA; break;
		case tf_compressed_rgba_s3tc_dxt5: gl_internal_format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; gl_pixel_format = GL_RGBA; break;
		//case tf_compressed_srgb_s3tc_dxt1: gl_internal_format = GL_COMPRESSED_SRGB_S3TC_DXT1_EXT; gl_pixel_format = GL_RGB; break;
		//case tf_compressed_srgb_alpha_s3tc_dxt1: gl_internal_format = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; gl_pixel_format = GL_RGBA; break;
		//case tf_compressed_srgb_alpha_s3tc_dxt3: gl_internal_format = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; gl_pixel_format = GL_RGBA; break;
		//case tf_compressed_srgb_alpha_s3tc_dxt5: gl_internal_format = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; gl_pixel_format = GL_RGBA; break;

		default:
			throw Exception(string_format("Unsupported TextureFormat (%1)", format));
	}
}
Пример #8
0
FunctionWidget::FunctionWidget(QWidget *parent): BaseObjectWidget(parent, OBJ_FUNCTION)
{
	try
	{
		QStringList types;
		QGridLayout *grid=nullptr, *grid1=nullptr;
    QVBoxLayout *vlayout=nullptr;
    QSpacerItem *spacer=nullptr;

		map<QString, vector<QWidget *> > fields_map;
		map<QWidget *, vector<QString> > value_map;
		QFrame *frame=nullptr;

		Ui_FunctionWidget::setupUi(this);

		configureFormLayout(function_grid, OBJ_FUNCTION);
		connect(parent_form->apply_ok_btn,SIGNAL(clicked(bool)), this, SLOT(applyConfiguration(void)));

    source_code_hl=new SyntaxHighlighter(source_code_txt);
		source_code_cp=new CodeCompletionWidget(source_code_txt);

		ret_type=new PgSQLTypeWidget(this);
    vlayout=new QVBoxLayout;
    spacer=new QSpacerItem(5,5,QSizePolicy::Preferred,QSizePolicy::Expanding);
    vlayout->addWidget(ret_type);
    vlayout->addSpacerItem(spacer);

		return_tab=new ObjectTableWidget(ObjectTableWidget::ALL_BUTTONS ^
																			 ObjectTableWidget::UPDATE_BUTTON, true, this);
		return_tab->setColumnCount(2);
		return_tab->setHeaderLabel(trUtf8("Column"), 0);
    return_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/column.png")),0);
		return_tab->setHeaderLabel(trUtf8("Type"), 1);
    return_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/usertype.png")),1);

		parameters_tab=new ObjectTableWidget(ObjectTableWidget::ALL_BUTTONS ^
																					 ObjectTableWidget::UPDATE_BUTTON, true, this);
		parameters_tab->setColumnCount(4);
		parameters_tab->setHeaderLabel(trUtf8("Name"),0);
    parameters_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/parameter.png")),0);
		parameters_tab->setHeaderLabel(trUtf8("Type"),1);
    parameters_tab->setHeaderIcon(QPixmap(QString(":/icones/icones/usertype.png")),1);
		parameters_tab->setHeaderLabel(trUtf8("Mode"),2);
		parameters_tab->setHeaderLabel(trUtf8("Default Value"),3);

		grid=new QGridLayout;
		grid->addWidget(parameters_tab,0,0,1,1);
		grid->setContentsMargins(4,4,4,4);
		func_config_twg->widget(1)->setLayout(grid);

		grid=dynamic_cast<QGridLayout *>(func_config_twg->widget(0)->layout());
    grid->addLayout(vlayout, grid->count(), 0, 1, 5);
		grid->addWidget(ret_table_gb, grid->count()-1, 0, 1, 5);

		grid1=new QGridLayout;
		grid1->addWidget(return_tab, 0, 0, 1, 1);
		grid1->setContentsMargins(2,2,2,2);
		ret_table_gb->setLayout(grid1);
		ret_table_gb->setVisible(false);

    fields_map[generateVersionsInterval(AFTER_VERSION, PgSQLVersions::PGSQL_VERSION_92)].push_back(leakproof_chk);
		frame=generateVersionWarningFrame(fields_map, &value_map);
		grid->addWidget(frame, grid->count()+1, 0, 1, 5);
		frame->setParent(func_config_twg->widget(0));

		parent_form->setMinimumSize(645, 675);

		SecurityType::getTypes(types);
		security_cmb->addItems(types);

		FunctionType::getTypes(types);
		func_type_cmb->addItems(types);

		BehaviorType::getTypes(types);
		behavior_cmb->addItems(types);

		connect(simple_rb, SIGNAL(clicked(bool)), this, SLOT(alternateReturnTypes(void)));
		connect(set_rb, SIGNAL(clicked(bool)), this, SLOT(alternateReturnTypes(void)));
		connect(table_rb, SIGNAL(clicked(bool)), this, SLOT(alternateReturnTypes(void)));
		connect(language_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(selectLanguage(void)));

		connect(parameters_tab, SIGNAL(s_rowAdded(int)), this, SLOT(showParameterForm()));
		connect(parameters_tab, SIGNAL(s_rowEdited(int)), this, SLOT(showParameterForm()));
		connect(return_tab, SIGNAL(s_rowAdded(int)), this, SLOT(showParameterForm()));
		connect(return_tab, SIGNAL(s_rowEdited(int)), this, SLOT(showParameterForm()));

		setRequiredField(language_lbl);
		setRequiredField(ret_method_lbl);
		setRequiredField(symbol_lbl);
		setRequiredField(library_lbl);
		setRequiredField(sourc_code_lbl);
    configureTabOrder();
	}
	catch(Exception &e)
	{
		throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
	}
}
Пример #9
0
void FunctionWidget::validateConfiguredFunction(void)
{
	vector<BaseObject *>::iterator itr, itr_end;
	vector<BaseObject *> obj_list;
	Conversion *conv=nullptr;
	Cast *cast=nullptr;
	Aggregate *aggr=nullptr;
	Language *lang=nullptr;
	Operator *oper=nullptr;
	Type *type=nullptr;
	Function *func=nullptr;
	BaseObject *object=nullptr;
	ObjectType obj_type;
	unsigned i1=0;

	func=dynamic_cast<Function *>(this->object);

	try
	{
		model->getObjectReferences(func, obj_list);
		itr=obj_list.begin();
		itr_end=obj_list.end();

		while(itr!=itr_end)
		{
			object=(*itr);
			obj_type=object->getObjectType();
			itr++;

			/* The validation of the function happens as follows:

				For each type of object in vector 'types' is obtained the list of objects.
				If there are elements in this list, the function is assigned for each element
				and these elements internally validates the function according to required by the
				each class rules.

				If the function is invalid the instances raises	exceptions accusing the error
				that is enough to check	the validity of the function in relation to objects that reference it. */
			if(obj_type==OBJ_CONVERSION)
			{
				conv=dynamic_cast<Conversion *>(object);
				if(conv->getConversionFunction()==func)
					conv->setConversionFunction(func);
			}
			else if(obj_type==OBJ_CAST)
			{
				cast=dynamic_cast<Cast *>(object);
				if(cast->getCastFunction()==func)
					cast->setCastFunction(func);
			}
			else if(obj_type==OBJ_AGGREGATE)
			{
				aggr=dynamic_cast<Aggregate *>(object);
				if(aggr->getFunction(Aggregate::FINAL_FUNC)==func)
					aggr->setFunction(Aggregate::FINAL_FUNC, func);
				else if(aggr->getFunction(Aggregate::TRANSITION_FUNC)==func)
					aggr->setFunction(Aggregate::TRANSITION_FUNC, func);
			}
			else if(obj_type==OBJ_TRIGGER)
			{
				dynamic_cast<Trigger *>(object)->setFunction(func);
			}
			else if(obj_type==OBJ_LANGUAGE)
			{
				lang=dynamic_cast<Language *>(object);

				for(i1=Language::VALIDATOR_FUNC; i1 <= Language::INLINE_FUNC; i1++)
				{
					if(lang->getFunction(i1)==func)
						lang->setFunction(func, i1);
				}
			}
			else if(obj_type==OBJ_OPERATOR)
			{
				oper=dynamic_cast<Operator *>(object);
				for(i1=Operator::FUNC_OPERATOR; i1 <= Operator::FUNC_RESTRICT; i1++)
				{
					if(oper->getFunction(i1)==func)
						oper->setFunction(func, i1);
				}
			}
			else if(obj_type==OBJ_TYPE)
			{
				type=dynamic_cast<Type *>(object);
				if(type->getConfiguration()==Type::BASE_TYPE)
				{
					for(i1=Type::INPUT_FUNC; i1 <=Type::ANALYZE_FUNC; i1++)
					{
						if(type->getFunction(i1)==func)
							type->setFunction(i1, func);
					}
				}
			}
			else if(obj_type==OBJ_EVENT_TRIGGER)
			{
				dynamic_cast<EventTrigger *>(object)->setFunction(func);
			}
		}
	}
	catch(Exception &e)
	{
		throw Exception(Exception::getErrorMessage(ERR_FUNC_CONFIG_INV_OBJECT)
                    .arg(object->getName(true))
										.arg(object->getTypeName()),
										ERR_FUNC_CONFIG_INV_OBJECT,
										__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
	}
}
Пример #10
0
bool HHVM_FUNCTION(trigger_error, const String& error_msg,
                   int error_type /* = k_E_USER_NOTICE */) {
  std::string msg = error_msg.data(); // not toCppString()
  if (UNLIKELY(g_context->getThrowAllErrors())) {
    throw Exception(folly::sformat("throwAllErrors: {}", error_type));
  }
  if (error_type == k_E_USER_ERROR) {
    g_context->handleError(msg, error_type, true,
                           ExecutionContext::ErrorThrowMode::IfUnhandled,
                           "\nFatal error: ");
    return true;
  }
  if (error_type == k_E_USER_WARNING) {
    g_context->handleError(msg, error_type, true,
                           ExecutionContext::ErrorThrowMode::Never,
                           "\nWarning: ");
    return true;
  }
  if (error_type == k_E_USER_NOTICE) {
    g_context->handleError(msg, error_type, true,
                           ExecutionContext::ErrorThrowMode::Never,
                           "\nNotice: ");
    return true;
  }
  if (error_type == k_E_USER_DEPRECATED) {
    g_context->handleError(msg, error_type, true,
                           ExecutionContext::ErrorThrowMode::Never,
                           "\nDeprecated: ");
    return true;
  }
  if (error_type == k_E_STRICT) {
    // So that we can raise strict warnings for mismatched
    // params in FCallBuiltin
    raise_strict_warning(msg);
    return true;
  }

  ActRec* fp = g_context->getStackFrame();

  if (fp->m_func->nativeFuncPtr() == (BuiltinFunction)HHVM_FN(trigger_error)) {
    fp = g_context->getOuterVMFrame(fp);
  }
  if (fp && fp->m_func->isBuiltin()) {
    if (error_type == k_E_ERROR) {
      raise_error_without_first_frame(msg);
      return true;
    }
    if (error_type == k_E_WARNING) {
      raise_warning_without_first_frame(msg);
      return true;
    }
    if (error_type == k_E_NOTICE) {
      raise_notice_without_first_frame(msg);
      return true;
    }
    if (error_type == k_E_DEPRECATED) {
      raise_deprecated_without_first_frame(msg);
      return true;
    }
    if (error_type == k_E_RECOVERABLE_ERROR) {
      raise_recoverable_error_without_first_frame(msg);
      return true;
    }
  }
  raise_warning("Invalid error type specified");
  return false;
}
Пример #11
0
SnippetsConfigWidget::SnippetsConfigWidget(QWidget * parent) : BaseConfigWidget(parent)
{
  QPixmap ico;
  QString gen_purpose=trUtf8("General purpose");
  map<QString, ObjectType> types_map;
  vector<ObjectType> types=BaseObject::getObjectTypes(true, {OBJ_RELATIONSHIP, OBJ_TAG, OBJ_TEXTBOX,
                                                             OBJ_PERMISSION, BASE_RELATIONSHIP });

  setupUi(this);

  for(ObjectType type : types)
    types_map[BaseObject::getTypeName(type)]=type;

  //Creates a combo with the accepted object type
  for(auto itr : types_map)
  {
    ico.load(QString(":/icones/icones/%1.png").arg(BaseObject::getSchemaName(itr.second)));
    applies_to_cmb->addItem(ico, itr.first, itr.second);
    filter_cmb->addItem(ico, itr.first, itr.second);
  }

  applies_to_cmb->insertItem(0, gen_purpose, BASE_OBJECT);
  applies_to_cmb->setCurrentIndex(0);

  filter_cmb->insertItem(0, gen_purpose, BASE_OBJECT);
  filter_cmb->insertItem(0, trUtf8("All snippets"));
  filter_cmb->setCurrentIndex(0);

  parsable_ht=new HintTextWidget(parsable_hint, this);
  parsable_ht->setText(parsable_chk->statusTip());

  placeholders_ht=new HintTextWidget(placeholders_hint, this);
  placeholders_ht->setText(placeholders_chk->statusTip());

  try
  {
    snippet_hl=new SyntaxHighlighter(snippet_txt, false);
    snippet_hl->loadConfiguration(GlobalAttributes::SQL_HIGHLIGHT_CONF_PATH);
  }
  catch(Exception &e)
  {
    throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__,&e);
  }

  enableEditMode(false);

  connect(new_tb, SIGNAL(clicked()), this, SLOT(resetForm()));
  connect(edit_tb, SIGNAL(clicked()), this, SLOT(editSnippet()));
  connect(remove_tb, SIGNAL(clicked()), this, SLOT(removeSnippet()));
  connect(remove_all_tb, SIGNAL(clicked()), this, SLOT(removeAllSnippets()));
  connect(cancel_tb, &QToolButton::clicked, [=](){ enableEditMode(false); });
  connect(snippets_cmb, &QComboBox::currentTextChanged, [=](){ enableEditMode(false); });
  connect(id_edt, SIGNAL(textChanged(QString)), this, SLOT(enableSaveButtons()));
  connect(label_edt, SIGNAL(textChanged(QString)), this, SLOT(enableSaveButtons()));
  connect(snippet_txt, SIGNAL(textChanged()), this, SLOT(enableSaveButtons()));
  connect(parsable_chk, SIGNAL(toggled(bool)), this, SLOT(enableSaveButtons()));
  connect(filter_cmb, SIGNAL(currentIndexChanged(int)), this, SLOT(filterSnippets(int)));
  connect(update_tb, SIGNAL(clicked()), this, SLOT(handleSnippet()));
  connect(add_tb, SIGNAL(clicked()), this, SLOT(handleSnippet()));
  connect(parse_tb, SIGNAL(clicked()), this, SLOT(parseSnippet()));
  connect(parsable_chk, SIGNAL(toggled(bool)), placeholders_chk, SLOT(setEnabled(bool)));
}
Пример #12
0
void FileOutputStream::flush() {
	if (buf_pos > 0 && fwrite((void*) buffer, sizeof(char), buf_pos, fp) != buf_pos)
			throw Exception(Exception::ERR_FILE_WRITE);
	buf_pos = 0;
	fflush(fp);
}
Пример #13
0
void  ModelValidationHelper::resolveConflict(ValidationInfo &info)
{
	try
	{
		vector<BaseObject *> refs=info.getReferences();
		BaseObject *obj=nullptr;

		//Resolving broken references by swaping the object ids
    if(info.getValidationType()==ValidationInfo::BROKEN_REFERENCE ||
       info.getValidationType()==ValidationInfo::SP_OBJ_BROKEN_REFERENCE)
		{
      BaseObject *info_obj=info.getObject(), *aux_obj=nullptr;
      unsigned obj_id=info_obj->getObjectId();

      if(info.getValidationType()==ValidationInfo::BROKEN_REFERENCE)
      {
        //Search for the object with the minor id
        while(!refs.empty() && !valid_canceled)
        {
          //For commom broken reference, check if the object id is greater than the reference id
          if(obj_id > refs.back()->getObjectId())
          {
            obj=refs.back();
            obj_id=obj->getObjectId();
          }

          refs.pop_back();
        }
      }

			//Swap the id of the validation object and the found object (minor id)
			if(obj)
      {
        BaseObject::swapObjectsIds(info_obj, obj, true);
        aux_obj=obj;
      }
      else
      {
        BaseObject::updateObjectId(info_obj);
        aux_obj=info_obj;
      }

      if(aux_obj->getObjectType()==OBJ_VIEW)
      {
        vector<BaseRelationship *> base_rels=db_model->getRelationships(dynamic_cast<BaseTable *>(aux_obj));
        for(auto rel : base_rels)
          BaseObject::updateObjectId(rel);
      }

			sleepThread(5);
		}
		//Resolving no unique name by renaming the constraints/indexes
		else if(info.getValidationType()==ValidationInfo::NO_UNIQUE_NAME)
		{
			unsigned suffix=1;
			QString new_name;
			Table *table=nullptr;
			ObjectType obj_type;
			BaseObject *obj=info.getObject();
			TableObject *tab_obj=nullptr;

			/* If the last element of the referrer objects is a table or view the
			info object itself need to be renamed since tables and views will not be renamed */
			bool rename_obj=(refs.back()->getObjectType()==OBJ_TABLE ||
											 refs.back()->getObjectType()==OBJ_VIEW);

			if(rename_obj)
			{
				table=dynamic_cast<Table *>(dynamic_cast<TableObject *>(obj)->getParentTable());
				obj_type=obj->getObjectType();

				do
				{
					//Configures a new name for the object [name]_[suffix]
					new_name=QString("%1_%2").arg(obj->getName()).arg(suffix);
					suffix++;
				}
				//Generates a new name until no object is found on parent table
				while(table->getObjectIndex(new_name, obj_type) >= 0);

				//Renames the object
				obj->setName(new_name);
			}

			//Renaming the referrer objects
			while(!refs.empty() && !valid_canceled)
			{
				obj_type=refs.back()->getObjectType();
				tab_obj=dynamic_cast<TableObject *>(refs.back());

				//Tables and view aren't renamed only table child objects (constraints, indexes)
				if(tab_obj && !tab_obj->isAddedByRelationship())
				{
					table=dynamic_cast<Table *>(tab_obj->getParentTable());

					do
					{
						//Configures a new name for the object [name]_[suffix]
						new_name=QString("%1_%2").arg(refs.back()->getName()).arg(suffix);
						suffix++;
					}
					//Generates a new name until no object is found on parent table
					while(table->getObjectIndex(new_name, obj_type) >= 0);

					//Renames the referrer object
					refs.back()->setName(new_name);
				}

				refs.pop_back();
				sleepThread(5);
			}
		}
	}
	catch(Exception &e)
	{
		throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
	}
}
Пример #14
0
void ModelValidationHelper::validateModel(void)
{
	if(!db_model)
		throw Exception(ERR_OPR_NOT_ALOC_OBJECT,__PRETTY_FUNCTION__,__FILE__,__LINE__);

	try
	{
		ObjectType types[]={ OBJ_ROLE, OBJ_TABLESPACE, OBJ_SCHEMA, OBJ_LANGUAGE, OBJ_FUNCTION,
												 OBJ_TYPE, OBJ_DOMAIN, OBJ_SEQUENCE, OBJ_OPERATOR, OBJ_OPFAMILY,
												 OBJ_OPCLASS, OBJ_COLLATION, OBJ_TABLE, OBJ_EXTENSION, OBJ_VIEW, OBJ_RELATIONSHIP },
								aux_types[]={ OBJ_TABLE, OBJ_VIEW },
               tab_obj_types[]={ OBJ_CONSTRAINT, OBJ_INDEX },
        obj_type;
		unsigned i, i1, cnt, aux_cnt=sizeof(aux_types)/sizeof(ObjectType),
						count=sizeof(types)/sizeof(ObjectType), count1=sizeof(tab_obj_types)/sizeof(ObjectType);
		BaseObject *object=nullptr, *refer_obj=nullptr;
		vector<BaseObject *> refs, refs_aux, *obj_list=nullptr;
		vector<BaseObject *>::iterator itr;
		TableObject *tab_obj=nullptr;
		Table *table=nullptr, *ref_tab=nullptr, *recv_tab=nullptr;
		Constraint *constr=nullptr;
		Relationship *rel=nullptr;
		map<QString, vector<BaseObject *> > dup_objects;
		map<QString, vector<BaseObject *> >::iterator mitr;
		QString name, signal_msg="`%1' (%2)";

		warn_count=error_count=progress=0;
		val_infos.clear();
		valid_canceled=false;

		/* Step 1: Validating broken references. This situation happens when a object references another
		whose id is smaller than the id of the first one. */
		for(i=0; i < count && !valid_canceled; i++)
		{
			obj_list=db_model->getObjectList(types[i]);
			itr=obj_list->begin();

			while(itr!=obj_list->end()&& !valid_canceled)
			{
				object=(*itr);
        obj_type=object->getObjectType();
				itr++;

				//Excluding the validation of system objects (created automatically)
				if(!object->isSystemObject())
				{
					emit s_objectProcessed(signal_msg.arg(object->getName()).arg(object->getTypeName()), object->getObjectType());

					/* Special validation case: For generalization and copy relationships validates the ids of participant tables.
					 * Reference table cannot own an id greater thant receiver table */
          if(obj_type==OBJ_RELATIONSHIP)
					{
						rel=dynamic_cast<Relationship *>(object);
						if(rel->getRelationshipType()==Relationship::RELATIONSHIP_GEN ||
							 rel->getRelationshipType()==Relationship::RELATIONSHIP_DEP)
						{
							recv_tab=rel->getReceiverTable();
							ref_tab=rel->getReferenceTable();

							if(ref_tab->getObjectId() > recv_tab->getObjectId())
							{
								object=ref_tab;
								refs_aux.push_back(recv_tab);
							}
						}
					}
					else
					{
						db_model->getObjectReferences(object, refs);
						refs_aux.clear();

						while(!refs.empty() && !valid_canceled)
						{
							//Checking if the referrer object is a table object. In this case its parent table is considered
							tab_obj=dynamic_cast<TableObject *>(refs.back());
							constr=dynamic_cast<Constraint *>(tab_obj);

							/* If the current referrer object has an id less than reference object's id
						then it will be pushed into the list of invalid references. The only exception is
						for foreign keys that are discarded from any validation since they are always created
						at end of code defintion being free of any reference breaking. */
							if(object != refs.back() &&
								 (!constr || (constr && constr->getConstraintType()!=ConstraintType::foreign_key)) &&
								 ((!tab_obj && refs.back()->getObjectId() <= object->getObjectId()) ||
									(tab_obj && !tab_obj->isAddedByRelationship() &&
									 tab_obj->getParentTable()->getObjectId() <= object->getObjectId())))
							{
								if(tab_obj)
									refer_obj=tab_obj->getParentTable();
								else
									refer_obj=refs.back();

								//Push the referrer object only if not exists on the list
								if(std::find(refs_aux.begin(), refs_aux.end(), refer_obj)==refs_aux.end())
									refs_aux.push_back(refer_obj);
							}

							refs.pop_back();
						}

            /* Validating a special object. The validation made here is to check if the special object
            (constraint/index/trigger/view) references a column added by a relationship and
            that relationship is being created after the creation of the special object */
            if(obj_type==OBJ_TABLE || obj_type==OBJ_VIEW /* || obj_type==OBJ_SEQUENCE */)
            {
              vector<ObjectType> tab_aux_types={ OBJ_CONSTRAINT, OBJ_TRIGGER, OBJ_INDEX };
              vector<TableObject *> *tab_objs;
              vector<Column *> ref_cols;
              vector<BaseObject *> rels;
              BaseObject *rel=nullptr;
              View *view=nullptr;
              Constraint *constr=nullptr;

              table=dynamic_cast<Table *>(object);
              view=dynamic_cast<View *>(object);

              if(table)
              {
                /* Checking the table children objects if they references some columns added by relationship.
                If so, the id of the relationships are swapped with the child object if the first is created
                after the latter. */
                for(auto obj_tp : tab_aux_types)
                {
                  tab_objs = table->getObjectList(obj_tp);

                  for(auto tab_obj : (*tab_objs))
                  {
                    ref_cols.clear();
                    rels.clear();

                    if(!tab_obj->isAddedByRelationship())
                    {
                      if(obj_tp==OBJ_CONSTRAINT)
                      {
                        constr=dynamic_cast<Constraint *>(tab_obj);

                        if(constr->getConstraintType()!=ConstraintType::primary_key)
                          ref_cols=constr->getRelationshipAddedColumns();
                      }
                      else if(obj_tp==OBJ_TRIGGER)
                        ref_cols=dynamic_cast<Trigger *>(tab_obj)->getRelationshipAddedColumns();
                      else
                        ref_cols=dynamic_cast<Index *>(tab_obj)->getRelationshipAddedColumns();
                    }

                    //Getting the relationships that owns the columns
                    for(auto ref_col : ref_cols)
                    {
                      rel=ref_col->getParentRelationship();
                      if(rel->getObjectId() > tab_obj->getObjectId() && std::find(rels.begin(), rels.end(), rel)==rels.end())
                        rels.push_back(rel);
                    }

                    generateValidationInfo(ValidationInfo::SP_OBJ_BROKEN_REFERENCE, tab_obj, rels);
                  }
                }
              }
              else
              {
                ref_cols=view->getRelationshipAddedColumns();

                //Getting the relationships that owns the columns
                for(auto ref_col : ref_cols)
                {
                  rel=ref_col->getParentRelationship();
                  if(rel->getObjectId() > object->getObjectId() && std::find(rels.begin(), rels.end(), rel)==rels.end())
                    rels.push_back(rel);
                }

                generateValidationInfo(ValidationInfo::SP_OBJ_BROKEN_REFERENCE, object, rels);
              }
            }
					}

          generateValidationInfo(ValidationInfo::BROKEN_REFERENCE, object, refs_aux);
				}
			}

			//Emit a signal containing the validation progress
			progress=((i+1)/static_cast<float>(count))*20;
			emit s_progressUpdated(progress, "");

			sleepThread(5);
		}


		/* Step 2: Validating name conflitcs between primary keys, unique keys, exclude constraints
		and indexs of all tables/views. The table and view names are checked too. */
		obj_list=db_model->getObjectList(OBJ_TABLE);
		itr=obj_list->begin();

		//Searching the model's tables and gathering all the constraints and index
		while(itr!=obj_list->end() && !valid_canceled)
		{
			table=dynamic_cast<Table *>(*itr);

			emit s_objectProcessed(signal_msg.arg(table->getName()).arg(object->getTypeName()), table->getObjectType());

			itr++;

			for(i=0; i < count1 && !valid_canceled; i++)
			{
				cnt=table->getObjectCount(tab_obj_types[i]);

				for(i1=0; i1 < cnt && !valid_canceled; i1++)
				{
					//Get the table object (constraint or index)
					tab_obj=dynamic_cast<TableObject *>(table->getObject(i1, tab_obj_types[i]));

					//Configures the full name of the object including the parent name
					name=tab_obj->getParentTable()->getSchema()->getName(true) + "." + tab_obj->getName(true);
					name.remove("\"");

					//Trying to convert the object to constraint
					constr=dynamic_cast<Constraint *>(tab_obj);

					/* If the object is an index or	a primary key, unique or exclude constraint,
					insert the object on duplicated	objects map */
					if((!constr ||
							(constr && (constr->getConstraintType()==ConstraintType::primary_key ||
													constr->getConstraintType()==ConstraintType::unique ||
													constr->getConstraintType()==ConstraintType::exclude))))
						dup_objects[name].push_back(tab_obj);
				}
			}

			sleepThread(5);
		}

    /* Inserting the tables and views to the map in order to check if there are table objects
			 that conflicts with thems */
		for(i=0; i < aux_cnt && !valid_canceled; i++)
		{
			obj_list=db_model->getObjectList(aux_types[i]);
			itr=obj_list->begin();
			while(itr!=obj_list->end() && !valid_canceled)
			{
				dup_objects[(*itr)->getName(true).remove("\"")].push_back(*itr);
				itr++;
			}

			sleepThread(5);
		}

		//Checking the map of duplicated objects
		mitr=dup_objects.begin();
		i=1;
		while(mitr!=dup_objects.end() && !valid_canceled)
		{
			/* If the vector of the current map element has more the one object
			indicates the duplicity thus generates a validation info */
			if(mitr->second.size() > 1)
      {
				refs.assign(mitr->second.begin() + 1, mitr->second.end());
        generateValidationInfo(ValidationInfo::NO_UNIQUE_NAME, mitr->second.front(), refs);
        refs.clear();
      }

			//Emit a signal containing the validation progress
			progress=20 + ((i/static_cast<float>(dup_objects.size()))*20);
			emit s_progressUpdated(progress, "");

			i++; mitr++;
			sleepThread(5);
		}

		if(!valid_canceled && !fix_mode)
		{
			//Step 3 (optional): Validating the SQL code onto a local DBMS.
			//Case the connection isn't specified indicates that the SQL validation will not be executed
			if(!conn)
			{
				//Emit a signal indicating the final progress
				emitValidationFinished();
			}
			//SQL validation only occurs when the model is completely validated.
			else
			{
				//If there is no errors start the dbms export thread
				if(error_count==0)
				{
					export_thread->start();
					emit s_sqlValidationStarted(true);
				}
				else
				{
					warn_count++;
					emitValidationFinished();
					emit s_validationInfoGenerated(ValidationInfo(trUtf8("There are pending errors! SQL validation will not be executed.")));
				}
			}
		}
	}
	catch(Exception &e)
	{
		throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
	}
}
Пример #15
0
void GL1TextureProvider::create(int new_width, int new_height, int new_depth, int array_size, TextureFormat texture_format, int levels)
{
	throw_if_disposed();

	GLint gl_internal_format;
	GLenum gl_pixel_format;
	to_opengl_textureformat(texture_format, gl_internal_format, gl_pixel_format);

	if ( (new_width > 32768) || (new_width < 1) )
	{
		throw Exception("Invalid texture width in the GL1 target");
	}

	if ( (texture_type == GL_TEXTURE_2D) || (texture_type == GL_TEXTURE_3D) )
	{
		if ( (new_height > 32768) || (new_height < 1) )
		{
			throw Exception("Invalid texture height in the GL1 target");
		}
	}

	if ( texture_type == GL_TEXTURE_3D )
	{
		if ( (new_depth > 32768) || (new_depth < 1) )
		{
			throw Exception("Invalid texture depth in the GL1 target");
		}
	}

	width = new_width;
	height = new_height;
	depth = new_depth;
	GL1TextureStateTracker state_tracker(texture_type, handle);

#ifndef __ANDROID__
	if (texture_type == GL_TEXTURE_1D)
	{
		pot_width = get_next_power_of_two(new_width);
		if (pot_width == new_width)
		{
			power_of_two_texture=true;
		}
		else
		{
			power_of_two_texture=false;
		}

		pot_ratio_width = (float) width / pot_width;
		glTexImage1D(
			GL_TEXTURE_1D,			// target
			0,						// level
			gl_internal_format,		// internalformat
			pot_width,				// width
			0,						// border
			gl_pixel_format,		// format
			GL_UNSIGNED_BYTE,		// type (it really doesn't matter since nothing is uploaded)
			nullptr);						// texels (0 to avoid uploading)
	}
#endif
	if (texture_type == GL_TEXTURE_2D)
	{
		pot_width = get_next_power_of_two(new_width);
		pot_height = get_next_power_of_two(new_height);
		if ( (pot_width == new_width) && (pot_height == new_height))
		{
			power_of_two_texture=true;
		}
		else
		{
			power_of_two_texture=false;
		}
		pot_ratio_width = (float) width / pot_width;
		pot_ratio_height = (float) height / pot_height;

		glTexImage2D(
			GL_TEXTURE_2D,			// target
			0,						// level
			gl_internal_format,		// internalformat
			pot_width,				// width
			pot_height,				// height
			0,						// border
			gl_pixel_format,		// format 
			GL_UNSIGNED_BYTE,		// type (it really doesn't matter since nothing is uploaded)
			nullptr);						// texels (0 to avoid uploading)

		// Clear the whole texture if it is npot
		if (!power_of_two_texture)
		{
			PixelBuffer image = PixelBuffer(pot_width, pot_height, tf_rgba8);
			void *data = image.get_data();
			memset(data, 0, pot_width * pot_height * 4);

			GLenum format;
			GLenum type;
			to_opengl_pixelformat(image, format, type);

			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
			const int bytesPerPixel = image.get_bytes_per_pixel();
#ifndef __ANDROID__
			glPixelStorei(GL_UNPACK_ROW_LENGTH, image.get_pitch() / bytesPerPixel);
			glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
			glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
#endif
			glTexImage2D(
				GL_TEXTURE_2D,		// target
				0,					// level
				gl_internal_format,	// internalformat
				pot_width,			// width
				pot_height,			// height
				0,					// border
				format,				// format
				type,				// type
				data);				// texels

		}
	}
	else
	{
		pot_width = get_next_power_of_two(new_width);
		pot_height = get_next_power_of_two(new_height);
		pot_depth = get_next_power_of_two(new_depth);
		pot_ratio_width = (float) width / pot_width;
		pot_ratio_height = (float) height / pot_height;
		pot_ratio_depth = (float) depth / pot_depth;
		if ( (pot_width == new_width) && (pot_height == new_height) && (pot_depth == new_depth))
		{
			power_of_two_texture=true;
		}
		else
		{
			power_of_two_texture=false;
		}

		glTexImage3D(
			GL_TEXTURE_3D,			// target
			0,						// level
			gl_internal_format,		// internalformat
			pot_width,				// width
			pot_height,				// height
			pot_depth,				// depth
			0,						// border
			gl_pixel_format,		// format 
			GL_UNSIGNED_BYTE,		// type (it really doesn't matter since nothing is uploaded)
			nullptr);						// texels (0 to avoid uploading)
	}
}
Пример #16
0
void FunctionWidget::applyConfiguration(void)
{
	try
	{
		Function *func=nullptr;
		unsigned count, i;
		Parameter param;
		QString str_aux;


		startConfiguration<Function>();

		func=dynamic_cast<Function *>(this->object);
		func->setLanguage(model->getObject(language_cmb->currentText(), OBJ_LANGUAGE));
		func->setFunctionType(func_type_cmb->currentText());
		func->setWindowFunction(window_func_chk->isChecked());
		func->setLeakProof(leakproof_chk->isChecked());
		func->setExecutionCost(exec_cost_spb->value());
		func->setRowAmount(rows_ret_spb->value());
		func->setBehaviorType(behavior_cmb->currentText());
		func->setSecurityType(security_cmb->currentText());
		func->removeParameters();

		count=parameters_tab->getRowCount();

		for(i=0; i < count; i++)
		{
			param.setName(parameters_tab->getCellText(i,0));
			param.setType(parameters_tab->getRowData(i).value<PgSQLType>());

			str_aux=parameters_tab->getCellText(i,2);
      param.setIn(str_aux.indexOf(QString("IN")) >= 0);
      param.setOut(str_aux.indexOf(QString("OUT")) >= 0);
      param.setVariadic(str_aux.indexOf(QString("VARIADIC")) >= 0);

			param.setDefaultValue(parameters_tab->getCellText(i,3));

			func->addParameter(param);
		}


		if(language_cmb->currentText()==~LanguageType(LanguageType::c))
		{
			func->setLibrary(library_edt->text());
			func->setSymbol(symbol_edt->text());
		}
		else
			func->setSourceCode(source_code_txt->toPlainText().toUtf8());

		if(simple_rb->isChecked() || set_rb->isChecked())
		{
			func->setReturnType(ret_type->getPgSQLType());
			func->setReturnSetOf(set_rb->isChecked());
		}
		else
		{
			func->removeReturnedTableColumns();
			count=return_tab->getRowCount();

			for(i=0; i<count; i++)
			{
				func->addReturnedTableColumn(return_tab->getCellText(i,0),
																		 return_tab->getRowData(i).value<PgSQLType>());
			}
		}

		BaseObjectWidget::applyConfiguration();

		validateConfiguredFunction();
		finishConfiguration();
	}
	catch(Exception &e)
	{
		cancelConfiguration();
		throw Exception(e.getErrorMessage(),e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e);
	}
}
Пример #17
0
void GL1TextureProvider::copy_from(GraphicContext &gc, int x, int y, int slice, int level, const PixelBuffer &ximage, const Rect &src_rect)
{
	OpenGL::set_active(gc);

	PixelBuffer image = ximage;

	if (src_rect.left < 0 || src_rect.top < 0 || src_rect.right > image.get_width() || src_rect.bottom > image.get_height())
		throw Exception("Rectangle out of bounds");

	throw_if_disposed();
	GL1TextureStateTracker state_tracker(texture_type, handle);

	// check out if the original texture needs or doesn't need an alpha channel
	bool needs_alpha = image.has_transparency();

	GLenum format;
	GLenum type;
	bool conv_needed = !to_opengl_pixelformat(image, format, type);

	// also check for the pitch (GL1 can only skip pixels, not bytes)
	if (!conv_needed)
	{
		const int bytesPerPixel = image.get_bytes_per_pixel();
		if (image.get_pitch() % bytesPerPixel != 0)
			conv_needed = true;
	}

	// no conversion needed
	if (!conv_needed)
	{
		// change alignment
		glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
		const int bytesPerPixel = image.get_bytes_per_pixel();
#ifndef __ANDROID__
		glPixelStorei(GL_UNPACK_ROW_LENGTH, image.get_pitch() / bytesPerPixel);
		glPixelStorei(GL_UNPACK_SKIP_PIXELS, src_rect.left);
		glPixelStorei(GL_UNPACK_SKIP_ROWS, src_rect.top);
#endif

	}
	// conversion needed
	else
	{
		bool big_endian = Endian::is_system_big();

		PixelBuffer buffer(
			src_rect.get_width(), src_rect.get_height(),
			needs_alpha ? tf_rgba8 : tf_rgb8);
	
		buffer.set_subimage(image, Point(0, 0), src_rect);

		format = needs_alpha ? GL_RGBA : GL_RGB;

		// Upload to GL1:
		glBindTexture(GL_TEXTURE_2D, handle);

		// change alignment
		glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
		const int bytesPerPixel = buffer.get_bytes_per_pixel();
#ifndef __ANDROID__
		glPixelStorei(GL_UNPACK_ROW_LENGTH, buffer.get_pitch() / bytesPerPixel);
		glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
		glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
#endif

		type = GL_UNSIGNED_BYTE;
		image = buffer;
	}

	// upload
	glTexSubImage2D(
		GL_TEXTURE_2D,            // target
		level,                    // level
		x, y,                     // xoffset, yoffset
		src_rect.get_width(),        // width
		src_rect.get_height(),       // height
		format,					  // format
		type,					  // type
		image.get_data());        // texels

	if (!power_of_two_texture)
	{
		// TODO: This needs corrected.It should be optimised and currently it does not write to the lower right quadrant

		// Check extend the right edge
		int right_edge = x + image.get_width();
		if ( right_edge >= width )
		{
			char *edge_data = (char *) image.get_data();
			edge_data += image.get_bytes_per_pixel() * (width-1);

			for(int edge_cnt = right_edge; edge_cnt < pot_width; edge_cnt++)
			{
				glTexSubImage2D(
					GL_TEXTURE_2D,		// target
					level,				// level
					edge_cnt, y,		// xoffset, yoffset
					1,					// width
					src_rect.get_height(),	// height
					format,				// format
					type,				// type
					edge_data);				// texels
			}
		}
		// Check extend the bottom edge
		int bottom_edge = y + image.get_height();
		if ( bottom_edge >= height )
		{
			char *edge_data = (char *) image.get_data();
			edge_data += image.get_pitch() * (height-1);

			for(int edge_cnt = bottom_edge; edge_cnt < pot_height; edge_cnt++)
			{
				glTexSubImage2D(
					GL_TEXTURE_2D,		// target
					level,				// level
					x, edge_cnt,		// xoffset, yoffset
					src_rect.get_width(),		// width
					1,	// height
					format,				// format
					type,				// type
					edge_data);				// texels
			}
		}
	}
	// Restore these unpack values to the default
#ifndef __ANDROID__
	glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
	glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
#endif
}
Пример #18
0
static int check_retval(int ret, const char *funcname) {
	if (ret < GP_OK)
		throw Exception(funcname, ret);
	return ret;
}
Пример #19
0
TextureProvider *GL1TextureProvider::create_view(TextureDimensions texture_dimensions, TextureFormat texture_format, int min_level, int num_levels, int min_layer, int num_layers)
{
	throw Exception("OpenGL 1 does not support texture views");
}
Пример #20
0
Desktop *RfbClientManager::onClientAuth(RfbClient *client)
{
  // The client is now authenticated, so remove its IP from the ban list.
  StringStorage ip;
  client->getPeerHost(&ip);
  updateIpInBan(&ip, true);

  m_newConnectionEvents->onSuccAuth(&ip);

  AutoLock al(&m_clientListLocker);

  // Checking if this client is allowed to connect, depending on its "shared"
  // flag and the server's configuration.
  ServerConfig *servConf = Configurator::getInstance()->getServerConfig();
  bool isAlwaysShared = servConf->isAlwaysShared();
  bool isNeverShared = servConf->isNeverShared();

  bool isResultShared;
  if (isAlwaysShared) {
    isResultShared = true;
  } else if (isNeverShared) {
    isResultShared = false;
  } else {
    isResultShared = client->getSharedFlag();
  }

  // If the client wishes to have exclusive access then remove other clients.
  if (!isResultShared) {
    // Which client takes priority, existing or incoming?
    if (servConf->isDisconnectingExistingClients()) {
      // Incoming
      disconnectAuthClients();
    } else {
      // Existing
      if (!m_clientList.empty()) {
        throw Exception(_T("Cannot disconnect existing clients and therefore")
                        _T(" the client will be disconected")); // Disconnect this client
      }
    }
  }

  // Removing the client from the non-authorized clients list.
  for (ClientListIter iter = m_nonAuthClientList.begin();
       iter != m_nonAuthClientList.end(); iter++) {
    RfbClient *clientOfList = *iter;
    if (clientOfList == client) {
      m_nonAuthClientList.erase(iter);
      break;
    }
  }

  // Adding to the authorized list.
  m_clientList.push_back(client);

  if (m_desktop == 0 && !m_clientList.empty()) {
    // Create WinDesktop and notify listeners that the first client has been
    // connected.
    m_desktop = m_desktopFactory->createDesktop(this, this, this, m_log);
    vector<RfbClientManagerEventListener *>::iterator iter;
    for (iter = m_listeners.begin(); iter != m_listeners.end(); iter++) {
      (*iter)->afterFirstClientConnect();
    }
  }
  return m_desktop;
}
Пример #21
0
// DJB's "RSA signatures and Rabin-Williams signatures..." (http://cr.yp.to/sigs/rwsota-20080131.pdf).
Integer InvertibleRWFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &x) const
{
	DoQuickSanityCheck();

	if(!m_precompute)
		Precompute();

	ModularArithmetic modn(m_n), modp(m_p), modq(m_q);
	Integer r, rInv;

	do
	{
		// Do this in a loop for people using small numbers for testing
		r.Randomize(rng, Integer::One(), m_n - Integer::One());
		// Fix for CVE-2015-2141. Thanks to Evgeny Sidorov for reporting.
		// Squaring to satisfy Jacobi requirements suggested by Jean-Pierre Munch.
		r = modn.Square(r);
		rInv = modn.MultiplicativeInverse(r);
	} while (rInv.IsZero());

	Integer re = modn.Square(r);
	re = modn.Multiply(re, x);    // blind

	const Integer &h = re, &p = m_p, &q = m_q;
	Integer e, f;

	const Integer U = modq.Exponentiate(h, (q+1)/8);
	if(((modq.Exponentiate(U, 4) - h) % q).IsZero())
		e = Integer::One();
	else
		e = -1;

	const Integer eh = e*h, V = modp.Exponentiate(eh, (p-3)/8);
	if(((modp.Multiply(modp.Exponentiate(V, 4), modp.Exponentiate(eh, 2)) - eh) % p).IsZero())
		f = Integer::One();
	else
		f = 2;

	Integer W, X;
	#pragma omp parallel sections if(CRYPTOPP_RW_USE_OMP)
	{
		#pragma omp section
		{
			W = (f.IsUnit() ? U : modq.Multiply(m_pre_2_3q, U));
		}
		#pragma omp section
		{
			const Integer t = modp.Multiply(modp.Exponentiate(V, 3), eh);
			X = (f.IsUnit() ? t : modp.Multiply(m_pre_2_9p, t));
		}
	}
	const Integer Y = W + q * modp.Multiply(m_pre_q_p, (X - W));

	// Signature
	Integer s = modn.Multiply(modn.Square(Y), rInv);
	CRYPTOPP_ASSERT((e * f * s.Squared()) % m_n == x);

	// IEEE P1363, Section 8.2.8 IFSP-RW, p.44
	s = STDMIN(s, m_n - s);
	if (ApplyFunction(s) != x)                      // check
		throw Exception(Exception::OTHER_ERROR, "InvertibleRWFunction: computational error during private key operation");

	return s;
}
Пример #22
0
QString SimulationMaker::attributeValue(QString name, QObject *parent) const {
    QString result = attributeValue(name, "");
    if (result.isEmpty())
        throw Exception("Missing attribute '" + name + "'", parent);
    return result;
}
Пример #23
0
void MeshLoader::OnError()
{
    throw Exception("");
}
    void UdpServerTransport::cycle(
        int timeoutMs,
        const volatile bool &) //stopFlag
    {
        // poll the UDP socket for messages, and read a message if one is available

        fd_set fdSet;
        FD_ZERO(&fdSet);
        FD_SET( static_cast<SOCKET>(mFd), &fdSet);
        timeval timeout;
        timeout.tv_sec = timeoutMs/1000;
        timeout.tv_usec = 1000*(timeoutMs%1000);

        int ret = Platform::OS::BsdSockets::select(
            mFd+1,
            &fdSet,
            NULL,
            NULL,
            timeoutMs < 0 ? NULL : &timeout);

        int err = Platform::OS::BsdSockets::GetLastError();
        if (ret == 1)
        {
            SessionStatePtr sessionStatePtr = getCurrentUdpSessionStatePtr();
            if (sessionStatePtr.get() == NULL)
            {
                sessionStatePtr = SessionStatePtr(new SessionState(*this));
                SessionPtr sessionPtr = getSessionManager().createSession();
                sessionPtr->setProactor(*sessionStatePtr);
                sessionStatePtr->mSessionPtr = sessionPtr;
                setCurrentUdpSessionStatePtr(sessionStatePtr);

                RcfSessionPtr rcfSessionPtr = 
                    boost::static_pointer_cast<RcfSession>(sessionPtr);

                rcfSessionPtr->mIoState = RcfSession::Reading;
            }

            {
                // read a message

                boost::shared_ptr<std::vector<char> > &readVecPtr =
                    sessionStatePtr->mReadVecPtr;

                if (readVecPtr.get() == NULL || !readVecPtr.unique())
                {
                    readVecPtr.reset( new std::vector<char>());
                }
                std::vector<char> &buffer = *readVecPtr;

                sockaddr from;
                int fromlen = sizeof(from);
                memset(&from, 0, sizeof(from));
                buffer.resize(4);

                int len = Platform::OS::BsdSockets::recvfrom(
                    mFd,
                    &buffer[0],
                    4,
                    MSG_PEEK,
                    &from,
                    &fromlen);

                err = Platform::OS::BsdSockets::GetLastError();
                if (isClientAddrAllowed( *(sockaddr_in *) &from ) &&
                    (len == 4 || (len == -1 && err == Platform::OS::BsdSockets::ERR_EMSGSIZE)))
                {
                    sockaddr_in *remoteAddr = reinterpret_cast<sockaddr_in*>(&from);
                    sessionStatePtr->remoteAddress = IpAddress(*remoteAddr);
                    unsigned int dataLength = 0;
                    memcpy(&dataLength, &buffer[0], 4);
                    networkToMachineOrder(&dataLength, 4, 1);
                    if (dataLength <= static_cast<unsigned int>(getMaxMessageLength()))
                    {
                        buffer.resize(4+dataLength);
                        memset(&from, 0, sizeof(from));
                        fromlen = sizeof(from);

                        len = Platform::OS::BsdSockets::recvfrom(
                            mFd,
                            &buffer[0],
                            4+dataLength,
                            0,
                            &from,
                            &fromlen);

                        if (static_cast<unsigned int>(len) == 4+dataLength)
                        {
                            getSessionManager().onReadCompleted(sessionStatePtr->mSessionPtr);
                        }
                    }
                    else
                    {
                        ByteBuffer byteBuffer;
                        encodeServerError(byteBuffer, RcfError_ServerMessageLength);
                        byteBuffer.expandIntoLeftMargin(4);

                        * (boost::uint32_t *) ( byteBuffer.getPtr() ) =
                            static_cast<boost::uint32_t>(byteBuffer.getLength()-4);

                        RCF::machineToNetworkOrder(byteBuffer.getPtr(), 4, 1);

                        char *buffer = byteBuffer.getPtr();
                        std::size_t bufferLen = byteBuffer.getLength();

                        const sockaddr_in &remoteAddr =
                            sessionStatePtr->remoteAddress.getSockAddr();

                        int len = sendto(
                            mFd,
                            buffer,
                            static_cast<int>(bufferLen),
                            0,
                            (const sockaddr *) &remoteAddr,
                            sizeof(remoteAddr));

                        RCF_UNUSED_VARIABLE(len);
                        discardPacket(mFd);
                    }
                }
                else
                {
                    // discard the message (sender ip not allowed, or message format bad)
                    discardPacket(mFd);
                }
            }
        }
        else if (ret == 0)
        {
            RCF_TRACE("server udp poll - no messages")(mFd)(mPort);
        }
        else if (ret == -1)
        {
            RCF_THROW(
                Exception(
                    RcfError_Socket,
                    err,
                    RcfSubsystem_Os,
                    "udp server select() failed "))
                (mFd)(mPort)(err);
        }

    }
Пример #25
0
/** get the speed value of the MarkersReference */
void MarkersReference::getSpeedValues(const SimTK::State &s, SimTK::Array_<Vec3> &speedValues) const
{
    throw Exception("MarkersReference: getSpeedValues not implemented.");
}
    void UdpServerTransport::open()
    {
        RCF_TRACE("")(mPort)(getNetworkInterface());

        // create and bind a socket for receiving UDP messages
        if (mFd == -1 && mPort >= 0)
        {
            int ret = 0;
            int err = 0;

            // create the socket
            mFd = static_cast<int>(socket(AF_INET, SOCK_DGRAM, 0));
            if (mFd == -1)
            {
                err = Platform::OS::BsdSockets::GetLastError();
                RCF_THROW(Exception(
                    RcfError_Socket, err, RcfSubsystem_Os, "socket() failed"))
                    (mFd);
            }

            // setup the address
            std::string networkInterface = getNetworkInterface();
            sockaddr_in serverAddr;
            memset(&serverAddr, 0, sizeof(serverAddr));
            serverAddr.sin_family = AF_INET;
            serverAddr.sin_port = htons( static_cast<u_short>(mPort) );
            if (networkInterface.size() > 0)
            {
                if (isdigit(networkInterface.at(0)))
                {
                    serverAddr.sin_addr.s_addr = inet_addr(
                        networkInterface.c_str());
                }
                else
                {
                    hostent *h = gethostbyname(networkInterface.c_str());
                    if (h)
                    {
                        serverAddr.sin_addr = * (in_addr *) h->h_addr_list[0];
                    }
                }
            }
            else
            {
                serverAddr.sin_addr.s_addr = INADDR_ANY;
            }

            // enable reception of broadcast messages
            int enable = 1;
            ret = setsockopt(mFd, SOL_SOCKET, SO_BROADCAST, (char *) &enable, sizeof(enable));
            err = Platform::OS::BsdSockets::GetLastError();
            if (ret)
            {
                RCF_TRACE("Failed to set SO_BROADCAST on listening udp socket")(ret)(err);
            }

            // Share the address binding, if appropriate.
            if (mEnableSharedAddressBinding)
            {
                enable = 1;

                // Set SO_REUSEADDR socket option.
                ret = setsockopt(mFd, SOL_SOCKET, SO_REUSEADDR, (char *) &enable, sizeof(enable));
                err = Platform::OS::BsdSockets::GetLastError();
                if (ret)
                {
                    RCF_TRACE("Failed to set SO_REUSEADDR on listening udp multicast socket")(ret)(err);
                }

                // On OS X and BSD variants, need to set SO_REUSEPORT as well.

#if (defined(__MACH__) && defined(__APPLE__)) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) 

                ret = setsockopt(mFd, SOL_SOCKET, SO_REUSEPORT, (char *) &enable, sizeof(enable));
                err = Platform::OS::BsdSockets::GetLastError();
                if (ret)
                {
                    RCF_TRACE("Failed to set SO_REUSEPORT on listening udp multicast socket")(ret)(err);
                }
#endif

            }
            

            // bind the socket
            ret = ::bind(mFd, (struct sockaddr*) &serverAddr, sizeof(serverAddr));
            if (ret < 0)
            {
                err = Platform::OS::BsdSockets::GetLastError();
                RCF_THROW(Exception(
                    RcfError_Socket, err, RcfSubsystem_Os, "bind() failed"))
                    (mFd)(mPort)(networkInterface)(ret);
            }
            RCF_ASSERT( mFd != -1 )(mFd);

            if (mMulticastIp.size() > 0)
            {
                // set socket option for receiving multicast messages
            
                ip_mreq imr;
                imr.imr_multiaddr.s_addr = inet_addr(mMulticastIp.c_str());
                imr.imr_interface.s_addr = INADDR_ANY;
                int ret = setsockopt(mFd,IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*) &imr, sizeof(imr));
                int err = Platform::OS::BsdSockets::GetLastError();

                RCF_VERIFY(
                    ret ==  0,
                    Exception(
                        RcfError_Socket,
                        err,
                        RcfSubsystem_Os,
                        "setsockopt() with IPPROTO_IP/IP_ADD_MEMBERSHIP failed"))
                        (mMulticastIp)(networkInterface);

                // TODO: enable source-filtered multicast messages
                //ip_mreq_source imr;
                //imr.imr_multiaddr.s_addr = inet_addr("232.5.6.7");
                //imr.imr_sourceaddr.s_addr = INADDR_ANY;//inet_addr("10.1.1.2");
                //imr.imr_interface.s_addr = INADDR_ANY;
                //int ret = setsockopt(mFd,IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (const char*) &imr, sizeof(imr));
                //int err = Platform::OS::BsdSockets::GetLastError();
            }

            // set the socket to nonblocking mode
            Platform::OS::BsdSockets::setblocking(mFd, false);

            // retrieve the port number, if it's generated by the system
            if (mPort == 0 && (mPort = getFdPort(mFd)) == 0)
            {
                err = Platform::OS::BsdSockets::GetLastError();
                RCF_THROW(Exception(
                    RcfError_Socket, err, RcfSubsystem_Os, "getsockname() failed"))
                    (mFd)(mPort)(networkInterface)(ret);
            }
        }
    }
void ExecuteScalarSubqueriesMatcher::visit(const ASTSubquery & subquery, ASTPtr & ast, Data & data)
{
    Context subquery_context = data.context;
    Settings subquery_settings = data.context.getSettings();
    subquery_settings.max_result_rows = 1;
    subquery_settings.extremes = 0;
    subquery_context.setSettings(subquery_settings);

    ASTPtr subquery_select = subquery.children.at(0);
    BlockIO res = InterpreterSelectWithUnionQuery(
        subquery_select, subquery_context, {}, QueryProcessingStage::Complete, data.subquery_depth + 1).execute();

    Block block;
    try
    {
        block = res.in->read();

        if (!block)
        {
            /// Interpret subquery with empty result as Null literal
            auto ast_new = std::make_unique<ASTLiteral>(Null());
            ast_new->setAlias(ast->tryGetAlias());
            ast = std::move(ast_new);
            return;
        }

        if (block.rows() != 1 || res.in->read())
            throw Exception("Scalar subquery returned more than one row", ErrorCodes::INCORRECT_RESULT_OF_SCALAR_SUBQUERY);
    }
    catch (const Exception & e)
    {
        if (e.code() == ErrorCodes::TOO_MANY_ROWS)
            throw Exception("Scalar subquery returned more than one row", ErrorCodes::INCORRECT_RESULT_OF_SCALAR_SUBQUERY);
        else
            throw;
    }

    size_t columns = block.columns();
    if (columns == 1)
    {
        auto lit = std::make_unique<ASTLiteral>((*block.safeGetByPosition(0).column)[0]);
        lit->alias = subquery.alias;
        lit->prefer_alias_to_column_name = subquery.prefer_alias_to_column_name;
        ast = addTypeConversion(std::move(lit), block.safeGetByPosition(0).type->getName());
    }
    else
    {
        auto tuple = std::make_shared<ASTFunction>();
        tuple->alias = subquery.alias;
        ast = tuple;
        tuple->name = "tuple";
        auto exp_list = std::make_shared<ASTExpressionList>();
        tuple->arguments = exp_list;
        tuple->children.push_back(tuple->arguments);

        exp_list->children.resize(columns);
        for (size_t i = 0; i < columns; ++i)
        {
            exp_list->children[i] = addTypeConversion(
                std::make_unique<ASTLiteral>((*block.safeGetByPosition(i).column)[0]),
                block.safeGetByPosition(i).type->getName());
        }
    }
}
Пример #28
0
	void DXBC_Reader::skip_bytes(int size)
	{
		if (get_remaining() < size)
			throw Exception("Unknown DXBC format");
		read_ptr += size;
	}
Пример #29
0
void Http::Request::recv(Socket &sock, bool parsePost)
{
	this->sock = &sock;

	clear();

	// Read first line
	String line;
	if(!sock.readLine(line)) throw NetException("Connection closed");
	method.clear();
	url.clear();
	line.readString(method);
	line.readString(url);

	String protocol;
	line.readString(protocol);
	version = protocol.cut('/');

	if(url.empty() || version.empty() || protocol != "HTTP")
		throw 400;

	if(method != "GET" && method != "POST" && method != "HEAD")
		throw 405;

	// Read headers
	while(true)
	{
		String line;
		AssertIO(sock.readLine(line));
		if(line.empty()) break;

		String value = line.cut(':');
		line.trim();
		value.trim();
		headers.insert(line,value);
	}

	// Read cookies
	String cookie;
	if(headers.get("Cookie", cookie))
	{
		while(!cookie.empty())
		{
			String next = cookie.cut(';');
			String value = cookie.cut('=');
			cookie.trim();
			value.trim();
			cookies.insert(cookie,value);
			cookie = next;
		}
	}

	fullUrl = url;
	
	// Read URL variables
	String getData = url.cut('?');
	if(!getData.empty())
	{
		List<String> exploded;
		getData.explode(exploded,'&');
		for(	List<String>::iterator it = exploded.begin();
				it != exploded.end();
				++it)
		{
			String value = it->cut('=').urlDecode();
			get.insert(it->urlDecode(), value);
		}
	}

	url = url.urlDecode();
	
	String expect;
	if((headers.get("Expect",expect) && expect.toLower() == "100-continue")
		|| (method == "POST" && version == "1.1"))
	{
		sock.write("HTTP/1.1 100 Continue\r\n\r\n");
	}
	
	// Read post variables
	if(method == "POST" && parsePost)
	{
		if(!headers.contains("Content-Length"))
			throw Exception("Missing Content-Length header in POST request");

		size_t contentLength = 0;
		headers["Content-Length"].extract(contentLength);
		
		String contentType;
		if(headers.get("Content-Type", contentType))
		{
			String parameters = contentType.cut(';');
			contentType.trim();
			
			if(contentType == "application/x-www-form-urlencoded")
			{
				String data;
				if(sock.read(data, contentLength) != contentLength)
					throw NetException("Connection unexpectedly closed");
			  
				List<String> exploded;
				data.explode(exploded,'&');
				for(	List<String>::iterator it = exploded.begin();
						it != exploded.end();
						++it)
				{
					String value = it->cut('=').urlDecode();
					post.insert(it->urlDecode(), value);
				}
			}
			else if(contentType == "multipart/form-data")
			{
				String boundary;
				while(true)
				{
					String key;
			  		if(!parameters.readUntil(key,';')) break;
					String value = key.cut('=');
					key.trim();
					value.trim();
					value.trimQuotes();
					if(key == "boundary") boundary = String("--") + value;
				}
				
				Assert(!boundary.empty());
				
				String line;
				while(line.empty()) AssertIO(sock.readLine(line));
				Assert(line == boundary);
				
				bool finished = false;
				while(!finished)
				{
					StringMap mimeHeaders;
					while(true)
					{
						String line;
						AssertIO(sock.readLine(line));
						if(line.empty()) break;
						
						String value = line.cut(':');
						line.trim();
						value.trim();
						mimeHeaders.insert(line,value);
					}
					
					String contentType;
					if(mimeHeaders.get("Content-Type", contentType))
					{
						String parameters = contentType.cut(';');
						contentType.trim();
					}
					
					String contentDisposition;
					if(!mimeHeaders.get("Content-Disposition", contentDisposition))
						throw Exception("Missing Content-Disposition header in multipart POST request");
					
					String parameters = contentDisposition.cut(';');
					contentDisposition.trim();
					
					String name, fileName;
					while(true)
					{
						String key;
			  			if(!parameters.readUntil(key,';')) break;
						String value = key.cut('=');
						key.trim();
						value.trim();
						value.trimQuotes();
						if(key == "name") name = value;
						else if(key == "filename") fileName = value;
					}
					
					Stream *stream = NULL;
					if(fileName.empty()) stream = &post[name];
					else {
						post[name] = fileName;
						TempFile *tempFile = new TempFile();
						files[name] = tempFile;
						stream = tempFile;
						LogDebug("Http::Request", String("File upload: ") + fileName);
					}
	
					String contentLength;
					if(mimeHeaders.get("Content-Length", contentLength))
					{
						size_t size = 0;
						contentLength >> size;
						sock.read(*stream,size);
						
						String line;
						AssertIO(sock.readLine(line));
						AssertIO(sock.readLine(line));
						if(line == boundary + "--") finished = true;
						else AssertIO(line == boundary);
					}
					else {
					  	/*String line;
						while(sock.readLine(line))
						{
							if(line == boundary) break;
							if(stream) stream->write(line);
							line.clear();
						}*/
						
						// TODO: This should be replaced with Boyer-Moore algorithm for performance
						String bound = String("\r\n") + boundary;
						char *buffer = new char[bound.size()];
						try {
							size_t size = 0;
							size_t c = 0;
							size_t i = 0;
							while(true)
							{
								if(c == size)
								{
									c = 0;
									size = sock.readData(buffer,bound.size()-i);
									AssertIO(size);
								}
								
								if(buffer[c] == bound[i])
								{
									++i; ++c;
									if(i == bound.size()) 
									{
										// If we are here there is no data left in buffer
										String line;
										AssertIO(sock.readLine(line));
										if(line == "--") finished = true;
										break;
									}
								}
								else {
								  	if(i) stream->writeData(bound.data(), i);
									
									// WARNING: this works only if the pattern is not redundant
									i = c;
									while(c != size && buffer[c] != bound[0]) ++c;
									if(c != i) stream->writeData(buffer + i, c - i);
									i = 0;
								}
							}
						}	  
						catch(...)
						{
							delete[] buffer;
							throw;
						}
						delete[] buffer;
					}
				}
Пример #30
0
int _tmain(int argc, _TCHAR* argv[])
{
    try
    {
        require( argc == 3, USAGE );
        require( fileExists( argv[1] ), "File not found" );
        require( fileExists( argv[2] ), "File not found" );

        TCOMIXMLDOMDocument3 xml = Msxml2_tlb::CoDOMDocument60::Create();
        TCOMIXMLDOMDocument3 xsl = Msxml2_tlb::CoDOMDocument60::Create();
        xsl->resolveExternals = VARIANT_TRUE;

        load( xml, argv[1] );
        load( xsl, argv[2] );

        BSTR result = NULL;
        Msxml2_tlb::IXMLDOMNodePtr pXSLDOM = xsl->documentElement;

        HRESULT hr = xml->transformNode( pXSLDOM, &result );

        if (FAILED(hr))
        {
            WideString errMsg = L"Failure code obtained from transformNode. ";

            // Try to get extended error info...
            IErrorInfo* errorInfo = NULL;

            if ( SUCCEEDED( GetErrorInfo( 0, &errorInfo ) ) )
            {
                boost::shared_ptr<void> releaseOnExit( errorInfo, release );

                BSTR reason = NULL;

                if ( SUCCEEDED( errorInfo->GetDescription( &reason ) ) )
                {
                    boost::shared_ptr<void> freeStringOnExit( reason, freeString );

                    if ( reason )
                    {
                        errMsg += WideString(reason);
                    }
                }
            }

            throw Exception( UnicodeString( errMsg ) );
        }

        boost::shared_ptr<void> freeStringOnExit( result, freeString );

        WideString ws(result);
        std::wcout << (wchar_t*)ws;

        return 0;
    }
    catch( Exception& e )
    {
        printError( e.Message );
    }
    catch( const std::exception& e )
    {
        printError( e.what() );
    }
    catch( ... )
    {
        printError( "Unspecified exception" );
    }
	return 1;
}