javax.validation.ValidationException Java Examples

The following examples show how to use javax.validation.ValidationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExperimentTest.java    From alchemy with MIT License 7 votes vote down vote up
@Test
public void testClearTreatments()  throws ValidationException {
    final Experiment experiment =
        new Experiment(null, "foo")
            .addTreatment("bar")
            .allocate("bar", 10)
            .addOverride("override", "bar", "true");

    assertEquals(1, experiment.getTreatments().size());
    assertEquals(1, experiment.getAllocations().size());
    assertEquals(1, experiment.getOverrides().size());

    experiment.clearTreatments();

    assertEquals(0, experiment.getTreatments().size());
    assertEquals(0, experiment.getAllocations().size());
    assertEquals(0, experiment.getOverrides().size());
}
 
Example #2
Source File: ExperimentTest.java    From alchemy with MIT License 6 votes vote down vote up
@Test
public void testCopyOf()  throws ValidationException {
    assertNull(Experiment.copyOf(null));

    final Experiment original =
        new Experiment(null, "experiment")
            .activate()
            .addTreatment("foo")
            .addOverride("override", "foo", "true")
            .allocate("foo", 10);

    final Experiment copy = Experiment.copyOf(original);

    assertFalse(original == copy);
    assertFalse(original.getTreatments().get(0) == copy.getTreatments().get(0));
    assertFalse(original.getAllocations().get(0) == copy.getAllocations().get(0));
    assertFalse(original.getOverrides().get(0) == copy.getOverrides().get(0));
    assertTrue(copy.getAllocations().get(0).getTreatment() == copy.getTreatments().get(0));
    assertTrue(copy.getOverrides().get(0).getTreatment() == copy.getTreatments().get(0));
}
 
Example #3
Source File: PropertyInjectorVisitor.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Override
public void setup(DAGSetupPlugin.Context context)
{
  this.dag = context.getDAG();
  try {
    this.path = context.getConfiguration().get("propertyVisitor.Path");
    Properties properties = new Properties();
    properties.load(this.getClass().getResourceAsStream(path));
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
      propertyMap.put(entry.getKey().toString(), entry.getValue().toString());
    }
  } catch (IOException ex) {
    throw new ValidationException("Not able to load input file " + path);
  }
  context.register(PRE_VALIDATE_DAG, this);
}
 
Example #4
Source File: ValidatingInvoker.java    From dropwizard-jaxws with Apache License 2.0 6 votes vote down vote up
/**
 * Copied and modified from com.yammer.dropwizard.jersey.jackson#JacksonMessageBodyProvider.validate()
 * Notes on Hibernate Validator:
 * - when validating object graphs, null references are ignored.
 * - from version 5 on, Hibernate Validator throws IllegalArgumentException instead of ValidationException
 *   for null parameter values:
 *   java.lang.IllegalArgumentException: HV000116: The object to be validated must not be null.
 */
private Object validate(Annotation[] annotations, Object value) {
    final Class<?>[] classes = findValidationGroups(annotations);

    if (classes != null) {
        final Collection<String> errors = ConstraintViolations.format(
                validator.validate(value, classes));

        if (!errors.isEmpty()) {
            String message = "\n";
            for (String error : errors) {
                message += "    " + error + "\n";
            }
            throw new ValidationException(message);
        }
    }

    return value;
}
 
Example #5
Source File: AbstractDataSetResource.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private void validateFields(String formula, List<SimpleSelectionField> columns) {
	String regex = REGEX_FIELDS_VALIDATION;
	Pattern p = Pattern.compile(regex);
	Matcher m = p.matcher(formula);

	while (m.find()) {
		boolean found = false;
		for (SimpleSelectionField simpleSelectionField : columns) {

			if (simpleSelectionField.getName().equals(m.group(0).replace("\"", ""))) {
				found = true;
				break;
			}
		}

		if (!found)
			throw new ValidationException();
	}

}
 
Example #6
Source File: TypeSafeActivator.java    From hibersap with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused") // called by reflection
static void activateBeanValidation(final Set<BapiInterceptor> bapiInterceptors,
                                   final SessionManagerConfig sessionManagerConfig) {
    try {
        ValidatorFactory factory = validatorFactoryFactory.buildValidatorFactory();
        bapiInterceptors.add(new BeanValidationInterceptor(factory));
    } catch (ValidationException e) {
        ValidationMode validationMode = sessionManagerConfig.getValidationMode();
        if (validationMode == ValidationMode.AUTO) {
            LOGGER.warn("Bean Validation will not be used: Bean Validation API is in the classpath, " +
                    "but default ValidatorFactory can not be built. " +
                    "ValidationMode is AUTO, so startup will be continued.", e);
        } else {
            throw new HibersapException("Unable to build the default ValidatorFactory, ValidationMode is " +
                    validationMode, e);
        }
    }
}
 
