public boolean isValid() { try { loadServices(); collectValidationPoints(); List<Document> wsdlDocs = getWSDLDocuments(); for (XNode vNode : vNodes) { if (!isExist(wsdlDocs, vNode)) { // System.out.println("Fail: " + vNode.getXPath()); FailureLocation loc = getFailureLocation(wsdlDocs, vNode.getFailurePoint()); vResults.addError( new Message( "FAILED_AT_POINT", LOG, loc.getLocation().getLineNumber(), loc.getLocation().getColumnNumber(), loc.getDocumentURI(), vNode.getPlainText())); } } } catch (Exception e) { this.vResults.addError(e.getMessage()); return false; } return vResults.isSuccessful(); }
private void collectValidationPointsForPortTypes() { for (QName ptName : portTypeRefNames) { PortType portType = getPortType(ptName); if (portType == null) { vResults.addError(new Message("NO_PORTTYPE", LOG, ptName)); continue; } XNode vPortTypeNode = getXNode(portType); for (Operation operation : getOperations(portType).values()) { XNode vOperationNode = getOperationXNode(vPortTypeNode, operation.getName()); if (operation.getInput() == null) { vResults.addError( new Message("WRONG_MEP", LOG, operation.getName(), portType.getQName())); continue; } javax.wsdl.Message inMsg = operation.getInput().getMessage(); if (inMsg == null) { addWarning( "Operation " + operation.getName() + " in PortType: " + portType.getQName() + " has no input message"); } else { XNode vInMsgNode = getXNode(inMsg); vInMsgNode.setFailurePoint(getInputXNode(vOperationNode, operation.getInput().getName())); vNodes.add(vInMsgNode); messageRefNames.add(inMsg.getQName()); } if (operation.getOutput() != null) { javax.wsdl.Message outMsg = operation.getOutput().getMessage(); if (outMsg == null) { addWarning( "Operation " + operation.getName() + " in PortType: " + portType.getQName() + " has no output message"); } else { XNode vOutMsgNode = getXNode(outMsg); vOutMsgNode.setFailurePoint( getOutputXNode(vOperationNode, operation.getOutput().getName())); vNodes.add(vOutMsgNode); messageRefNames.add(outMsg.getQName()); } } for (Iterator<?> iter = operation.getFaults().values().iterator(); iter.hasNext(); ) { Fault fault = (Fault) iter.next(); javax.wsdl.Message faultMsg = fault.getMessage(); XNode vFaultMsgNode = getXNode(faultMsg); vFaultMsgNode.setFailurePoint(getFaultXNode(vOperationNode, fault.getName())); vNodes.add(vFaultMsgNode); messageRefNames.add(faultMsg.getQName()); } } } }
public static void logConsoleWarnings(Map<String, ValidationResult> results) { for (ValidationResult result : results.values()) { if (!result.isValid() && result.getValidationMessage() != null) { log.warn(result.getValidationMessage()); } } }
/** * Returns a map where the key is a user and the value is a naturally-sorted list of results they * should receive. * * @param results all the validation run results, in a sorted set * @return map of users to results */ private Map<User, SortedSet<ValidationResult>> getUserResults( SortedSet<ValidationResult> results) { Map<User, SortedSet<ValidationResult>> userResults = new HashMap<>(); for (ValidationResult result : results) { for (ValidationRuleGroup ruleGroup : result.getValidationRule().getGroups()) { if (ruleGroup.hasUserGroupsToAlert()) { for (UserGroup userGroup : ruleGroup.getUserGroupsToAlert()) { for (User user : userGroup.getMembers()) { if (!ruleGroup.isAlertByOrgUnits() || canUserAccessSource(user, result.getOrgUnit())) { SortedSet<ValidationResult> resultSet = userResults.get(user); if (resultSet == null) { resultSet = new TreeSet<>(); userResults.put(user, resultSet); } resultSet.add(result); } } } } } } return userResults; }
@Test public void testHasFailures() { res = new ValidationResult(); res.addFailure(new BeanValidationFailure(obj1, "obj1 1", "mes obj1 1")); assertTrue(res.hasFailures()); assertTrue(res.hasFailures(obj1)); assertFalse(res.hasFailures(obj2)); }
@Test public void testEmpty() { res = new ValidationResult(); assertFalse(res.hasFailures()); assertFalse(res.hasFailures(obj1)); assertFalse(res.hasFailures(null)); }
@NonNls private String generateWarningLabelText(final ValidationResult configurationException) { return "<html><body><b>" + configurationException.getTitle() + ": </b>" + configurationException.getMessage() + "</body></html>"; }
@Test public void shouldFailOnBrokenSchema() { JAXPValidator v = new JAXPValidator(Languages.W3C_XML_SCHEMA_NS_URI); v.setSchemaSource(new StreamSource(this.getClass().getResourceAsStream("/broken.xsd"))); ValidationResult r = v.validateSchema(); assertFalse(r.isValid()); assertTrue(r.getProblems().iterator().hasNext()); }
/** * Formats and sets name on the period of each result. * * @param results the collection of validation results. * @param format the i18n format. */ private void formatPeriods(Collection<ValidationResult> results, I18nFormat format) { if (format != null) { for (ValidationResult result : results) { if (result != null && result.getPeriod() != null) { result.getPeriod().setName(format.formatPeriod(result.getPeriod())); } } } }
@Test public void shouldSuccessfullyValidateInstance() { JAXPValidator v = new JAXPValidator(Languages.W3C_XML_SCHEMA_NS_URI); v.setSchemaSource(new StreamSource(this.getClass().getResourceAsStream("/Book.xsd"))); ValidationResult r = v.validateInstance( new StreamSource(this.getClass().getResourceAsStream("/BookXsdGenerated.xml"))); assertTrue(r.isValid()); assertFalse(r.getProblems().iterator().hasNext()); }
private ValidationResult verifyCodeInternal(ValueSet vs, CodeableConcept code) throws Exception { for (Coding c : code.getCoding()) { ValidationResult res = verifyCodeInternal(vs, c.getSystem(), c.getCode(), c.getDisplay()); if (res.isOk()) return res; } if (code.getCoding().isEmpty()) return new ValidationResult(IssueSeverity.ERROR, "None code provided"); else return new ValidationResult( IssueSeverity.ERROR, "None of the codes are in the specified value set"); }
@Test public void testGetFailures() { res = new ValidationResult(); res.addFailure(new BeanValidationFailure(obj1, "obj1 1", "mes obj1 1")); res.addFailure(new BeanValidationFailure(obj1, "obj1 1", "mes obj1 1")); res.addFailure(new BeanValidationFailure(obj2, "obj1 1", "mes obj1 1")); assertEquals(2, res.getFailures(obj1).size()); assertEquals(1, res.getFailures(obj2).size()); assertEquals(3, res.getFailures().size()); }
/** * Counts the results of each importance type, for all the importance types that are found within * the results. * * @param results results to analyze * @return Mapping between importance type and result counts. */ private Map<String, Integer> countResultsByImportanceType(Set<ValidationResult> results) { Map<String, Integer> importanceCountMap = new HashMap<>(); for (ValidationResult result : results) { Integer importanceCount = importanceCountMap.get(result.getValidationRule().getImportance()); importanceCountMap.put( result.getValidationRule().getImportance(), importanceCount == null ? 1 : importanceCount + 1); } return importanceCountMap; }
/* (non-Javadoc) * @see com.alpine.illuminator.license.validator.ILicenseValidator#validateKey(java.lang.String, com.alpine.illuminator.license.validator.ILicenseValidator.ValidateHandler) */ @Override public ValidationResult validateKey(String license, int userCount, int modelerUserCount) { ValidationResult valid = null; try { String[] comboKey = LiecnseDecryptor.decrypt(license, IlluminatorLicenseInfoBuilder.PRODUCT_NAME) .split(LiecnseDecryptor.SEPARATOR_MARK); if (LiecnseDecryptor.ENCRYPT_KEY.equals(comboKey[0]) && IlluminatorLicenseInfoBuilder.PRODUCT_NAME.equals( comboKey[1])) { // basic info passed validate for (int i = 2; i < comboKey.length; i++) { switch (i) { case 2: if (!LiecnseDecryptor.IGNORE.equals(comboKey[2]) && userCount > Integer.parseInt(comboKey[2])) { valid = ValidationResult.OVER_LIMIT; valid.setMessage(comboKey[2]); } break; case 3: if (!LiecnseDecryptor.IGNORE.equals(comboKey[3]) && isExpire(comboKey[3])) { valid = ValidationResult.EXPIRED; valid.setMessage(comboKey[3]); } break; case 5: if (!LiecnseDecryptor.IGNORE.equals(comboKey[5]) && !MacAddressUtil.isAVlidateMacAddress(comboKey[5])) { valid = ValidationResult.MACHINE_UNMATCHED; } break; case 6: if (!LiecnseDecryptor.IGNORE.equals(comboKey[6]) && modelerUserCount > Integer.parseInt(comboKey[6])) { valid = ValidationResult.OVER_LIMIT_MODELER; valid.setMessage(comboKey[6]); } } } if (valid == null) { valid = ValidationResult.PASS; } } else { valid = ValidationResult.UNKNOWN_LICENSE; } } catch (Exception e) { e.printStackTrace(); valid = ValidationResult.UNKNOWN_LICENSE; } return valid; }
@Test public void describe() { DbProperty targetDbProp = mock(DbProperty.class); when(targetDbProp.getPath()).thenReturn("alfresco.some_table.idx_table_id.name"); when(targetDbProp.getPropertyValue()).thenReturn("idx_table_id"); when(targetDbProp.getDbObject()).thenReturn(new Index("")); ValidationResult validation = new ValidationResult(targetDbProp, "value must be 'xyz'"); assertEquals( "Validation: index alfresco.some_table.idx_table_id.name=\"idx_table_id\" fails to " + "match rule: value must be 'xyz'", validation.describe()); }
@Test public void testGlobalResultInvalid() { final AnalyzerCreationResult<TestAnalyzerType> failedResult = new AnalyzerCreationResult<TestAnalyzerType>( this.testAnalyzerType, ValidationResult.invalidResult("Something global wrong"), createParameterResults(ValidationResult.validResult(), ValidationResult.validResult())); Assert.assertFalse(failedResult.wasSuccessful()); Assert.assertNull(failedResult.getAnalyzer()); Assert.assertFalse(failedResult.getGlobalResult().isValid()); Assert.assertEquals( failedResult.getParameterResults().keySet(), new HashSet<>(Arrays.asList(this.stringParameterSpec, this.intParameterSpec))); Assert.assertTrue(failedResult.getParameterResults().get(this.stringParameterSpec).isValid()); Assert.assertTrue(failedResult.getParameterResults().get(this.intParameterSpec).isValid()); }
@Test public void testSuccessfulCreation() { final AnalyzerCreationResult<TestAnalyzerType> successfulResult = new AnalyzerCreationResult<TestAnalyzerType>( this.testAnalyzer, ValidationResult.validResult(), createParameterResults(ValidationResult.validResult(), ValidationResult.validResult())); Assert.assertTrue(successfulResult.wasSuccessful()); Assert.assertEquals(this.testAnalyzer, successfulResult.getAnalyzer()); Assert.assertTrue(successfulResult.getGlobalResult().isValid()); Assert.assertEquals( successfulResult.getParameterResults().keySet(), new HashSet<>(Arrays.asList(this.stringParameterSpec, this.intParameterSpec))); Assert.assertTrue( successfulResult.getParameterResults().get(this.stringParameterSpec).isValid()); Assert.assertTrue(successfulResult.getParameterResults().get(this.intParameterSpec).isValid()); }
// This exception should mention wrapping a MissingFactException @Test(expected = RuleExecutionException.class) public void testRuleFailsWhenConsumerDoesntHaveFact() { Product product = new Product("a-product", "A product for testing"); product.setAttribute(PRODUCT_CPULIMITED, "2"); productCurator.create(product); when(this.productAdapter.getProductById("a-product")).thenReturn(product); ValidationResult result = enforcer.preEntitlement( TestUtil.createConsumer(), entitlementPoolWithMembersAndExpiration(owner, product, 1, 2, expiryDate(2000, 1, 1)), 1); assertFalse(result.isSuccessful()); assertTrue(result.hasErrors()); assertFalse(result.hasWarnings()); }
@Override public ValidationResult validate(RenderedService entity, ValidationResult result) { SubscriberSession oldSubscriberSession = subscriberDAO.getSubscriberSessionAfterDate( entity.getSubscriberAccount(), entity.getDate()); if (oldSubscriberSession != null) { result.addError("errors.hasSessionAfterDateWithId", entity.getId()); return result; } SubscriberTariff oldSubscriberTariff = subscriberDAO.getSubscriberTariffAfterDate(entity.getSubscriberAccount(), entity.getDate()); if (oldSubscriberTariff != null) { result.addError("errors.hasTariffAfterDateWithId", entity.getId()); return result; } return result; }
/** * Generate and send an alert message containing a list of validation results to a set of users. * * @param results results to put in this message * @param users users to receive these results * @param scheduledRunStart date/time when the scheduled run started */ private void sendAlertmessage( SortedSet<ValidationResult> results, Set<User> users, Date scheduledRunStart) { StringBuilder builder = new StringBuilder(); SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Map<String, Integer> importanceCountMap = countResultsByImportanceType(results); String subject = "Alerts as of " + dateTimeFormatter.format(scheduledRunStart) + ": High " + (importanceCountMap.get("high") == null ? 0 : importanceCountMap.get("high")) + ", Medium " + (importanceCountMap.get("medium") == null ? 0 : importanceCountMap.get("medium")) + ", Low " + (importanceCountMap.get("low") == null ? 0 : importanceCountMap.get("low")); // TODO use velocity template for message for (ValidationResult result : results) { ValidationRule rule = result.getValidationRule(); builder .append(result.getOrgUnit().getName()) .append(" ") .append(result.getPeriod().getName()) .append( result.getAttributeOptionCombo().isDefault() ? "" : " " + result.getAttributeOptionCombo().getName()) .append(LN) .append(rule.getName()) .append(" (") .append(rule.getImportance()) .append(") ") .append(LN) .append(rule.getLeftSide().getDescription()) .append(": ") .append(result.getLeftsideValue()) .append(LN) .append(rule.getRightSide().getDescription()) .append(": ") .append(result.getRightsideValue()) .append(LN) .append(LN); } log.info("Alerting users: " + users.size() + ", subject: " + subject); messageService.sendMessage(subject, builder.toString(), null, users); }
private void updateWarning() { final ValidationResult configurationException = getValidationResult(); if (configurationException != null) { myOutlinePanel.setVisible(true); myWarningLabel.setVisible(true); myWarningLabel.setText(generateWarningLabelText(configurationException)); final Runnable quickFix = configurationException.getQuickFix(); if (quickFix == null) { myFixButton.setVisible(false); } else { myFixButton.setVisible(true); myQuickFix = quickFix; } } else { myOutlinePanel.setVisible(false); myWarningLabel.setVisible(false); myFixButton.setVisible(false); } }
public boolean convert( ValidationResult result, ValidationErrors errors, ContainerMetaData container, Locale locale) { boolean convert = super.convert(result, errors, container, locale); if (!convert) { return convert; } Date date = (Date) result.getValue(container.getName()); if (date == null) { return convert; } result.setValue(container.getName(), new Timestamp(date.getTime())); return true; }
private void collectValidationPointsForMessages() { for (QName msgName : messageRefNames) { javax.wsdl.Message message = getMessage(msgName); for (Iterator<?> iter = message.getParts().values().iterator(); iter.hasNext(); ) { Part part = (Part) iter.next(); QName elementName = part.getElementName(); QName typeName = part.getTypeName(); if (elementName == null && typeName == null) { vResults.addError(new Message("PART_NO_TYPES", LOG)); continue; } if (elementName != null && typeName != null) { vResults.addError(new Message("PART_NOT_UNIQUE", LOG)); continue; } if (elementName != null && typeName == null) { boolean valid = validatePartType(elementName.getNamespaceURI(), elementName.getLocalPart(), true); if (!valid) { vResults.addError( new Message( "TYPE_REF_NOT_FOUND", LOG, message.getQName(), part.getName(), elementName)); } } if (typeName != null && elementName == null) { boolean valid = validatePartType(typeName.getNamespaceURI(), typeName.getLocalPart(), false); if (!valid) { vResults.addError( new Message( "TYPE_REF_NOT_FOUND", LOG, message.getQName(), part.getName(), typeName)); } } } } }
@Override public void flush() { log.debug("Going to store validation result in key-value storage"); Namespace namespace = namespace(); KeyValueStorage keyValueStorage = kernelContext.getService(KeyValueStorage.class); keyValueStorage.put( namespace, RESULT, ValidationResult.create(validator.getName(), invoked, failed)); log.debug("invoked {} failed {}", invoked, failed); }
private void saveToCache(ValidationResult res, String cacheName) throws IOException { if (cacheName == null) return; if (res.getDisplay() != null) TextFile.stringToFile(res.getDisplay(), cacheName); else if (res.getMessage() != null) { if (res.getSeverity() == IssueSeverity.WARNING) TextFile.stringToFile("!warning: " + res.getMessage(), cacheName); else TextFile.stringToFile("!error: " + res.getMessage(), cacheName); } }
public String getErrorMessage() { return vResults.toString(); }
private void addWarning(String warningMsg) { if (suppressWarnings) { return; } vResults.addWarning(warningMsg); }
private static ValidationResult conjunctionOf(ValidationResult a, ValidationResult b) { return a.isOk() ? b : a; }
private static String getMessage(ValidationResult validationResult) { return "Request is invalid: " + validationResult.getMessages().stream().collect(Collectors.joining(", ")); }
@Override protected boolean canDoAction() { if (disk == null) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VM_IMAGE_DOES_NOT_EXIST); } DiskValidator oldDiskValidator = new DiskValidator(disk); ValidationResult isHostedEngineDisk = oldDiskValidator.validateNotHostedEngineDisk(); if (!isHostedEngineDisk.isValid()) { return validate(isHostedEngineDisk); } disk.setReadOnly(getParameters().isReadOnly()); DiskValidator diskValidator = getDiskValidator(disk); if (!checkDiskUsedAsOvfStore(diskValidator)) { return false; } if (isOperationPerformedOnDiskSnapshot() && (!validate(getSnapshotsValidator().snapshotExists(getSnapshot())) || !validate( getSnapshotsValidator() .snapshotTypeSupported( getSnapshot(), Collections.singletonList(SnapshotType.REGULAR))))) { return false; } boolean isImageDisk = disk.getDiskStorageType().isInternal(); if (isImageDisk) { // TODO : this load and check of the active disk will be removed // after inspecting upgrade Disk activeDisk = loadActiveDisk(disk.getId()); if (((DiskImage) activeDisk).getImageStatus() == ImageStatus.ILLEGAL) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_DISK_OPERATION); } if (((DiskImage) disk).getImageStatus() == ImageStatus.LOCKED) { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_DISKS_LOCKED); addCanDoActionMessageVariable("diskAliases", disk.getDiskAlias()); return false; } } if (!isVmExist() || !isVmInUpPausedDownStatus()) { return false; } if (!canRunActionOnNonManagedVm()) { return false; } updateDisksFromDb(); if (!isDiskCanBeAddedToVm(disk, getVm()) || !isDiskPassPciAndIdeLimit(disk)) { return false; } if (getVmDeviceDao().exists(new VmDeviceId(disk.getId(), getVmId()))) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_DISK_ALREADY_ATTACHED); } if (disk.isShareable() && !isVersionSupportedForShareable( disk, getStoragePoolDao() .get(getVm().getStoragePoolId()) .getCompatibilityVersion() .getValue())) { return failCanDoAction(EngineMessage.ACTION_NOT_SUPPORTED_FOR_CLUSTER_POOL_LEVEL); } if (!isOperationPerformedOnDiskSnapshot() && !disk.isShareable() && disk.getNumberOfVms() > 0) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_NOT_SHAREABLE_DISK_ALREADY_ATTACHED); } if (isImageDisk && getStoragePoolIsoMapDao() .get( new StoragePoolIsoMapId( ((DiskImage) disk).getStorageIds().get(0), getVm().getStoragePoolId())) == null) { return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_MATCH); } if (isImageDisk) { StorageDomain storageDomain = getStorageDomainDao() .getForStoragePool( ((DiskImage) disk).getStorageIds().get(0), ((DiskImage) disk).getStoragePoolId()); StorageDomainValidator storageDomainValidator = getStorageDomainValidator(storageDomain); if (!validate(storageDomainValidator.isDomainExistAndActive())) { return false; } } if (!validate(diskValidator.isReadOnlyPropertyCompatibleWithInterface())) { return false; } if (!validate(diskValidator.isVirtIoScsiValid(getVm()))) { return false; } if (!validate(diskValidator.isDiskInterfaceSupported(getVm()))) { return false; } if (!isVmNotInPreviewSnapshot()) { return false; } if (getParameters().isPlugUnPlug() && getVm().getStatus() != VMStatus.Down) { return canPerformDiskHotPlug(disk); } return true; }