示例#1
0
QDomDocument TestLanguageFiles::loadDomDocument(const QUrl &path, const QXmlSchema &schema) const
{
    QDomDocument document;
    QXmlSchemaValidator validator(schema);
    if (!validator.validate(path)) {
        qWarning() << "Schema is not valid, aborting loading of XML document:" << path.toLocalFile();
        return document;
    }

    QString errorMsg;
    QFile file(path.toLocalFile());
    if (file.open(QIODevice::ReadOnly)) {
        if (!document.setContent(&file, &errorMsg)) {
            qWarning() << errorMsg;
        }
    } else {
        qWarning() << "Could not open XML document " << path.toLocalFile() << " for reading, aborting.";
    }
    return document;
}
void
RestRollupsUri::handle_delete(http_request request)
{
    std::cout << request.method() << " : " << request.absolute_uri().path() << std::endl;
    int rc = 0;
    std::string resultstr;
    std::pair<bool, std::string> result {true, std::string()};

    char json[1024];

    // extract json from request
    snprintf(json, sizeof(json), "%s", request.extract_string(true).get().c_str());
    std::cout << "JSON:\n" << json << std::endl;

    rapidjson::Document document; 
    if (document.Parse(json).HasParseError())
    {
        rc = 1;
        resultstr += "document invalid";
    }

    rapidjson::SchemaValidator validator(*_schema);
    if (!document.Accept(validator)) {
        rc = 1;
        resultstr += get_schema_validation_error(&validator);
    }

    Value::MemberIterator name = document.FindMember("name");

    // Execute Ivy Engine command
    if (rc == 0)
    {
        std::unique_lock<std::mutex> u_lk(goStatementMutex);
        std::pair<int, std::string> 
        rslt = m_s.delete_rollup(name->value.GetString());
    }

    http_response response(status_codes::OK);
    make_response(response, resultstr, result);
    request.reply(response);
}
示例#3
0
文件: validate.cpp 项目: G-Node/nix
Result validate(const Tag &tag) {
    Result result_base = validate_entity_with_sources(tag);
    Result result = validator({
        must(tag, &Tag::position, notEmpty(), "position is not set!"),
        could(tag, &Tag::references, notEmpty(), {
            must(tag, &Tag::position, positionsMatchRefs(tag.references()),
                "number of entries in position does not match number of dimensions in all referenced DataArrays!"),
            could(tag, &Tag::extent, notEmpty(), {
                must(tag, &Tag::position, extentsMatchPositions(tag.extent()), "Number of entries in position and extent do not match!"),
                must(tag, &Tag::extent, extentsMatchRefs(tag.references()),
                    "number of entries in extent does not match number of dimensions in all referenced DataArrays!") })
        }),
        // check units for validity
        could(tag, &Tag::units, notEmpty(), {
            must(tag, &Tag::units, isValidUnit(), "Unit is invalid: not an atomic SI. Note: So far composite units are not supported!"),
            must(tag, &Tag::references, tagRefsHaveUnits(tag.units()), "Some of the referenced DataArrays' dimensions don't have units where the tag has. Make sure that all references have the same number of dimensions as the tag has units and that each dimension has a unit set."),
                must(tag, &Tag::references, tagUnitsMatchRefsUnits(tag.units()), "Some of the referenced DataArrays' dimensions have units that are not convertible to the units set in tag. Note: So far composite SI units are not supported!")}),
    });

    return result.concat(result_base);
}
void AssociatedURLLoader::ClientAdapter::didReceiveResponse(unsigned long, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)
{
    ASSERT_UNUSED(handle, !handle);
    if (!m_client)
        return;

    // Try to use the original ResourceResponse if possible.
    WebURLResponse validatedResponse = WrappedResourceResponse(response);
    HTTPResponseHeaderValidator validator(m_options.crossOriginRequestPolicy == WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl);
    if (!m_options.exposeAllResponseHeaders)
        validatedResponse.visitHTTPHeaderFields(&validator);

    // If there are blocked headers, copy the response so we can remove them.
    const HTTPHeaderSet& blockedHeaders = validator.blockedHeaders();
    if (!blockedHeaders.isEmpty()) {
        validatedResponse = WebURLResponse(validatedResponse);
        HTTPHeaderSet::const_iterator end = blockedHeaders.end();
        for (HTTPHeaderSet::const_iterator it = blockedHeaders.begin(); it != end; ++it)
            validatedResponse.clearHTTPHeaderField(*it);
    }
    m_client->didReceiveResponse(m_loader, validatedResponse);
}
示例#5
0
void URLFormWidget::validateData()
{
    bool valid;

    QString editMetadata = MetadataEngine::getInstance().getFieldProperties(
                MetadataEngine::EditProperty, getFieldId());
    FormWidgetValidator validator(editMetadata, MetadataEngine::URLTextType);
    QString errorMessage;

    valid = validator.validate(getData(), errorMessage);

    if (valid) {
        emit dataEdited();
    } else {
        //restore last valid value
        m_lineEdit->undo();

        //inform FormView that the widget needs attention
        //by animating the widget
        emit requiresAttention(errorMessage);
    }
}
示例#6
0
Extension::Validity Extension::validate()
{
    // Skips the validation if already done.
    if( m_validity != UnknownValidity )
    {
        return m_validity;
    }

    // Retrieves the extension point.
    Runtime * rntm( Runtime::getDefault() );
     ::boost::shared_ptr< ExtensionPoint >  point( rntm->findExtensionPoint(m_point) );

    // Checks that the point exists.
    if( !point )
    {
        throw RuntimeException(m_point + " : invalid point reference.");
    }

    // Validates the extension.
    ::boost::shared_ptr< io::Validator >   validator( point->getExtensionValidator() );
    OSLM_ASSERT("Sorry, validator creation failed for point "<<point->getIdentifier(), validator );

    // Check extension XML Node <extension id="xxx" implements="yyy" >...</extension>
    validator->clearErrorLog();
    if( validator->validate( m_xmlNode ) == true )
    {
        m_validity = Valid;
    }
    else
    {
        m_validity = Invalid;
        const std::string   identifier = m_id.empty() ? "anonymous" : m_id;
        OSLM_ERROR("In bundle " << getBundle()->getIdentifier() << ". " << identifier
                << ": invalid extension XML element node does not respect schema. Verification error log is : "
                << std::endl << validator->getErrorLog() );
    }

    return m_validity;
}
void tst_QXmlSchemaValidator::constructorQXmlNamePool() const
{
    // test that the name pool from the schema is used by
    // the schema validator as well
    QXmlSchema schema;

    QXmlNamePool np = schema.namePool();

    const QXmlName name(np, QLatin1String("localName"),
                            QLatin1String("http://example.com/"),
                            QLatin1String("prefix"));

    QXmlSchemaValidator validator(schema);

    QXmlNamePool np2(validator.namePool());
    QCOMPARE(name.namespaceUri(np2), QString::fromLatin1("http://example.com/"));
    QCOMPARE(name.localName(np2), QString::fromLatin1("localName"));
    QCOMPARE(name.prefix(np2), QString::fromLatin1("prefix"));

    // make sure namePool() is const
    const QXmlSchemaValidator constValidator(schema);
    np = constValidator.namePool();
}
void tst_QXmlSchemaValidator::defaultConstructor() const
{
    /* Allocate instance in different orders. */
    {
        QXmlSchema schema;
        QXmlSchemaValidator validator(schema);
    }

    {
        QXmlSchema schema1;
        QXmlSchema schema2;

        QXmlSchemaValidator validator1(schema1);
        QXmlSchemaValidator validator2(schema2);
    }

    {
        QXmlSchema schema;

        QXmlSchemaValidator validator1(schema);
        QXmlSchemaValidator validator2(schema);
    }
}
示例#9
0
int  Parser::evaluator(Token op, int value1, int value2){
	// validator!!
	validator(value1, value2,op);
	switch (op)
	{
	case T_PLUS:
		return value1 + value2;
	case T_MINUS:
		return value1 - value2;
	case T_MULTIPLY:
		return value1 * value2;
	case T_DIVIDE:
		return value1 / value2;
	case T_EXP:
		return int(std::pow(value1 ,value2));
	case T_MODULO:
		return value1 % value2;
	default:
		std::cout << "Error in Operation\n";
		return -1;
			
	}
}
示例#10
0
FileReader::FileReader(QString fileName, QAbstractItemModel* d, MyWidget* p) : file(fileName), model(d), parent(p) {
    QByteArray data("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
                    "<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
                    "<xsd:element name=\"chart\" type=\"chartType\"/>"
                    "	<xsd:complexType name=\"chartType\">"
                    "		<xsd:sequence>"
                    "			<xsd:element name=\"title\" type=\"xsd:string\"/>"
                    "			<xsd:element name=\"xlabel\" type=\"xsd:string\" minOccurs=\"0\"/>"
                    "			<xsd:element name=\"ylabel\" type=\"xsd:string\" minOccurs=\"0\"/>"
                    "			<xsd:element name=\"point\" type=\"pointType\" maxOccurs=\"unbounded\"/>"
                    "		</xsd:sequence>"
                    "	</xsd:complexType>"
                    "	<xsd:complexType name=\"pointType\">"
                    "		<xsd:sequence>"
                    "			<xsd:element name=\"x\" type=\"xsd:string\"/>"
                    "			<xsd:element name=\"y\" type=\"xsd:string\"/>"
                    "		</xsd:sequence>"
                    "	</xsd:complexType>"
                    "</xsd:schema>");
    if(!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(parent, tr("qCharts"), tr("Cannot read file %1:\n%2.").arg(fileName).arg(file.errorString()));
        return;
    }
    QXmlSchema schema;
    schema.load(data);
    if(schema.isValid()) {
        QXmlSchemaValidator validator(schema);
        if(validator.validate(&file, QUrl::fromLocalFile(file.fileName()))){
            isReadable=true;
        }
        else {
            isReadable=false;
            QMessageBox::warning(this, tr("qCharts"), tr("The file that you are trying to open isn't valid."));
        }
    }
    file.close();
}
void UserVariableOptionsWidget::newClicked()
{
    class Validator : public QValidator
    {
    public:
        Validator(KoVariableManager *variableManager) : m_variableManager(variableManager) {}
        virtual State validate(QString &input, int &) const
        {
            QString s = input.trimmed();
            return s.isEmpty() || m_variableManager->userVariables().contains(s) ? Intermediate : Acceptable;
        }
    private:
        KoVariableManager *m_variableManager;
    };
    Validator validator(variableManager());
    QString name = KInputDialog::getText(i18n("New Variable"), i18n("Name for new variable:"), QString(), 0, this, &validator).trimmed();
    if (name.isEmpty()) {
        return;
    }
    userVariable->setName(name);
    variableManager()->setValue(userVariable->name(), QString(), QLatin1String("string"));
    updateNameEdit();
    valueEdit->setFocus();
}
示例#12
0
void Feed::CheckFeed() {
  m_lastChecked = boost::posix_time::microsec_clock::universal_time();
  cURL::EasyInterface easy(m_url, m_etag);
  switch (easy.PerformRequest()) {
    case 200: {
      m_etag = easy.GetResponseEtag();
      FeedValidator validator(easy.GetResponseData(), *this);
      validator.Validate(m_feedData);
      m_valid = true;
      if (m_valid) {
        CreateEntries(m_feedData);
      }
      return;
    }
    case 304: {
      m_valid = true;
      return;
    }
    default: {
      m_entries.clear();
      m_valid = false;
    }
  }
}
示例#13
0
 bool MainWindow::validate()
 {
     QUrl url("qrc:/resources/peach.xsd");

     const QByteArray instanceData = completingTextEdit->toPlainText().toUtf8();

     MessageHandler messageHandler;

     QXmlSchema schema;
     schema.setMessageHandler(&messageHandler);

     schema.load(url);

     bool errorOccurred = false;
     if (!schema.isValid()) {
         errorOccurred = true;
     } else {
         QXmlSchemaValidator validator(schema);
         if (!validator.validate(instanceData))
             errorOccurred = true;
     }

     if (errorOccurred) {
         statusLabel->setText(messageHandler.statusMessage());
         moveCursor(messageHandler.line(), messageHandler.column());
         return false;
     } else {
         statusLabel->setText(tr("Validation successful"));
         return true;
     }

     const QString styleSheet = QString("QstatusLabel {background: %1; padding: 3px}")
                                       .arg(errorOccurred ? QColor(Qt::red).lighter(160).name() :
                                                            QColor(Qt::green).lighter(160).name());
     statusLabel->setStyleSheet(styleSheet);
 }