Example #7
Source File: LogicalPlanTest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testLocalityValidation()
{
  TestGeneratorInputOperator input1 = dag.addOperator("input1", TestGeneratorInputOperator.class);
  GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class);
  StreamMeta s1 = dag.addStream("input1.outport", input1.outport, o1.inport1).setLocality(Locality.THREAD_LOCAL);
  dag.validate();

  TestGeneratorInputOperator input2 = dag.addOperator("input2", TestGeneratorInputOperator.class);
  dag.addStream("input2.outport", input2.outport, o1.inport2);

  try {
    dag.validate();
    Assert.fail("Exception expected for " + o1);
  } catch (ValidationException ve) {
    Assert.assertThat("", ve.getMessage(), RegexMatcher.matches("Locality THREAD_LOCAL invalid for operator .* with multiple input streams .*"));
  }

  s1.setLocality(null);
  dag.validate();
}
 
Example #8
Source File: Input.java    From onedev with MIT License 6 votes vote down vote up
@Nullable
public Object getTypedValue(@Nullable InputSpec inputSpec) {
	if (inputSpec != null) {
		try {
			return inputSpec.convertToObject(getValues());
		} catch (ValidationException e) {
			String displayValue;
			if (type.equals(FieldSpec.SECRET)) 
				displayValue = SecretInput.MASK;
			else 
				displayValue = "" + getValues();
			
			logger.error("Error converting field value (field: {}, value: {}, error: {})", 
					getName(), displayValue, e.getMessage());
			return null;
		}
	} else {
		return null;
	}
}
 
Example #9
Source File: MgmtTargetResource.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ResponseEntity<MgmtAction> updateAction(@PathVariable("targetId") final String targetId,
        @PathVariable("actionId") final Long actionId, @RequestBody final MgmtActionRequestBodyPut actionUpdate) {

    Action action = deploymentManagement.findAction(actionId)
            .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
    if (!action.getTarget().getControllerId().equals(targetId)) {
        LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), targetId);
        return ResponseEntity.notFound().build();
    }

    if (MgmtActionType.FORCED != actionUpdate.getActionType()) {
        throw new ValidationException("Resource supports only switch to FORCED.");
    }

    action = deploymentManagement.forceTargetAction(actionId);

    return ResponseEntity.ok(MgmtTargetMapper.toResponseWithLinks(targetId, action));
}
 
Example #10
Source File: ValidationExceptionMapper.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public Response toResponse(ValidationException exception) {
    logException(exception);

    Response.ResponseBuilder responseBuilder;

    if (exception instanceof ConstraintViolationException) {
        responseBuilder = Response.status(Response.Status.BAD_REQUEST);
    } else {
        responseBuilder = Response.serverError();
        Monitors.error("error", "error");
    }

    Map<String, Object> entityMap = new HashMap<>();
    entityMap.put("instance", host);

    responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
    responseBuilder.entity(toErrorResponse(exception));

    return responseBuilder.build();
}
 
Example #11
Source File: LogicalPlanModificationTest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetOperatorProperty()
{
  GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class);
  OperatorMeta o1Meta = dag.getMeta(o1);

  TestPlanContext ctx = new TestPlanContext();
  dag.setAttribute(OperatorContext.STORAGE_AGENT, ctx);
  PhysicalPlan plan = new PhysicalPlan(dag, ctx);
  ctx.deploy.clear();
  ctx.undeploy.clear();

  PlanModifier pm = new PlanModifier(plan);
  try {
    pm.setOperatorProperty(o1Meta.getName(), "myStringProperty", "propertyValue");
    Assert.fail("validation error exepected");
  } catch (javax.validation.ValidationException e) {
    Assert.assertTrue(e.getMessage().contains(o1Meta.toString()));
  }

  GenericTestOperator newOperator = new GenericTestOperator();
  pm.addOperator("newOperator", newOperator);
  pm.setOperatorProperty("newOperator", "myStringProperty", "propertyValue");
  Assert.assertEquals("", "propertyValue", newOperator.getMyStringProperty());
}
 
