/*
Non-validating (e.g. that the artifact type is correct) load

TODO - add some logging to the parsing
772097
protected static ArtifactMap populateArtifactMapFromStream(ArtifactMap tempMap, InputStream is) {
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        try {
            XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);

            if (logger.isLoggable(Level.FINEST)) {
                logger.finest("Loaded XMLStreamReader = " + xmlStreamReader);
            }

            boolean processedRoot = false;

            // We are going to take advantage of the simplified structure of a
            // line
            // E.g.:
            // <batch-artifacts>
            //   <item-processor id=MyItemProcessor class=jsr352/sample/MyItemProcessorImpl/>
            //   ..
            // </batch-artifacts>
            //
            // and have much simpler logic than general-purpose parsing would
            // require.
            while (xmlStreamReader.hasNext()) {
                int event = xmlStreamReader.next();

                // Until we reach end of document
                if (event == XMLStreamConstants.END_DOCUMENT) {
                    break;
                }

                // At this point we have either:
                //    A) just passed START_DOCUMENT, and are at START_ELEMENT for the root,
                //       <batch-artifacts>, or
                //    B) we have just passed END_ELEMENT for one of the artifacts which is a child of
                //       <batch-artifacts>.
                //
                //  Only handle START_ELEMENT now so we can skip whitespace CHARACTERS events.
                //
                if (event == XMLStreamConstants.START_ELEMENT) {
                    if (!processedRoot) {
                        QName rootQName = xmlStreamReader.getName();
                        if (!rootQName.equals(BATCH_ROOT_ELEM)) {
                            throw new IllegalStateException("Expecting document with root element QName: " + BATCH_ROOT_ELEM
                                                            + ", but found root element with QName: " + rootQName);
                        } else {
                            processedRoot = true;
                        }
                    } else {

                        // Should only need localName
                        String annotationShortName = xmlStreamReader.getLocalName();
                        String id = xmlStreamReader.getAttributeValue(null, "id");
                        String className = xmlStreamReader.getAttributeValue(null, "class");
                        tempMap.addEntry(annotationShortName, id, className);

                        // Ignore anything else (text/whitespace) within this
                        // element
                        while (event != XMLStreamConstants.END_ELEMENT) {
                            event = xmlStreamReader.next();
                        }
                    }
                }
            }
            xmlStreamReader.close();
            is.close();
            return tempMap;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
192025
@Override
    public void validateDefault(InputProblemReporter rep, boolean normalize)
        throws XMLStreamException
    {
        String normStr = validateDefaultName(rep, normalize);
        if (normalize) {
            mDefValue.setValue(normStr);
        }

        // Ok, but was it declared?

        /* 03-Dec-2004, TSa: This is rather ugly -- need to know we
         *   actually really get a DTD reader, and DTD reader needs
         *   to expose a special method... but it gets things done.
         */
        EntityDecl ent = ((MinimalDTDReader) rep).findEntity(normStr);
        checkEntity(rep, normStr, ent);
    }
448793
@Override
    public ARCHIVETYPE process(final MavenResolvedArtifact artifact, final Class<ARCHIVETYPE> returnType)
            throws IllegalArgumentException {

        if (artifact == null) {
            throw new IllegalArgumentException("Resolution artifact must be specified");
        }
        File file = artifact.asFile();
        if (file == null) {
            throw new IllegalArgumentException("Artifact was not resolved");
        }

        return ShrinkWrap.create(ZipImporter.class, file.getName()).importFrom(file).as(returnType);
    }
1321005
function legacyExtensionLoading (ext, name) {
    if (typeof ext === 'function') {
      ext = ext(new showdown.Converter());
    }
    if (!showdown.helper.isArray(ext)) {
      ext = [ext];
    }
    var valid = validate(ext, name);

    if (!valid.valid) {
      throw Error(valid.error);
    }

    for (var i = 0; i < ext.length; ++i) {
      switch (ext[i].type) {
        case 'lang':
          langExtensions.push(ext[i]);
          break;
        case 'output':
          outputModifiers.push(ext[i]);
          break;
        default:// should never reach here
          throw Error('Extension loader error: Type unrecognized!!!');
      }
    }
  }