示例#14
0
void peanoclaw::tests::StatisticsTest::testGetNeighborPositionOnDifferentLevel() {
  tarch::la::Vector<DIMENSIONS, double> position(1.0/3.0);
  tarch::la::Vector<DIMENSIONS, double> size(1.0/3.0);
  int level = 2;
  tarch::la::Vector<DIMENSIONS, double> expectedNeighborPosition;
  assignList(expectedNeighborPosition) =
      2.0/3.0
      ,0.0
      #ifdef Dim3
      ,0.0
      #endif
      ;
  tarch::la::Vector<DIMENSIONS, int> discreteNeighborPosition;
  assignList(discreteNeighborPosition) =
      1
      ,-1
      #ifdef Dim3
      ,-1
      #endif
      ;

  tarch::la::Vector<DIMENSIONS, double> domainOffset(0.0);
  tarch::la::Vector<DIMENSIONS, double> domainSize(1.0);
  peanoclaw::statistics::ParallelGridValidator validator(domainOffset, domainSize, false);

  tarch::la::Vector<DIMENSIONS, double> neighborPosition
    = validator.getNeighborPositionOnLevel(
      position,
      size,
      level,
      level,
      discreteNeighborPosition
    );

  validateWithParams2(tarch::la::equals(neighborPosition, expectedNeighborPosition), neighborPosition, expectedNeighborPosition);
}
示例#15
0
shared_ptr<ValidationError> PersonValidator::validateEmail() const {
    auto editor = dynamic_cast<QLineEdit *>(mFieldEditors["email"]);
    auto text = editor->text().trimmed();
    if (text.isEmpty()) {
        return nullptr;
    }

    if (text.size() > 64) {
        return make_shared<ValidationError>(
            editor, tr("Invalid data entered"),
            tr("The email cannot be longer than 64 characters."));
    }

    QRegExp regExp("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b",
                   Qt::CaseInsensitive);
    QRegExpValidator validator(regExp);
    int pos = 0;
    if (validator.validate(text, pos) != QValidator::Acceptable) {
        return make_shared<ValidationError>(
            editor, tr("Invalid data entered"),
            tr("You need to provide a valid person's email address."));
    }
    return nullptr;
}
示例#16
0
static enum misc_command_type
process_next_line (char *p, struct command_line **command, int parse_commands,
		   void (*validator)(char *, void *), void *closure)
{
  char *p_end;
  char *p_start;
  int not_handled = 0;

  /* Not sure what to do here.  */
  if (p == NULL)
    return end_command;

  /* Strip trailing whitespace.  */
  p_end = p + strlen (p);
  while (p_end > p && (p_end[-1] == ' ' || p_end[-1] == '\t'))
    p_end--;

  p_start = p;
  /* Strip leading whitespace.  */
  while (p_start < p_end && (*p_start == ' ' || *p_start == '\t'))
    p_start++;

  /* 'end' is always recognized, regardless of parse_commands value.
     We also permit whitespace before end and after.  */
  if (p_end - p_start == 3 && !strncmp (p_start, "end", 3))
    return end_command;
  
  if (parse_commands)
    {
      /* If commands are parsed, we skip initial spaces.  Otherwise,
	 which is the case for Python commands and documentation
	 (see the 'document' command), spaces are preserved.  */
      p = p_start;

      /* Blanks and comments don't really do anything, but we need to
	 distinguish them from else, end and other commands which can
	 be executed.  */
      if (p_end == p || p[0] == '#')
	return nop_command;

      /* Is the else clause of an if control structure?  */
      if (p_end - p == 4 && !strncmp (p, "else", 4))
	return else_command;

      /* Check for while, if, break, continue, etc and build a new
	 command line structure for them.  */
      if ((p_end - p >= 14 && !strncmp (p, "while-stepping", 14))
	  || (p_end - p >= 8 && !strncmp (p, "stepping", 8))
	  || (p_end - p >= 2 && !strncmp (p, "ws", 2)))
	{
	  /* Because validate_actionline and encode_action lookup
	     command's line as command, we need the line to
	     include 'while-stepping'.

	     For 'ws' alias, the command will have 'ws', not expanded
	     to 'while-stepping'.  This is intentional -- we don't
	     really want frontend to send a command list with 'ws',
	     and next break-info returning command line with
	     'while-stepping'.  This should work, but might cause the
	     breakpoint to be marked as changed while it's actually
	     not.  */
	  *command = build_command_line (while_stepping_control, p);
	}
      else if (p_end - p > 5 && !strncmp (p, "while", 5))
	{
	  char *first_arg;

	  first_arg = p + 5;
	  while (first_arg < p_end && isspace (*first_arg))
	    first_arg++;
	  *command = build_command_line (while_control, first_arg);
	}
      else if (p_end - p > 2 && !strncmp (p, "if", 2))
	{
	  char *first_arg;

	  first_arg = p + 2;
	  while (first_arg < p_end && isspace (*first_arg))
	    first_arg++;
	  *command = build_command_line (if_control, first_arg);
	}
      else if (p_end - p >= 8 && !strncmp (p, "commands", 8))
	{
	  char *first_arg;

	  first_arg = p + 8;
	  while (first_arg < p_end && isspace (*first_arg))
	    first_arg++;
	  *command = build_command_line (commands_control, first_arg);
	}
      else if (p_end - p == 6 && !strncmp (p, "python", 6))
	{
	  /* Note that we ignore the inline "python command" form
	     here.  */
	  *command = build_command_line (python_control, "");
	}
      else if (p_end - p == 10 && !strncmp (p, "loop_break", 10))
	{
	  *command = (struct command_line *)
	    xmalloc (sizeof (struct command_line));
	  (*command)->next = NULL;
	  (*command)->line = NULL;
	  (*command)->control_type = break_control;
	  (*command)->body_count = 0;
	  (*command)->body_list = NULL;
	}
      else if (p_end - p == 13 && !strncmp (p, "loop_continue", 13))
	{
	  *command = (struct command_line *)
	    xmalloc (sizeof (struct command_line));
	  (*command)->next = NULL;
	  (*command)->line = NULL;
	  (*command)->control_type = continue_control;
	  (*command)->body_count = 0;
	  (*command)->body_list = NULL;
	}
      else
	not_handled = 1;
    }

  if (!parse_commands || not_handled)
    {
      /* A normal command.  */
      *command = (struct command_line *)
	xmalloc (sizeof (struct command_line));
      (*command)->next = NULL;
      (*command)->line = savestring (p, p_end - p);
      (*command)->control_type = simple_control;
      (*command)->body_count = 0;
      (*command)->body_list = NULL;
    }

  if (validator)
    {
      volatile struct gdb_exception ex;

      TRY_CATCH (ex, RETURN_MASK_ALL)
	{
	  validator ((*command)->line, closure);
	}
      if (ex.reason < 0)
	{
	  xfree (*command);
	  throw_exception (ex);
	}
    }
::boost::shared_ptr<Bundle> BundleDescriptorReader::createBundle(const ::boost::filesystem::path& location) throw(RuntimeException)
{
    ::boost::shared_ptr<Bundle> bundle;
    // Get the descriptor location.
    ::boost::filesystem::path completeLocation = location;
    if(!completeLocation.is_complete())
    {
        completeLocation = ::boost::filesystem::current_path() / location;
    }

    ::boost::filesystem::path descriptorLocation(location / "plugin.xml");
    if(::boost::filesystem::exists(descriptorLocation) == false)
    {
        throw RuntimeException("'plugin.xml': file not found.");
    }

    // Validation
    std::ostringstream fileLocation;
    fileLocation << "share/fwRuntime_" <<  FWRUNTIME_VER << "/plugin.xsd";
    const ::boost::filesystem::path pluginXSDLocation( ::boost::filesystem::current_path() / fileLocation.str() );

    Validator   validator(pluginXSDLocation);
    if( validator.validate(descriptorLocation) == false )
    {
        throw RuntimeException("Invalid bundle descriptor file. " + validator.getErrorLog());
    }

    // Get the document.
#if BOOST_FILESYSTEM_VERSION > 2
    xmlDocPtr document = xmlParseFile(  descriptorLocation.string().c_str() );
#else
    xmlDocPtr document = xmlParseFile(  descriptorLocation.native_file_string().c_str() );
#endif
    if(document == 0)
    {
        throw RuntimeException("Unable to read the bundle descriptor file.");
    }


    try
    {
        // Get the root node.
        xmlNodePtr rootNode = xmlDocGetRootElement(document);

        if (xmlXIncludeProcessTreeFlags (rootNode, XML_PARSE_NOBASEFIX) == -1)
        {
            throw RuntimeException("Unable to manage xinclude !");
        }

        if(xmlStrcmp(rootNode->name, (const xmlChar*) PLUGIN.c_str()) != 0)
        {
            throw RuntimeException("Unexpected XML element");
        }

        // Creates and process the plugin element.
        bundle = processPlugin(rootNode, completeLocation);

        // Job's done!
        xmlFreeDoc(document);

    }
    catch(std::exception& exception)
    {
        xmlFreeDoc(document);
        throw ;
    }
    return bundle;
}
示例#18
0
sk_sp<SkImage> SkImage::MakeFromGenerator(std::unique_ptr<SkImageGenerator> generator,
                                          const SkIRect* subset) {
    SkImage_Lazy::Validator validator(SharedGenerator::Make(std::move(generator)), subset, nullptr);

    return validator ? sk_make_sp<SkImage_Lazy>(&validator) : nullptr;
}
示例#19
0
svn_error_t *
svn_wc_relocate4(svn_wc_context_t *wc_ctx,
                 const char *local_abspath,
                 const char *from,
                 const char *to,
                 svn_wc_relocation_validator3_t validator,
                 void *validator_baton,
                 apr_pool_t *scratch_pool)
{
  svn_node_kind_t kind;
  const char *repos_relpath;
  const char *old_repos_root, *old_url;
  const char *new_repos_root, *new_url;
  size_t from_len;
  size_t old_url_len;
  const char *uuid;
  svn_boolean_t is_wc_root;

  SVN_ERR(svn_wc__is_wcroot(&is_wc_root, wc_ctx, local_abspath,
                            scratch_pool));
  if (! is_wc_root)
    {
      const char *wcroot_abspath;
      svn_error_t *err;

      err = svn_wc__db_get_wcroot(&wcroot_abspath, wc_ctx->db,
                                  local_abspath, scratch_pool, scratch_pool);
      if (err)
        {
          svn_error_clear(err);
          return svn_error_createf(
            SVN_ERR_WC_INVALID_OP_ON_CWD, NULL,
            _("Cannot relocate '%s' as it is not the root of a working copy"),
            svn_dirent_local_style(local_abspath, scratch_pool));
        }
      else
        {
          return svn_error_createf(
            SVN_ERR_WC_INVALID_OP_ON_CWD, NULL,
            _("Cannot relocate '%s' as it is not the root of a working copy; "
              "try relocating '%s' instead"),
            svn_dirent_local_style(local_abspath, scratch_pool),
            svn_dirent_local_style(wcroot_abspath, scratch_pool));
        }
    }

  SVN_ERR(svn_wc__db_read_info(NULL, &kind, NULL, &repos_relpath,
                               &old_repos_root, &uuid,
                               NULL, NULL, NULL, NULL, NULL, NULL,
                               NULL, NULL, NULL, NULL, NULL, NULL,
                               NULL, NULL, NULL, NULL, NULL, NULL,
                               NULL, NULL, NULL,
                               wc_ctx->db, local_abspath, scratch_pool,
                               scratch_pool));

  if (kind != svn_node_dir)
    return svn_error_create(SVN_ERR_CLIENT_INVALID_RELOCATION, NULL,
                            _("Cannot relocate a single file"));

  old_url = svn_path_url_add_component2(old_repos_root, repos_relpath,
                                        scratch_pool);
  old_url_len = strlen(old_url);
  from_len = strlen(from);
  if ((from_len > old_url_len) || (strncmp(old_url, from, strlen(from)) != 0))
    return svn_error_createf(SVN_ERR_WC_INVALID_RELOCATION, NULL,
                             _("Invalid source URL prefix: '%s' (does not "
                               "overlap target's URL '%s')"),
                             from, old_url);

  if (old_url_len == from_len)
    new_url = to;
  else
    new_url = apr_pstrcat(scratch_pool, to, old_url + from_len, (char *)NULL);
  if (! svn_path_is_url(new_url))
    return svn_error_createf(SVN_ERR_WC_INVALID_RELOCATION, NULL,
                             _("Invalid relocation destination: '%s' "
                               "(not a URL)"), new_url);

  new_repos_root = url_remove_final_relpath(new_url, repos_relpath,
                                            scratch_pool, scratch_pool);
  if (!new_repos_root)
    return svn_error_createf(SVN_ERR_WC_INVALID_RELOCATION, NULL,
                             _("Invalid relocation destination: '%s' "
                               "(does not point to target)" ), new_url);

  SVN_ERR(validator(validator_baton, uuid, new_url, new_repos_root,
                    scratch_pool));

  return svn_error_trace(svn_wc__db_global_relocate(wc_ctx->db, local_abspath,
                                                    new_repos_root,
                                                    scratch_pool));
}
示例#20
0
QT_USE_NAMESPACE

int main(int argc, char **argv)
{
    enum ExitCode
    {
        Valid = 0,
        Invalid,
        ParseError
    };

    enum ExecutionMode
    {
        InvalidMode,
        SchemaOnlyMode,
        InstanceOnlyMode,
        SchemaAndInstanceMode
    };

    const QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(QLatin1String("xmlpatternsvalidator"));

    QStringList arguments = QCoreApplication::arguments();
    if (arguments.size() != 2 && arguments.size() != 3) {
        qDebug() << QXmlPatternistCLI::tr("usage: xmlpatternsvalidator (<schema url> | <instance url> <schema url> | <instance url>)");
        return ParseError;
    }

    // parse command line arguments
    ExecutionMode mode = InvalidMode;

    QUrl schemaUri;
    QUrl instanceUri;

    {
        QUrl url = arguments[1];

        if (url.isRelative())
            url = QUrl::fromLocalFile(arguments[1]);

        if (arguments.size() == 2) {
            // either it is a schema or instance document

            if (arguments[1].toLower().endsWith(QLatin1String(".xsd"))) {
                schemaUri = url;
                mode = SchemaOnlyMode;
            } else {
                // as we could validate all types of xml documents, don't check the extension here
                instanceUri = url;
                mode = InstanceOnlyMode;
            }
        } else if (arguments.size() == 3) {
            instanceUri = url;
            schemaUri = arguments[2];

            if (schemaUri.isRelative())
                schemaUri = QUrl::fromLocalFile(schemaUri.toString());

            mode = SchemaAndInstanceMode;
        }
    }

    // Validate schema
    QXmlSchema schema;
    if (InstanceOnlyMode != mode) {
        schema.load(schemaUri);
        if (!schema.isValid())
            return Invalid;
    }

    if (SchemaOnlyMode == mode)
        return Valid;

    // Validate instance
    QXmlSchemaValidator validator(schema);
    if (validator.validate(instanceUri))
        return Valid;

    return Invalid;
}
AddDirectory::AddDirectory(QString *num,QWidget *parent,const char *name)
  : QDialog(parent,name,true)
{
  add_number=num;

  //
  // Fix the Window Size
  //
  setMinimumWidth(sizeHint().width());
  setMinimumHeight(sizeHint().height());
  setMaximumWidth(sizeHint().width());
  setMaximumHeight(sizeHint().height());

  setCaption("Call Administrator - Add Directory");

  //
  // Create Fonts
  //
  QFont label_font=QFont("Helvetica",12,QFont::Bold);
  label_font.setPixelSize(12);
  QFont font=QFont("Helvetica",12,QFont::Normal);
  font.setPixelSize(12);

  //
  // Validator
  //
  QIntValidator validator(this,"validator");
  validator.setRange(100,999999);

  //
  // Number
  //
  add_number_edit=new QLineEdit(this,"add_number_edit");
  add_number_edit->setGeometry(100,10,120,20);
  add_number_edit->setFont(font);
  add_number_edit->setMaxLength(6);
  add_number_edit->setValidator(&validator);
  QLabel *label=
    new QLabel(add_number_edit,"Number:",this,"add_number_label");
  label->setGeometry(10,10,85,20);
  label->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
  label->setFont(label_font);

  //
  //  OK Button
  //
  QPushButton *button=new QPushButton(this,"ok_button");
  button->setGeometry(sizeHint().width()-180,sizeHint().height()-60,80,50);
  button->setDefault(true);
  button->setFont(label_font);
  button->setText("&OK");
  connect(button,SIGNAL(clicked()),this,SLOT(okData()));

  //
  //  Cancel Button
  //
  button=new QPushButton(this,"cancel_button");
  button->setGeometry(sizeHint().width()-90,sizeHint().height()-60,80,50);
  button->setFont(label_font);
  button->setText("&Cancel");
  connect(button,SIGNAL(clicked()),this,SLOT(cancelData()));
}
示例#22
0
UniValue gobject(const JSONRPCRequest& request)
{
    std::string strCommand;
    if (request.params.size() >= 1)
        strCommand = request.params[0].get_str();

    if (request.fHelp  ||
        (
#ifdef ENABLE_WALLET
         strCommand != "prepare" &&
#endif // ENABLE_WALLET
         strCommand != "vote-many" && strCommand != "vote-conf" && strCommand != "vote-name" && strCommand != "submit" && strCommand != "count" &&
         strCommand != "deserialize" && strCommand != "get" && strCommand != "getvotes" && strCommand != "getcurrentvotes" && strCommand != "list" && strCommand != "diff" &&
         strCommand != "check" ))
        throw std::runtime_error(
                "gobject \"command\"...\n"
                "Manage governance objects\n"
                "\nAvailable commands:\n"
                "  check              - Validate governance object data (proposal only)\n"
#ifdef ENABLE_WALLET
                "  prepare            - Prepare governance object by signing and creating tx\n"
#endif // ENABLE_WALLET
                "  submit             - Submit governance object to network\n"
                "  deserialize        - Deserialize governance object from hex string to JSON\n"
                "  count              - Count governance objects and votes (additional param: 'json' or 'all', default: 'json')\n"
                "  get                - Get governance object by hash\n"
                "  getvotes           - Get all votes for a governance object hash (including old votes)\n"
                "  getcurrentvotes    - Get only current (tallying) votes for a governance object hash (does not include old votes)\n"
                "  list               - List governance objects (can be filtered by signal and/or object type)\n"
                "  diff               - List differences since last diff\n"
                "  vote-name         - Vote on a governance object by masternode name (using masternode.conf setup)\n"
                "  vote-conf          - Vote on a governance object by masternode configured in syscoin.conf\n"
                "  vote-many          - Vote on a governance object by all masternodes (using masternode.conf setup)\n"
                );


    if(strCommand == "count") {
        std::string strMode{"json"};

        if (request.params.size() == 2) {
            strMode = request.params[1].get_str();
        }

        if (request.params.size() > 2 || (strMode != "json" && strMode != "all")) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject count ( \"json\"|\"all\" )'");
        }

        return strMode == "json" ? governance.ToJson() : governance.ToString();
    }
    /*
        ------ Example Governance Item ------

        gobject submit 6e622bb41bad1fb18e7f23ae96770aeb33129e18bd9efe790522488e580a0a03 0 1 1464292854 "beer-reimbursement" 5b5b22636f6e7472616374222c207b2270726f6a6563745f6e616d65223a20225c22626565722d7265696d62757273656d656e745c22222c20227061796d656e745f61646472657373223a20225c225879324c4b4a4a64655178657948726e34744744514238626a6876464564615576375c22222c2022656e645f64617465223a202231343936333030343030222c20226465736372697074696f6e5f75726c223a20225c227777772e646173687768616c652e6f72672f702f626565722d7265696d62757273656d656e745c22222c2022636f6e74726163745f75726c223a20225c22626565722d7265696d62757273656d656e742e636f6d2f3030312e7064665c22222c20227061796d656e745f616d6f756e74223a20223233342e323334323232222c2022676f7665726e616e63655f6f626a6563745f6964223a2037342c202273746172745f64617465223a202231343833323534303030227d5d5d1
    */

    // DEBUG : TEST DESERIALIZATION OF GOVERNANCE META DATA
    if(strCommand == "deserialize")
    {
        if (request.params.size() != 2) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject deserialize <data-hex>'");
        }

        std::string strHex = request.params[1].get_str();

        std::vector<unsigned char> v = ParseHex(strHex);
        std::string s(v.begin(), v.end());

        UniValue u(UniValue::VOBJ);
        u.read(s);

        return u.write().c_str();
    }

    // VALIDATE A GOVERNANCE OBJECT PRIOR TO SUBMISSION
    if(strCommand == "check")
    {
        if (request.params.size() != 2) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject check <data-hex>'");
        }

        // ASSEMBLE NEW GOVERNANCE OBJECT FROM USER PARAMETERS

        uint256 hashParent;

        int nRevision = 1;

        int64_t nTime = GetAdjustedTime();
        std::string strDataHex = request.params[1].get_str();

        CGovernanceObject govobj(hashParent, nRevision, nTime, uint256(), strDataHex);

        if(govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) {
            CProposalValidator validator(strDataHex);
            if(!validator.Validate())  {
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid proposal data, error messages:" + validator.GetErrorMessages());
            }
        }
        else {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid object type, only proposals can be validated");
        }

        UniValue objResult(UniValue::VOBJ);

        objResult.push_back(Pair("Object status", "OK"));

        return objResult;
    }