Example #12
Source File: PlanModifier.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
/**
 * Add stream to logical plan. If a stream with same name and source already
 * exists, the new downstream operator will be attached to it.
 *
 * @param streamName
 * @param sourceOperName
 * @param sourcePortName
 * @param targetOperName
 * @param targetPortName
 */
public void addStream(String streamName, String sourceOperName, String sourcePortName, String targetOperName, String targetPortName)
{
  OperatorMeta om = logicalPlan.getOperatorMeta(sourceOperName);
  if (om == null) {
    throw new ValidationException("Invalid operator name " + sourceOperName);
  }

  Operators.PortMappingDescriptor portMap = new Operators.PortMappingDescriptor();
  Operators.describe(om.getOperator(), portMap);
  PortContextPair<OutputPort<?>> sourcePort = portMap.outputPorts.get(sourcePortName);
  if (sourcePort == null) {
    throw new AssertionError(String.format("Invalid port %s (%s)", sourcePortName, om));
  }
  addStream(streamName, sourcePort.component, getInputPort(targetOperName, targetPortName));
}
 
Example #13
Source File: AllocationsTest.java    From alchemy with MIT License 6 votes vote down vote up
@Test
public void testClear() {
    Treatment t1, t2;
    try {
        t1 = new Treatment("control");
        t2 = new Treatment("other");
    } catch (ValidationException e) {
        // this should never happen
        t1 = null;
        t2 = null;
    }

    final  Allocations allocations = new Allocations(Lists.newArrayList(
        new Allocation(t1, 0, 5),
        new Allocation(t2, 5, 5)
    ));

    assertEquals(2, allocations.getAllocations().size());
    assertEquals(10, allocations.getSize());

    allocations.clear();

    assertEquals(0, allocations.getAllocations().size());
    assertEquals(0, allocations.getSize());
}
 
Example #14
Source File: CapabilityDescriptorSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
protected void validateUnique(@Nullable final CapabilityIdentity id, final Map<String, String> properties)
{
  CapabilityReferenceFilter filter = duplicatesFilter(id, properties);

  log.trace("Validating that unique capability of type {} and properties {}", type(), filter.getProperties());

  Collection<? extends CapabilityReference> references = capabilityRegistry.get().get(filter);
  if (!references.isEmpty()) {
    StringBuilder message = new StringBuilder().append("Only one capability of type '").append(name()).append("'");
    for (Entry<String, String> entry : filter.getProperties().entrySet()) {
      message.append(", ").append(propertyName(entry.getKey()).toLowerCase()).append(" '").append(entry.getValue())
          .append("'");
    }
    message.append(" can be created");
    throw new ValidationException(message.toString());
  }
}
 
Example #15
Source File: ResteasyViolationExceptionMapper.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public Response toResponse(ValidationException exception) {
    if (exception instanceof ConstraintDefinitionException) {
        return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
    }
    if (exception instanceof ConstraintDeclarationException) {
        return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
    }
    if (exception instanceof GroupDefinitionException) {
        return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
    }
    if (exception instanceof ResteasyViolationException) {
        ResteasyViolationException resteasyViolationException = ResteasyViolationException.class.cast(exception);
        Exception e = resteasyViolationException.getException();
        if (e != null) {
            return buildResponse(unwrapException(e), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
        } else if (resteasyViolationException.getReturnValueViolations().size() == 0) {
            return buildViolationReportResponse(resteasyViolationException, Status.BAD_REQUEST);
        } else {
            return buildViolationReportResponse(resteasyViolationException, Status.INTERNAL_SERVER_ERROR);
        }
    }
    return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
}
 
Example #16
Source File: OptionalValidatorFactoryBean.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() {
	try {
		super.afterPropertiesSet();
	}
	catch (ValidationException ex) {
		LogFactory.getLog(getClass()).debug("Failed to set up a Bean Validation provider", ex);
	}
}
 
Example #17
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void validate() {
	if (urlCustomer == null) {
		throw new ValidationException("No URL for the Customer Service!");
	}
	if (urlFactory == null) {
		throw new ValidationException("No URL for the Factory Service!");
	}
	if (urlOrder == null) {
		throw new ValidationException("No URL for the Factory Service!");
	}
}
 
Example #18
Source File: AbstractDataSetResource.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void validateBrackets(String formula) {
	int roundBrackets = 0;
	int squareBrackets = 0;
	int curlyBrackets = 0;

	for (int i = 0; i < formula.length(); i++) {
		switch (formula.charAt(i)) {
		case '(':
			roundBrackets++;
			break;
		case ')':
			roundBrackets--;
			break;
		case '[':
			squareBrackets++;
			break;
		case ']':
			squareBrackets--;
			break;
		case '{':
			curlyBrackets++;
			break;
		case '}':
			curlyBrackets--;
			break;

		default:
			break;
		}
	}

	if (roundBrackets != 0 || squareBrackets != 0 || curlyBrackets != 0)
		throw new ValidationException();

}
 
Example #19
Source File: ParamSupply.java    From onedev with MIT License 5 votes vote down vote up
private static void validateParamNames(Collection<String> paramSpecNames, Collection<String> paramNames) {
	for (String paramSpecName: paramSpecNames) {
		if (!paramNames.contains(paramSpecName))
			throw new ValidationException("Missing job parameter: " + paramSpecName);
	}
	for (String paramName: paramNames) {
		if (!paramSpecNames.contains(paramName))
			throw new ValidationException("Unknown job parameter: " + paramName);
	}
}
 
Example #20
Source File: ContainersImpl.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
    public boolean deploy(final InputStream archive, final String name) {
        if (!OpenEJB.isInitialized()) stuck = name;
        else System.out.println("STUCK " + stuck);

        exception = null;

        final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);

        ThreadSingletonServiceImpl.exit(null);
        if (assembler != null) {
            assembler.destroy();
        }
        try {
            final File file = writeToFile(archive, name);
            final Map<String, Object> map = new HashMap<String, Object>();
            map.put(EJBContainer.MODULES, file);
            map.put(EJBContainer.APP_NAME, name);

            originalClassLoader = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[]{file.toURI().toURL()}, originalClassLoader));
            container = EJBContainer.createEJBContainer(map);