443803
function () {
    if (this.loadTypeSet || this.loadType === LoaderBase.typeText) {
      this.content = this.xhr.response || this.xhr.responseText;
    } else {
      switch (this.loadType) {

        case LoaderBase.typeArraybuffer:

          if (ArrayBuffer) {
            this.content = stringToArrayBuffer(this.xhr.response);
          } else {
            throw new Error('This browser does not support ArrayBuffer');
          }
          break;

        case LoaderBase.typeBlob:
        case LoaderBase.typeVideo:
        case LoaderBase.typeAudio:

          if (Blob) {
            if (!this.fileMeta) {
              this.fileMeta = new FileMeta();
            }

            if (this.fileMeta.mime === null) {
              this.fileMeta.mime = getMimeFromURL(this.url);
            }

            this.content = new Blob([ stringToArrayBuffer(this.xhr.response) ], { type: this.fileMeta.mime });
          } else {
            throw new Error('This browser does not support Blob');
          }
          break;

        case LoaderBase.typeJSON:

          this.content = JSON.parse(this.xhr.response);
          break;

        case LoaderBase.typeDocument:

          // this needs some work pretty sure there's a better way to handle this
          this.content = this.xhr.response;
          break;

      }
    }
  }
1027718
@Override
    public void validate() {

        if (entityClass == null) {
            throw new IllegalArgumentException("testentity class cannot be null");
        }

        if (!entityClass.isAnnotationPresent(DeepEntity.class)) {
            throw new AnnotationTypeMismatchException(null, entityClass.getCanonicalName());
        }

        super.validate();

        /* let's validate fieldNames in @DeepField annotations */
        Field[] deepFields = AnnotationUtils.filterDeepFields(entityClass);

        Map<String, Cell> colDefs = super.columnDefinitions();

        /* colDefs is null if table does not exist. I.E. this configuration will be used as an output configuration
         object, and the output table is dynamically created */
        if (colDefs == null) {
            return;
        }

        for (Field field : deepFields) {
            String annotationFieldName = AnnotationUtils.deepFieldName(field);

            if (!colDefs.containsKey(annotationFieldName)) {
                throw new DeepNoSuchFieldException("Unknown column name \'" + annotationFieldName + "\' specified for" +
                        " field " + entityClass.getCanonicalName() + "#" + field.getName() + ". Please, " +
                        "make sure the field name you specify in @DeepField annotation matches _exactly_ the column " +
                        "name " +
                        "in the database");
            }
        }
    }
564944
public static boolean isValid(Artifact artifact) {
        return artifact.getGroupId() != null && !FAKE.equals(artifact.getGroupId());
    }
298883
@Check
	public void checkArtifactUse(SarlArtifact artifact) {
		error(MessageFormat.format(
				Messages.SARLValidator_0,
				this.grammarAccess.getSpaceKeyword()),
				artifact,
				null);
	}
52502
def validate_for_request(self):
        """"""
        if not self.use_packages and not self.modules and not self.pulp:
            raise ValueError("Nothing to compose (no packages, modules, or enabled pulp repos)")

        if self.packages and not self.koji_tag:
            raise ValueError('koji_tag is required when packages are used')
1003496
public void validate() {
    if (StringUtils.isEmpty(name) || StringUtils.isEmpty(group)) {
      throw new IllegalArgumentException("Package name or group not set.");
    }
    if (filters.isEmpty()) {
      throw new IllegalArgumentException("No package filter defined / no package root path set.");
    }
    if (created == null) {
      throw new IllegalArgumentException("Package creation date not set.");
    }
  }
1061857
@Override
	public List<ParsingError> doValidate() {

		String fileName = this.commandName + Constants.FILE_EXT_COMMANDS;
		File commandsDirectory = new File( this.context.getApp().getDirectory(), Constants.PROJECT_DIR_COMMANDS );
		File commandFileToExecute;

		List<ParsingError> result = new ArrayList<> ();
		if( Utils.isEmptyOrWhitespaces( this.commandName )) {
			result.add( error( ErrorCode.CMD_MISSING_COMMAND_NAME ));
		}

		// Prevent a commands file from invoking itself recursively
		// If the command was loaded from a file...
		else if( this.context.getCommandFile() != null
				&& fileName.equals( this.context.getCommandFile().getName())) {

			result.add( error( ErrorCode.CMD_LOOPING_COMMAND, name( this.commandName )));
		}

		// The commands file to execute must exist.
		else if( ! ( commandFileToExecute = new File( commandsDirectory, fileName )).exists()) {
			result.add( error( ErrorCode.CMD_INEXISTING_COMMAND, name( this.commandName )));
		}

		// If it exists, we do not want it to contain the same instruction.
		// Can happen if we execute a commands (not loaded from a file) that executes
		// a commands file with the same instruction...
		else {
			try {
				String content = Utils.readFileContent( commandFileToExecute );
				Pattern p = Pattern.compile( PREFIX + "\\s+" + Pattern.quote( this.commandName ), Pattern.CASE_INSENSITIVE );
				if( p.matcher( content ).find())
					result.add( error( ErrorCode.CMD_NASTY_LOOPING_COMMAND, name( this.commandName )));

			} catch( IOException e ) {
				// If we cannot load the file's content, do not push the validation further...
				Utils.logException( Logger.getLogger( getClass().getName()), e );
			}
		}

		return result;
	}