#ifdef ENABLE_WALLET
    // PREPARE THE GOVERNANCE OBJECT BY CREATING A COLLATERAL TRANSACTION
    if(strCommand == "prepare")
    {
        if (!EnsureWalletIsAvailable(request.fHelp))
            return NullUniValue;

        if (request.params.size() != 5) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Correct usage is 'gobject prepare <parent-hash> <revision> <time> <data-hex>'");
        }

        // ASSEMBLE NEW GOVERNANCE OBJECT FROM USER PARAMETERS

        uint256 hashParent;

        // -- attach to root node (root node doesn't really exist, but has a hash of zero)
        if(request.params[1].get_str() == "0") {
            hashParent = uint256();
        } else {
            hashParent = ParseHashV(request.params[1], "fee-txid, parameter 1");
        }

        std::string strRevision = request.params[2].get_str();
        std::string strTime = request.params[3].get_str();
        int nRevision = atoi(strRevision);
        int64_t nTime = atoi64(strTime);
        std::string strDataHex = request.params[4].get_str();

        // CREATE A NEW COLLATERAL TRANSACTION FOR THIS SPECIFIC OBJECT

        CGovernanceObject govobj(hashParent, nRevision, nTime, uint256(), strDataHex);

        if(govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) {
            CProposalValidator validator(strDataHex);
            if(!validator.Validate())  {
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid proposal data, error messages:" + validator.GetErrorMessages());
            }
        }

        if(govobj.GetObjectType() == GOVERNANCE_OBJECT_TRIGGER) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Trigger objects need not be prepared (however only masternodes can create them)");
        }

        if(govobj.GetObjectType() == GOVERNANCE_OBJECT_WATCHDOG) {
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Watchdogs are deprecated");
        }
		{
			LOCK(cs_main);
			std::string strError = "";
			if (!govobj.IsValidLocally(strError, false))
				throw JSONRPCError(RPC_INTERNAL_ERROR, "Governance object is not valid - " + govobj.GetHash().ToString() + " - " + strError);
		}
        EnsureWalletIsUnlocked();

        CWalletTx wtx;
        if(!pwalletMain->GetBudgetSystemCollateralTX(wtx, govobj.GetHash(), govobj.GetMinCollateralFee(), false)) {
            throw JSONRPCError(RPC_INTERNAL_ERROR, "Error making collateral transaction for governance object. Please check your wallet balance and make sure your wallet is unlocked.");
        }

        // -- make our change address
        CReserveKey reservekey(pwalletMain);
        // -- send the tx to the network
        CValidationState state;
        if (!pwalletMain->CommitTransaction(wtx, reservekey, g_connman.get(), state, NetMsgType::TX)) {
            throw JSONRPCError(RPC_INTERNAL_ERROR, "CommitTransaction failed! Reason given: " + state.GetRejectReason());
        }

        DBG( std::cout << "gobject: prepare "
             << " GetDataAsPlainString = " << govobj.GetDataAsPlainString()
             << ", hash = " << govobj.GetHash().GetHex()
             << ", txidFee = " << wtx.GetHash().GetHex()
             << std::endl; );

        return wtx.GetHash().ToString();
    }