//            final WebBeansContext webBeansContext = ThreadSingletonServiceImpl.get();
//            dump(webBeansContext.getBeanManagerImpl());
        } catch (Exception e) {
            if (e instanceof EJBException && e.getCause() instanceof ValidationException) {
                exception = ValidationException.class.cast(e.getCause());
            } else {
                exception = e;
            }
            return false;
        }

        return true;
    }
 
Example #21
Source File: AfterEqualsToTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void no_such_method_exception_test() {
    thrown.expect(ValidationException.class);
    thrown.expectMessage(CoreMatchers.containsString("HV000028"));
    AfterEqualsToErrorTestBean target = new AfterEqualsToErrorTestBean();
    VALIDATOR.validate(target);
}
 
Example #22
Source File: BeanValidator.java    From Guice-configuration with Apache License 2.0 5 votes vote down vote up
public BeanValidator() {
    ValidatorFactory f = null;
    try {
        f = Validation.buildDefaultValidatorFactory();
        log.debug("Validation factory builder found");
    } catch (ValidationException e) {
        log.debug("No validation factory found in classpath");
    } finally {
        factory = f;
    }
}
 
Example #23
Source File: ParamSupply.java    From onedev with MIT License 5 votes vote down vote up
public static void validateParams(List<ParamSpec> paramSpecs, List<ParamSupply> params) {
	Map<String, List<List<String>>> paramMap = new HashMap<>();
	for (ParamSupply param: params) {
		List<List<String>> values;
		if (param.getValuesProvider() instanceof SpecifiedValues)
			values = param.getValuesProvider().getValues();
		else
			values = null;
		if (paramMap.put(param.getName(), values) != null)
			throw new ValidationException("Duplicate param: " + param.getName());
	}
	validateParamMatrix(getParamSpecMap(paramSpecs), paramMap);
}
 
Example #24
Source File: ValidationExceptionMapper.java    From conductor with Apache License 2.0 5 votes vote down vote up
private static ErrorResponse toErrorResponse(ValidationException ve) {
    if ( ve instanceof ConstraintViolationException ) {
        return constraintViolationExceptionToErrorResponse((ConstraintViolationException) ve);
    } else {
        ErrorResponse result = new ErrorResponse();
        result.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        result.setMessage(ve.getMessage());
        return result;
    }
}
 
Example #25
Source File: IPv4Test.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidOnly() {

    thrown.expect(ValidationException.class);
    thrown.expectMessage(containsString("HV000032"));
    class IPv4TargetBean {

        @IPv4(only = {
            "foo", "bar"
        })
        public String value;
    }
    IPv4TargetBean target = new IPv4TargetBean();
    VALIDATOR.validate(target);
}
 