1252458
private void validateEntities(JsonNode data) throws InvalidInputException {
    for (JsonNode node : data.findParents(INDEX_START)) {

      for (String key : new String[] {INDEX_START, INDEX_END, ID, TYPE}) {
        if (node.path(key).isMissingNode()) {
          throw new InvalidInputException("Required field \"" + key + "\" missing from the entity payload");
        }
      }

      int startIndex = node.get(INDEX_START).intValue();
      int endIndex = node.get(INDEX_END).intValue();

      if (endIndex <= startIndex) {
        throw new InvalidInputException(String.format("Invalid entity payload: %s (start index: %s, end index: %s)",
            node.get(ID).textValue(), startIndex, endIndex));
      }

    }
  }
179882
void validatePackage(EntityType entityType) {
    Package pack = entityType.getPackage();
    if (pack != null
        && isSystemPackage(pack)
        && !systemEntityTypeRegistry.hasSystemEntityType(entityType.getId())) {
      throw new MolgenisValidationException(
          new ConstraintViolation(
              format(
                  "Adding entity [%s] to system package [%s] is not allowed",
                  entityType.getId(), pack.getId())));
    }
  }
1327846
function (type, error = null, id = null) {
    type = type.toUpperCase()
    let errors = {
        'NO_DATA': 'No info for that id yet. Or maybe the data provided was wrong.',
        'BUSY': 'The server providing the info is busy right now. Try again.',
        'UNAVAILABLE': 'The server providing the info is unavailable right now. Try again later.',
        'EMPTY': 'The provider server was parsed correctly, but has no data to show. Try Again later.',
        'DOWN': 'The provider server is currently down. Try Again later.',
        'PARSER': 'Something went wrong when parsing the provider website.',
        'ACTION_REQUIRED': 'That tracker requires an aditional step in their website.'
    }

    let message = error != null ? error : errors[type]
    message = id != null ? message + ' ID:' + id : message
    return new Error(type + ' - ' + message)
}
25918
function validateMetadata(metadataPath, cb) {
  validateJSonStructure(metadataPath, function(err, metadataObject) {
    if (err) {
      cb(err, null);
    } else {
      cb(null, metadataObject.files);
    }
  });
}
1369929
function validateVuln (doc) {
	log(`validateVuln: doc ${JSON.stringify(doc)}`);
	const validateVulnQuery = { pattern: doc.pattern, language: doc.language, evilInput: doc.evilInput, nPumps: 250000, timeLimit: 1 };

	const tmpFile = `/tmp/validate-uploads-${process.pid}.json`;
	fs.writeFileSync(tmpFile, JSON.stringify(validateVulnQuery));

	try {
		const cmd = `${process.env.VULN_REGEX_DETECTOR_ROOT}/src/validate/validate-vuln.pl ${tmpFile} 2>/dev/null`;
		const stdout = childProcess.execSync(cmd, {encoding: 'utf8'});
		const result = JSON.parse(stdout);
		log(JSON.stringify(result));
		return result.timedOut === 1;
	} catch (e) {
		log(`Error: ${JSON.stringify(e)}`);
		return false;
	} finally {
		fs.unlinkSync(tmpFile);
	}
}
196882
@Override
    public synchronized boolean load() {
        Either<Void, T> oldData = data;
        long oldModified = modified;
        String oldKey = versionedKey;
        try {
            if (isOutOfDate() || needsData()) {
                String newVersionedKey = reader.getAsString(key)
                                               .orElse(null);
                val loaded = nonAtomicload(newVersionedKey);
                data = Either.right((T) loaded._2());
                modified = loaded._1();
                versionedKey = newVersionedKey;
            } else {
                return false;
            }
        } catch (Throwable e) {
            data = oldData;
            versionedKey = oldKey;
            modified = oldModified;
            logger.info(e.getMessage(), e);
            throw ExceptionSoftener.throwSoftenedException(e);
        }
        return true;
    }