示例#23
0
void QLineEdit::keyPressEvent( QKeyEvent *e )
{
    if ( e->key() == Key_Enter || e->key() == Key_Return ) {
	QValidator * v = validator();
	if ( !v || v->validate( tbuf, cursorPos ) == QValidator::Acceptable ) {
	    emit returnPressed();
	} else if ( v ) {
	    v->fixup( tbuf );
	    if ( v->validate( tbuf, cursorPos ) == QValidator::Acceptable )
		emit returnPressed();
	}
	// ### 2.0 must fix this
	e->ignore();
	return;
    }
    if ( e->ascii() >= 32 &&
	 e->key() != Key_Delete &&
	 e->key() != Key_Backspace ) {
	QString t( 2 );
	t[0] = e->ascii();
	t[1] = '\0';
	insert( t );
	return;
    }
    int unknown = 0;
    if ( e->state() & ControlButton ) {
	switch ( e->key() ) {
	case Key_A:
	case Key_Left:
	    home( e->state() & ShiftButton );
	    break;
	case Key_B:
	    cursorLeft( e->state() & ShiftButton );
	    break;
	case Key_C:
	    if ( hasMarkedText() && echoMode() == Normal )
		copyText();
	    break;
	case Key_D:
	    del();
	    break;
	case Key_E:
	case Key_Right:
	    end( e->state() & ShiftButton );
	    break;
	case Key_F:
	    cursorRight( e->state() & ShiftButton );
	    break;
	case Key_H:
	    backspace();
	    break;
	case Key_K:
	    if ( cursorPos < (int)tbuf.length() ) {
		QString t( tbuf );
		t.detach(); // ### 2.0
		t.truncate( cursorPos );
		validateAndSet( t, cursorPos, cursorPos, cursorPos );
	    }
	    break;
	case Key_V:
	    insert( QApplication::clipboard()->text() );
	case Key_X:
	    if ( hasMarkedText() && echoMode() == Normal ) {
		copyText();
		del();
	    }
	    break;
	default:
	    unknown++;
	}
    } else {
	switch ( e->key() ) {
	case Key_Left:
	    cursorLeft( e->state() & ShiftButton );
	    break;
	case Key_Right:
	    cursorRight( e->state() & ShiftButton );
	    break;
	case Key_Backspace:
	    backspace();
	    break;
	case Key_Home:
	    home( e->state() & ShiftButton );
	    break;
	case Key_End:
	    end( e->state() & ShiftButton );
	    break;
	case Key_Delete:
	    del();
	    break;
	default:
	    unknown++;
	}
    }

    if ( unknown ) {				// unknown key
	e->ignore();
	return;
    }
}
示例#24
0
bool QLineEdit::validateAndSet( const char * newText, int newPos,
				int newMarkAnchor, int newMarkDrag )
{
    QString t( newText );
    if ( !t.isEmpty() ) {
	uchar *p = (uchar *) t.data();
	while ( *p ) {		// unprintable/linefeed becomes space
	    if ( *p < 32 )
		*p = 32;
	    p++;
	}
    }
    if ( t.length() > (uint)maxLength() )
	t.truncate( maxLength() );

    QValidator * v = validator();

    if ( v && v->validate( t, newPos ) == QValidator::Invalid &&
	 v->validate( tbuf, cursorPos ) != QValidator::Invalid ) {
	return FALSE;
    }

    // okay, it succeeded
    if ( newMarkDrag != markDrag ||
	 newMarkAnchor |! markAnchor ||
	 newPos != cursorPos ||
	 t != tbuf ) {
	int minP = QMIN( cursorPos, minMark() );
	int maxP = QMAX( cursorPos, maxMark() );
	cursorPos = newPos;
	markAnchor = newMarkAnchor;
	markDrag = newMarkDrag;
	d->pmDirty = TRUE;

	minP = QMIN( minP, QMIN( cursorPos, minMark() ) );
	maxP = QMAX( maxP, QMAX( cursorPos, maxMark() ) );
	
	if ( tbuf == t || tbuf == t.right( tbuf.length() ) ) {
	    int i = 0;
	    while( i < minP && t[i] == tbuf[i] )
		i++;
	    minP = i;
	    i = t.length();
	    if ( i > (int) tbuf.length() ) {
		tbuf = t;
	    } else {
		while( i > maxP && t[i] == tbuf[i] )
		    i--;
	    }
	    maxP = i;
	    repaintArea( minP, maxP );
	} else {
	    tbuf = t;
	    d->pmDirty = TRUE;
	    QFontMetrics fm = fontMetrics();
	    int x;
	    if ( offset > cursorPos )
		x = 0;
	    else
		x = fm.width(t.mid( offset, cursorPos - offset) );
	    int margin = frame() ? 2 : 0;
	    if ( x >= width() - margin ) {
		while( x >= width() - margin ) {
		    int w = fm.width( tbuf[offset] );
		    x -= w;
		    offset++;
		}
	    }
	    d->pmDirty = TRUE;
	    repaint( FALSE );
	}
    }
    emit textChanged( tbuf );
    return TRUE;
}
示例#25
0
[[noreturn]] void throwingFunction() {
  Validator validator(1, "one_uncaught_exception_in_function");
  throw std::runtime_error("exception");
}
示例#26
0
void CmdLineOptions::parse(int argc, char **argv, StringList &left_overs) {
  std::unique_lock<std::mutex> l(mutex_);
  left_overs.clear();

  auto get_nice_program_name = [argv]() -> std::string {
    std::string result = std::string(argv[0]);
    // Remove everything but the command's name.
    size_t const pos = result.find_last_of("/");
    if (pos != result.npos) {
      if (pos + 1 < result.size()) {
        result = result.substr(pos);
      }
    }
    return result;
  };
  programName_ = get_nice_program_name();

  StringList listOfOptionsWithNoValue;

  for (int i(1); i < argc; ++i) {
    int const next = (i + 1) < argc ? i + 1 : -1;

    std::string arg(argv[i]);
    {
      SwitchOptList::iterator it = find_switch(arg);
      if (it != switchOptionList_.end()) {
        it->set(!it->get_default());
        continue;
      }
    }
    {
      ArgOptList::iterator it = find_arg(arg);
      if (it != argOptionList_.end()) {
        if (next != -1) {
          it->set(argv[next]);
          ++i;
          continue;
        } else {
          listOfOptionsWithNoValue.push_back(arg);
          continue;
        }
      }
    }

    // not an option :/
    left_overs.push_back(arg);
  }

  // check for the help switch.
  if (get_switch(HELP_SWITCH_NAME)) {
    print_usage(stdStream_);
    exit(EXIT_SUCCESS);
  }

  StringList listOfMissingRequiredOptions;
  StringList listOfInvalidOptions;
  for (StringOption const &option : argOptionList_) {
    if (!option.is_set() && option.is_required()) {
      listOfMissingRequiredOptions.push_back(option.name());
    } else {
      // Validate the argument
      ValidatorFunctionMap::const_iterator it = validatorFunctionMap_.find(
          option.name());
      if (it != validatorFunctionMap_.end()) {
        ValidatorFunctionList const &list(it->second);
        for (ValidatorFunction const &validator : list) {
          if (!validator(option.name(), option.get())) {
            listOfInvalidOptions.push_back(option.name());
          }
        }
      }
    }
  }

  parserResultHandler_(left_overs, listOfMissingRequiredOptions,
                       listOfOptionsWithNoValue, listOfInvalidOptions);
}
QValidator::State UnsignedIntegerEdit::validity() const
{
    int cursorPos = cursorPosition();
    QString txt = text();
    return validator()->validate(txt, cursorPos);
}
示例#28
0
WT_USTRING WDateEdit::format() const
{
  return validator()->format();
}
示例#29
0
void FeatureClassDlg::setFieldData(QTreeWidgetItem* pItem, int column)
{
    if (pItem == NULL)
    {
        return;
    }

    DynamicObject* pClass = getCurrentFeatureClass();
    if (pClass == NULL)
    {
        return;
    }

    QString fieldName = pItem->text(0);
    if (column == 0)     // Name
    {
        QString oldFieldName = pItem->data(column, Qt::UserRole).toString();
        if (fieldName == oldFieldName)
        {
            return;
        }

        if (mpFieldTree->findItems(fieldName, Qt::MatchExactly, column).count() > 1)
        {
            QMessageBox::warning(this, windowTitle(), "Another field exists with the same name.  "
                                 "Please choose a unique name for the field.");
            pItem->setText(column, oldFieldName);
            return;
        }

        DataVariant field = pClass->getAttribute(oldFieldName.toStdString());
        pClass->removeAttribute(oldFieldName.toStdString());
        pClass->setAttribute(fieldName.toStdString(), field);

        pItem->setData(column, Qt::UserRole, QVariant(fieldName));
    }
    else                 // Type or Value
    {
        QString fieldType = pItem->text(1);
        QString fieldValue = pItem->text(2);

        if (column == 1)  // Type
        {
            // If the type changed, ensure that the value is valid with the new type and reset the value if necessary
            QString validateString = fieldValue;
            int pos = 0;

            if (fieldType == "int")
            {
                QIntValidator validator(this);
                if (validator.validate(validateString, pos) != QValidator::Acceptable)
                {
                    pItem->setText(2, "0");
                    return;     // Return since this method will be called again as a result to changing the value text
                }
            }
            else if (fieldType == "double")
            {
                QDoubleValidator validator(this);
                if (validator.validate(fieldValue, pos) != QValidator::Acceptable)
                {
                    pItem->setText(2, "0.0");
                    return;     // Return since this method will be called again as a result to changing the value text
                }
            }
        }

        DataVariant field;
        if (fieldType == "int")
        {
            int intValue = fieldValue.toInt();
            field = DataVariant(intValue);
        }
        else if (fieldType == "double")
        {
            double doubleValue = fieldValue.toDouble();
            field = DataVariant(doubleValue);
        }
        else if (fieldType == "string")
        {
            std::string stringValue = fieldValue.toStdString();
            field = DataVariant(stringValue);
        }

        pClass->setAttribute(fieldName.toStdString(), field);
    }
}
示例#30
0
TEST(UncaughtExceptions, no_exception) {
  Validator validator(0, "no_exception");
}