Example #26
Source File: FieldSupply.java    From onedev with MIT License 5 votes vote down vote up
public static void validateFields(Map<String, FieldSpec> fieldSpecs, List<FieldSupply> fields) {
	Map<String, List<String>> fieldMap = new HashMap<>();
	for (FieldSupply field: fields) {
		List<String> values;
		if (field.getValueProvider() instanceof SpecifiedValue)
			values = field.getValueProvider().getValue();
		else
			values = null;
		if (fieldMap.put(field.getName(), values) != null)
			throw new ValidationException("Duplicate field: " + field.getName());
	}
	validateFieldMap(fieldSpecs, fieldMap);
}
 
Example #27
Source File: FieldSupply.java    From onedev with MIT License 5 votes vote down vote up
private static void validateFieldNames(Collection<String> fieldSpecNames, Collection<String> fieldNames) {
	for (String fieldSpecName: fieldSpecNames) {
		if (!fieldNames.contains(fieldSpecName))
			throw new ValidationException("Missing issue field: " + fieldSpecName);
	}
	for (String fieldName: fieldNames) {
		if (!fieldSpecNames.contains(fieldName))
			throw new ValidationException("Unknown issue field: " + fieldName);
	}
}
 
Example #28
Source File: DefaultExceptionMapper.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(Exception exception) {
    final int statusCode;
    if (exception instanceof WebApplicationException) {
        statusCode = ((WebApplicationException) exception).getResponse().getStatus();
    } else if (exception instanceof KubernetesClientException) {
        KubernetesClientException kce = (KubernetesClientException) exception;
        if (kce.getStatus() != null) {
            statusCode = kce.getStatus().getCode();
        } else if (kce.getCause() instanceof SocketTimeoutException) {
            statusCode = Response.Status.SERVICE_UNAVAILABLE.getStatusCode();
        } else {
            statusCode = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
        }

    } else if (exception instanceof UnresolvedAddressException || exception instanceof JsonProcessingException || exception instanceof UnresolvedAddressSpaceException || exception instanceof ValidationException) {
        statusCode = Response.Status.BAD_REQUEST.getStatusCode();
    } else {
        statusCode = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
    }
    Response response = Response.status(statusCode)
            .entity(Status.failureStatus(statusCode, getReasonPhrase(statusCode), exception.getMessage()))
            .build();

    if (Response.Status.Family.familyOf(statusCode) == Response.Status.Family.CLIENT_ERROR) {
        log.info("Returning client error HTTP status {}: {}", statusCode, exception.getMessage());
    } else {
        log.warn("Returning server error HTTP status " + statusCode, exception);
    }

    return response;
}
 
Example #29
Source File: PageBulkDeleteController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping
public String delete(
		@Valid @ModelAttribute("form") PageBulkDeleteForm form,
		BindingResult errors,
		String query,
		RedirectAttributes redirectAttributes) {
	redirectAttributes.addAttribute("query", query);

	if (!form.isConfirmed()) {
		errors.rejectValue("confirmed", "Confirmed");
	}
	if (errors.hasErrors()) {
		logger.debug("Errors: {}", errors);
		return "redirect:/_admin/{language}/pages/index";
	}
	
	Collection<Page> pages = null;
	try {
		pages = pageService.bulkDeletePage(form.buildPageBulkDeleteRequest(), errors);
	}
	catch (ValidationException e) {
		if (errors.hasErrors()) {
			logger.debug("Errors: {}", errors);
			return "redirect:/_admin/{language}/pages/index";
		}
		throw e;
	}
	
	List<String> errorMessages = null;
	if (errors.hasErrors()) {
		errorMessages = new ArrayList<>();
		for (ObjectError error : errors.getAllErrors()) {
			errorMessages.add(messageSourceAccessor.getMessage(error));
		}
	}
	
	redirectAttributes.addFlashAttribute("deletedPages", pages);
	redirectAttributes.addFlashAttribute("errorMessages", errorMessages);
	return "redirect:/_admin/{language}/pages/index";
}
 
Example #30
Source File: IssueChoiceInput.java    From onedev with MIT License 5 votes vote down vote up
public static Object convertToObject(List<String> strings) {
	if (strings.size() == 0) {
		return null;
	} else if (strings.size() == 1) {
		String value = strings.iterator().next();
		try {
			return Long.valueOf(value);
		} catch (NumberFormatException e) {
			throw new ValidationException("Invalid issue number");
		}
	} else {
		throw new ValidationException("Not eligible for multi-value");
	}
}