Java Examples for javax.validation.ValidationException

The following java examples will help you to understand the usage of javax.validation.ValidationException. These source code samples are taken from different open source projects.

Example 1
Project: gabinete-virtual-master  File: ProdutoController.java View source code
@RequestMapping(value = "/produto/salvarProduto", method = RequestMethod.POST)
public String salvarProduto(@Valid Produto produto, BindingResult result, ModelMap model) {
    String mensagem = null;
    if (result.hasFieldErrors("nome") || result.hasFieldErrors("descricao") || result.hasFieldErrors("preco")) {
        mensagem = mensagensPadronizadas.erroAoCadastrarProduto;
        model.addAttribute("mensagemTitulo", mensagem);
        return "forward:/produto";
    } else {
        try {
            produtoService.salvarProduto(produto);
            mensagem = mensagensPadronizadas.produtoAdicionadoComSucesso;
        } catch (ValidationException e) {
            mensagem = e.getMessage();
        }
        model.addAttribute("mensagemTitulo", mensagem);
        return "forward:/produto";
    }
}
Example 2
Project: spring-framework-master  File: MethodValidationTests.java View source code
@SuppressWarnings("unchecked")
private void doTestProxyValidation(MyValidInterface proxy) {
    assertNotNull(proxy.myValidMethod("value", 5));
    try {
        assertNotNull(proxy.myValidMethod("value", 15));
        fail("Should have thrown ValidationException");
    } catch (javax.validation.ValidationException ex) {
    }
    try {
        assertNotNull(proxy.myValidMethod(null, 5));
        fail("Should have thrown ValidationException");
    } catch (javax.validation.ValidationException ex) {
    }
    try {
        assertNotNull(proxy.myValidMethod("value", 0));
        fail("Should have thrown ValidationException");
    } catch (javax.validation.ValidationException ex) {
    }
    proxy.myValidAsyncMethod("value", 5);
    try {
        proxy.myValidAsyncMethod("value", 15);
        fail("Should have thrown ValidationException");
    } catch (javax.validation.ValidationException ex) {
    }
    try {
        proxy.myValidAsyncMethod(null, 5);
        fail("Should have thrown ValidationException");
    } catch (javax.validation.ValidationException ex) {
    }
    assertEquals("myValue", proxy.myGenericMethod("myValue"));
    try {
        proxy.myGenericMethod(null);
        fail("Should have thrown ValidationException");
    } catch (javax.validation.ValidationException ex) {
    }
}
Example 3
Project: morphia-master  File: TestMorphiaValidation.java View source code
/**
     * Test method for {@link ValidationExtension#prePersist(Object, com.mongodb.DBObject, org.mongodb.morphia.mapping.Mapper)}.
     */
@Test
public final void testPrePersist() {
    final E e = new E();
    e.email = "not an email";
    new ValidationExtension(getMorphia());
    try {
        getDs().save(e);
        Assert.fail("Should have failed validation");
    } catch (ValidationException exception) {
    }
    e.email = "foo@bar.com";
    getDs().save(e);
}
Example 4
Project: hibernate-validator-master  File: ConstraintDescriptorImpl.java View source code
@SuppressWarnings("unchecked")
private Set<Class<? extends Payload>> buildPayloadSet(T annotation) {
    Set<Class<? extends Payload>> payloadSet = newHashSet();
    Class<Payload>[] payloadFromAnnotation;
    try {
        //TODO be extra safe and make sure this is an array of Payload
        payloadFromAnnotation = run(GetAnnotationParameter.action(annotation, ConstraintHelper.PAYLOAD, Class[].class));
    } catch (ValidationException e) {
        payloadFromAnnotation = null;
    }
    if (payloadFromAnnotation != null) {
        payloadSet.addAll(Arrays.asList(payloadFromAnnotation));
    }
    return CollectionHelper.toImmutableSet(payloadSet);
}
Example 5
Project: beanvalidation-tck-master  File: MessageInterpolationTest.java View source code
@Test
@SpecAssertion(section = Sections.VALIDATIONAPI_MESSAGE_CUSTOMRESOLUTION, id = "g")
public void testExceptionDuringMessageInterpolationIsWrappedIntoValidationException() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    ExceptionThrowingMessageInterpolator interpolator = new ExceptionThrowingMessageInterpolator();
    Validator validator = factory.usingContext().messageInterpolator(interpolator).getValidator();
    try {
        validator.validate(new TestBeanWithPropertyConstraint("Bob"));
        fail("Expected exception wasn't thrown.");
    } catch (ValidationException ve) {
        assertEquals(ve.getCause(), interpolator.exception);
    }
}
Example 6
Project: google-web-toolkit-svnmirror-master  File: GwtSpecificValidatorCreator.java View source code
@Override
protected void compose(ClassSourceFileComposerFactory composerFactory) {
    addImports(composerFactory, Annotation.class, ConstraintViolation.class, GWT.class, GwtBeanDescriptor.class, GwtValidationContext.class, HashSet.class, IllegalArgumentException.class, Set.class, ValidationException.class);
    composerFactory.setSuperclass(AbstractGwtSpecificValidator.class.getCanonicalName() + "<" + beanType.getQualifiedSourceName() + ">");
    composerFactory.addImplementedInterface(validatorType.getName());
}
Example 7
Project: gwt-sandbox-master  File: GwtSpecificValidatorCreator.java View source code
@Override
protected void compose(ClassSourceFileComposerFactory composerFactory) {
    addImports(composerFactory, Annotation.class, ConstraintViolation.class, GWT.class, ValidationGroupsMetadata.class, Group.class, GroupChain.class, PathImpl.class, Node.class, GroupChainGenerator.class, GwtBeanDescriptor.class, BeanMetadata.class, GwtValidationContext.class, ArrayList.class, HashSet.class, IllegalArgumentException.class, Set.class, Collection.class, Iterator.class, List.class, ValidationException.class);
    composerFactory.setSuperclass(AbstractGwtSpecificValidator.class.getCanonicalName() + "<" + beanType.getQualifiedSourceName() + ">");
    composerFactory.addImplementedInterface(validatorType.getName());
}
Example 8
Project: gwt.svn-master  File: GwtSpecificValidatorCreator.java View source code
@Override
protected void compose(ClassSourceFileComposerFactory composerFactory) {
    addImports(composerFactory, Annotation.class, ConstraintViolation.class, GWT.class, ValidationGroupsMetadata.class, Group.class, GroupChain.class, PathImpl.class, Node.class, GroupChainGenerator.class, GwtBeanDescriptor.class, BeanMetadata.class, GwtValidationContext.class, ArrayList.class, HashSet.class, IllegalArgumentException.class, Set.class, Collection.class, Iterator.class, List.class, ValidationException.class);
    composerFactory.setSuperclass(AbstractGwtSpecificValidator.class.getCanonicalName() + "<" + beanType.getQualifiedSourceName() + ">");
    composerFactory.addImplementedInterface(validatorType.getName());
}
Example 9
Project: scalagwt-gwt-master  File: GwtSpecificValidatorCreator.java View source code
@Override
protected void compose(ClassSourceFileComposerFactory composerFactory) {
    addImports(composerFactory, Annotation.class, ConstraintViolation.class, GWT.class, GwtBeanDescriptor.class, GwtValidationContext.class, HashSet.class, IllegalArgumentException.class, Set.class, ValidationException.class);
    composerFactory.setSuperclass(AbstractGwtSpecificValidator.class.getCanonicalName() + "<" + beanType.getQualifiedSourceName() + ">");
    composerFactory.addImplementedInterface(validatorType.getName());
}
Example 10
Project: sitebricks-master  File: DefaultPageBook.java View source code
private static Object call(Object page, final Method method, Object[] args) {
    try {
        return method.invoke(page, args);
    } catch (IllegalAccessException e) {
        throw new EventDispatchException("Could not access event method (appears to be a security problem): " + method, e);
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause instanceof ValidationException) {
            throw (ValidationException) cause;
        }
        StackTraceElement[] stackTrace = cause.getStackTrace();
        throw new EventDispatchException(String.format("Exception [%s - \"%s\"] thrown by event method [%s]\n\nat %s\n" + "(See below for entire trace.)\n", cause.getClass().getSimpleName(), cause.getMessage(), method, stackTrace[0]), e);
    }
}
Example 11
Project: storm-data-contracts-master  File: ContractValidator.java View source code
public <T> ValidatedContract<T> validate(T contract) {
    try {
        if (contract != null) {
            Set e = this.validator.validate(contract, new Class[0]);
            return new ValidatedContract(contract, e);
        } else {
            return new ValidatedContract(contract, new ValidationException("Contract cannot be null"));
        }
    } catch (ValidationException var3) {
        return new ValidatedContract(contract, var3);
    }
}
Example 12
Project: arquillian-weld-embedded-1.1-master  File: MockValidationServices.java View source code
public ValidatorFactory getDefaultValidatorFactory() {
    return new ValidatorFactory() {

        public ValidatorContext usingContext() {
            // TODO Auto-generated method stub
            return null;
        }

        public <T> T unwrap(Class<T> type) {
            if (type.equals(ValidatorFactory.class)) {
                return type.cast(this);
            } else {
                throw new ValidationException();
            }
        }

        public Validator getValidator() {
            return new MockValidator();
        }

        public TraversableResolver getTraversableResolver() {
            // TODO Auto-generated method stub
            return null;
        }

        public MessageInterpolator getMessageInterpolator() {
            // TODO Auto-generated method stub
            return null;
        }

        public ConstraintValidatorFactory getConstraintValidatorFactory() {
            // TODO Auto-generated method stub
            return null;
        }
    };
}
Example 13
Project: arquillian_deprecated-master  File: MockValidationServices.java View source code
public ValidatorFactory getDefaultValidatorFactory() {
    return new ValidatorFactory() {

        public ValidatorContext usingContext() {
            // TODO Auto-generated method stub
            return null;
        }

        public <T> T unwrap(Class<T> type) {
            if (type.equals(ValidatorFactory.class)) {
                return type.cast(this);
            } else {
                throw new ValidationException();
            }
        }

        public Validator getValidator() {
            return new MockValidator();
        }

        public TraversableResolver getTraversableResolver() {
            // TODO Auto-generated method stub
            return null;
        }

        public MessageInterpolator getMessageInterpolator() {
            // TODO Auto-generated method stub
            return null;
        }

        public ConstraintValidatorFactory getConstraintValidatorFactory() {
            // TODO Auto-generated method stub
            return null;
        }
    };
}
Example 14
Project: capedwarf-green-master  File: SimpleConstraintDescriptor.java View source code
private Map<String, Object> buildAnnotationParameterMap() {
    final Method[] declaredMethods;
    if (System.getSecurityManager() != null) {
        declaredMethods = AccessController.doPrivileged(new PrivilegedAction<Method[]>() {

            public Method[] run() {
                return annotation.annotationType().getDeclaredMethods();
            }
        });
    } else {
        declaredMethods = annotation.annotationType().getDeclaredMethods();
    }
    Map<String, Object> parameters = new HashMap<String, Object>(declaredMethods.length);
    for (Method m : declaredMethods) {
        try {
            parameters.put(m.getName(), m.invoke(annotation));
        } catch (IllegalAccessException e) {
            throw new ValidationException("Unable to read annotation attributes: " + annotation.getClass(), e);
        } catch (InvocationTargetException e) {
            throw new ValidationException("Unable to read annotation attributes: " + annotation.getClass(), e);
        }
    }
    return Collections.unmodifiableMap(parameters);
}
Example 15
Project: gwt-master  File: GwtSpecificValidatorCreator.java View source code
@Override
protected void compose(ClassSourceFileComposerFactory composerFactory) {
    addImports(composerFactory, Annotation.class, ConstraintViolation.class, GWT.class, ValidationGroupsMetadata.class, Group.class, GroupChain.class, PathImpl.class, Node.class, GroupChainGenerator.class, GwtBeanDescriptor.class, BeanMetadata.class, GwtValidationContext.class, ArrayList.class, HashSet.class, IllegalArgumentException.class, Set.class, Collection.class, Iterator.class, List.class, ValidationException.class);
    composerFactory.setSuperclass(AbstractGwtSpecificValidator.class.getCanonicalName() + "<" + beanType.getQualifiedSourceName() + ">");
    composerFactory.addImplementedInterface(validatorType.getName());
}
Example 16
Project: hibersap-master  File: TypeSafeActivator.java View source code
// called by reflection
@SuppressWarnings("unused")
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 17
Project: iter-master  File: BootstrapingTest.java View source code
// @Test
public void consistencyError() {
    String[] args = "-i input-file.xml -l constant-lhs -n 5 -N 1 -r 10 -c ale -s ale -m http://www.inf.usi.ch/phd/gambi/attachments/autocles/doodle-manifest.xml -j http://www.inf.usi.ch/phd/gambi/attachments/autocles/doodle-clients.jmx".split(" ");
    try {
        // This can generate exception if parsing or validation fail !
        CLIParser parser = registry.getService(CLIParser.class);
        parser.parse(args);
    } catch (ValidationException e) {
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("An Exception was generated");
    }
}
Example 18
Project: jaxrs-oauth2-master  File: GrantTypeBasedResourceComparatorTest.java View source code
@Test
public void should_fail_when_no_grant_type_param_cant_be_read() throws Exception {
    Message message = new MessageImpl();
    when(messageReader.extractGrantTypeParameter(message)).thenThrow(new MessageReadException("can't read grant_type !"));
    thrown.expect(ValidationException.class);
    comparator.compare(new ClassResourceInfo(TestResourceB.class), new ClassResourceInfo(TestResourceA.class), message);
}
Example 19
Project: saos-master  File: EnrichmentTagUploadServiceTest.java View source code
@Test
public void uploadEnrichmentTags_ValidationError() throws Exception {
    // given
    InputStream inputStream = mock(InputStream.class);
    EnrichmentTagItem enrichmentTagItem = mock(EnrichmentTagItem.class);
    when(jsonFactory.createParser(Mockito.any(InputStream.class))).thenReturn(jsonParser);
    when(jsonParser.nextToken()).thenReturn(JsonToken.START_ARRAY);
    when(jsonObjectIterator.nextJsonObject(jsonParser, EnrichmentTagItem.class)).thenReturn(enrichmentTagItem, (EnrichmentTagItem) null);
    Mockito.doThrow(ValidationException.class).when(enrichmentTagItemUploadProcessor).processEnrichmentTagItem(enrichmentTagItem);
    // execute & assert
    executeAndAssertError(inputStream, ERROR_INVALID_DATA);
}
Example 20
Project: spring-boot-master  File: MessageInterpolatorFactory.java View source code
@Override
public MessageInterpolator getObject() throws BeansException {
    try {
        return Validation.byDefaultProvider().configure().getDefaultMessageInterpolator();
    } catch (ValidationException ex) {
        MessageInterpolator fallback = getFallback();
        if (fallback != null) {
            return fallback;
        }
        throw ex;
    }
}
Example 21
Project: AugumentedSzczecin_java-master  File: PoiDao.java View source code
default P checkDuplicateAndCreate(final P entity, final User user) {
    final Long RADIUS = 10l;
    Optional<P> entityWithSameName = findNameDuplicateForOwner(user, entity.getName());
    if (entityWithSameName.isPresent()) {
        // Find 1 entity within {radius} meters around entity.location, owned by user
        Collection<P> entitiesWithSameNameWithinRange = find(entity.getLocation(), RADIUS, // tags
        Collections.<String>emptyList(), Optional.of(entity.getName()), // street
        Optional.absent(), // subs
        Collections.<Place.Subcategory>emptyList(), // paid
        Optional.absent(), // open
        Optional.absent(), // owner
        Optional.of(user), // first page
        Optional.of(0), // 1 result
        1);
        if (!entitiesWithSameNameWithinRange.isEmpty()) {
            throw new ValidationException(String.format("Entity name duplicate within %d meters.", RADIUS));
        }
    }
    return createWithOwner(entity, user);
}
Example 22
Project: candlepin-master  File: ValidationExceptionMapper.java View source code
@Override
public Response toResponse(ValidationException exception) {
    Map<String, String> map = VersionUtil.getVersionMap();
    ResponseBuilder bldr = Response.status(Status.BAD_REQUEST).type(determineBestMediaType()).header(VersionUtil.VERSION_HEADER, map.get("version") + "-" + map.get("release"));
    StringBuffer message = new StringBuffer();
    if (ConstraintViolationException.class.isAssignableFrom(exception.getClass())) {
        for (ConstraintViolation cv : ((ConstraintViolationException) exception).getConstraintViolations()) {
            message.append(cv.getPropertyPath().toString());
            message.append(": ");
            message.append(cv.getMessage());
        }
        bldr.entity(new ExceptionMessage(message.toString()));
    } else {
        getDefaultBuilder(exception, Response.Status.BAD_REQUEST, determineBestMediaType());
    }
    return bldr.build();
}
Example 23
Project: components-master  File: RichFacesBeanValidatorFactory.java View source code
public void init() throws InitializationException {
    // https://jira.jboss.org/jira/browse/RF-7226
    try {
        validatorFactory = Validation.buildDefaultValidatorFactory();
        validatorContext = validatorFactory.usingContext();
        MessageInterpolator jsfMessageInterpolator = new JsfMessageInterpolator(validatorFactory.getMessageInterpolator());
        validatorContext.messageInterpolator(jsfMessageInterpolator);
    } catch (ValidationException e) {
        throw new InitializationException(e);
    }
}
Example 24
Project: Resteasy-master  File: GeneralValidatorImpl.java View source code
@Override
public boolean isMethodValidatable(Method m) {
    if (!isExecutableValidationEnabled) {
        return false;
    }
    ExecutableType[] types = null;
    List<ExecutableType[]> typesList = getExecutableTypesOnMethodInHierarchy(m);
    if (typesList.size() > 1) {
        throw new ValidationException(Messages.MESSAGES.validateOnExceptionOnMultipleMethod());
    }
    if (typesList.size() == 1) {
        types = typesList.get(0);
    } else {
        ValidateOnExecution voe = m.getDeclaringClass().getAnnotation(ValidateOnExecution.class);
        if (voe == null) {
            types = defaultValidatedExecutableTypes;
        } else {
            if (voe.type().length > 0) {
                types = voe.type();
            } else {
                types = defaultValidatedExecutableTypes;
            }
        }
    }
    boolean isGetterMethod = isGetter(m);
    for (int i = 0; i < types.length; i++) {
        switch(types[i]) {
            case IMPLICIT:
            case ALL:
                return true;
            case NONE:
                continue;
            case NON_GETTER_METHODS:
                if (!isGetterMethod) {
                    return true;
                }
                continue;
            case GETTER_METHODS:
                if (isGetterMethod) {
                    return true;
                }
                continue;
            default:
                continue;
        }
    }
    return false;
}
Example 25
Project: billy-master  File: GenericInvoiceEntryBuilderImpl.java View source code
@Override
protected void validateInstance() throws ValidationException {
    this.validateValues();
    GenericInvoiceEntry i = this.getTypeInstance();
    BillyValidator.mandatory(i.getDescription(), GenericInvoiceEntryBuilderImpl.LOCALIZER.getString("field.description"));
    //		BillyValidator.mandatory(i.getCreditOrDebit(), GenericInvoiceEntryBuilderImpl.LOCALIZER
    //						.getString("field.entry_credit_or_debit"));
    BillyValidator.mandatory(i.getTaxPointDate(), GenericInvoiceEntryBuilderImpl.LOCALIZER.getString("field.tax_point_date"));
    BillyValidator.mandatory(i.getCurrency(), GenericInvoiceEntryBuilderImpl.LOCALIZER.getString("field.currency"));
    if (i.getAmountType().compareTo(AmountType.WITH_TAX) == 0) {
        BillyValidator.mandatory(i.getUnitAmountWithoutTax(), GenericInvoiceEntryBuilderImpl.LOCALIZER.getString("field.unit_gross_amount"));
    } else {
        BillyValidator.mandatory(i.getUnitAmountWithoutTax(), GenericInvoiceEntryBuilderImpl.LOCALIZER.getString("field.unit_gross_amount"));
    }
}
Example 26
Project: cxf-master  File: JAXRSClientServerValidationTest.java View source code
protected void run() {
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setResourceClasses(BookStoreWithValidation.class);
    sf.setResourceProvider(BookStoreWithValidation.class, new SingletonResourceProvider(new BookStoreWithValidation()));
    sf.setProvider(new ValidationExceptionMapper() {

        @Override
        public Response toResponse(ValidationException exception) {
            Response r = super.toResponse(exception);
            return JAXRSUtils.toResponseBuilder(r.getStatus()).type("application/xml").entity(new Book("Validation", 123L)).build();
        }
    });
    sf.setAddress("http://localhost:" + PORT + "/");
    BeanValidationInInterceptor in = new JAXRSBeanValidationInInterceptor();
    in.setProvider(new BeanValidationProvider(new JAXRSParameterNameProvider()));
    sf.setInInterceptors(Arrays.<Interceptor<? extends Message>>asList(in));
    sf.setOutInterceptors(Arrays.<Interceptor<? extends Message>>asList(new JAXRSBeanValidationOutInterceptor()));
    sf.create();
}
Example 27
Project: jo-widgets-master  File: BeanValidatorFactory.java View source code
@Override
public Validator create() {
    if (failed) {
        return null;
    } else {
        try {
            return Validation.buildDefaultValidatorFactory().getValidator();
        } catch (final ValidationException e) {
            LOGGER.info("No implementaion for javax.validation (bean balidation) found " + Validator.class.getName() + ". Bean validation anotations will have no effect!", e);
            failed = true;
            return null;
        }
    }
}
Example 28
Project: quickstart-master  File: ContactRESTService.java View source code
/**
     * Creates a new contact from the values provided. Performs validation and will return a JAX-RS response with either 200 (ok)
     * or with a map of fields, and related errors.
     *
     * @param Contact
     * @return Response
     */
@SuppressWarnings("unused")
@POST
public Response createContact(Contact contact) {
    log.info("createContact started. Contact = " + contact.getFirstName() + " " + contact.getLastName() + " " + contact.getEmail() + " " + contact.getPhoneNumber() + " " + contact.getBirthDate() + " " + contact.getId());
    if (contact == null) {
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    }
    Response.ResponseBuilder builder = null;
    try {
        // Go add the new Contact.
        Contact created = service.create(contact);
        // Construct a location of created contact.
        URI location = null;
        try {
            UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
            uriBuilder.path(Long.toString(created.getId()));
            location = uriBuilder.build();
        } catch (LoggableFailure lf) {
        }
        // Create an CREATED Response and pass the URI location back in case it is needed.
        builder = Response.created(location);
        log.info("createContact completed. Contact = " + contact.getFirstName() + " " + contact.getLastName() + " " + contact.getEmail() + " " + contact.getPhoneNumber() + " " + contact.getBirthDate() + " " + contact.getId());
    } catch (ConstraintViolationException ce) {
        log.info("ConstraintViolationException - " + ce.toString());
        builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
        log.info("ValidationException - " + e.toString());
        Map<String, String> responseObj = new HashMap<>();
        responseObj.put("email", "That email is already used, please use a unique email");
        builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
        log.info("Exception - " + e.toString());
        Map<String, String> responseObj = new HashMap<>();
        responseObj.put("error", e.getMessage());
        builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }
    return builder.build();
}
Example 29
Project: rapidoid-master  File: HttpBeanValidationTest.java View source code
@Test
public void testCustomValidation() {
    On.get("/invalid1").html((@Valid Bar bar) -> "ok");
    On.get("/invalid2").json((@Valid Bar bar) -> "ok");
    On.custom().validator(( req,  bean) -> {
        throw U.rte("Invalid!");
    });
    onlyGet("/invalid1?err");
    onlyGet("/invalid2?err");
    On.custom().validator(null);
    My.validator(( req,  bean) -> {
        throw new ValidationException("Validation failed!");
    });
    onlyGet("/invalid1?val");
    onlyGet("/invalid2?val");
    My.validator(null);
    On.custom().validator(( req,  bean) -> {
        throw new InvalidData("Invalid data!");
    });
    onlyGet("/invalid1?inv");
    onlyGet("/invalid2?inv");
}
Example 30
Project: Rhegium-master  File: ValidationTestCase.java View source code
@Test(expected = ValidationException.class)
public void testValidationSettermethodLevelFail() throws Exception {
    Injector injector = buildInjector();
    SetterMethodLevelTest instance = injector.getInstance(SetterMethodLevelTest.class);
    try {
        instance.setTest1(null);
    } catch (ConstraintViolationException e) {
        fail("setTest1(null) thrown ConstraintViolationException");
    } finally {
        try {
            instance.setTest2(null);
        } catch (ValidationException e) {
            e.printStackTrace();
            throw e;
        }
    }
}
Example 31
Project: richfaces-master  File: EventRESTService.java View source code
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response createEvent(Event event) {
    Response.ResponseBuilder builder = null;
    try {
        validateEvent(event);
        ea.addEvent(event);
        // Create an "ok" response
        builder = Response.ok();
    } catch (ConstraintViolationException ce) {
        builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("name", "Name taken");
        builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("error", e.getMessage());
        builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }
    return builder.build();
}
Example 32
Project: spring-cloud-stream-modules-master  File: TriggerProperties.java View source code
public SimpleDateFormat getDateFormat() {
    if (!StringUtils.hasText(this.dateFormat)) {
        throw new ValidationException("'dateFormat' must not be empty.");
    }
    try {
        return new SimpleDateFormat(this.dateFormat);
    } catch (IllegalArgumentException e) {
        throw new ValidationException("Invalid Date format for the string: " + this.dateFormat);
    }
}
Example 33
Project: spring-data-graph-master  File: ValidatingNodePropertyFieldAccessorListenerFactory.java View source code
@Override
public void valueChanged(GraphBacked<T> graphBacked, Object oldVal, Object newVal) {
    if (validator == null)
        return;
    Set<ConstraintViolation<T>> constraintViolations = validator.validateValue((Class<T>) entityType.getType(), propertyName, newVal);
    if (!constraintViolations.isEmpty())
        throw new ValidationException("Error validating field " + propertyName + " of " + entityType + ": " + constraintViolations);
}
Example 34
Project: tools4j-cli-master  File: CliMainTest.java View source code
@Test
public void test_input_constraint_violation() {
    final class ValidatedCommand {

        @CliOption(shortName = "o")
        @Max(10)
        @Min(5)
        @NotNull
        private Integer opt;

        @CliCmd
        public void validate(@Max(10) @Min(5) @NotNull Integer arg) {
        }
    }
    ;
    // success
    String[] args = new String[] { "validate" };
    args = fill(args, new String[] { "-o", "6" });
    args = fill(args, new String[] { "6" });
    CliMain cli = new CliMain(args);
    try {
        cli.run(new ValidatedCommand());
    } catch (ValidationException e) {
        fail(e.getMessage());
    }
    // too small opt
    args = new String[] { "validate" };
    args = fill(args, new String[] { "-o", "4" });
    args = fill(args, new String[] { "6" });
    cli = new CliMain(args);
    try {
        cli.run(new ValidatedCommand());
        fail("Validation exception expected");
    } catch (ValidationException e) {
        assertTrue("Wrong message: " + e.getMessage(), e.getMessage().contains(Validator.OPT_VIOLATION_MSG));
    }
    // too small arg
    args = new String[] { "validate" };
    args = fill(args, new String[] { "-o", "6" });
    args = fill(args, new String[] { "1" });
    cli = new CliMain(args);
    try {
        cli.run(new ValidatedCommand());
        fail("Validation exception expected");
    } catch (ValidationException e) {
        assertTrue("Wrong message: " + e.getMessage(), e.getMessage().contains(Validator.ARG_VIOLATION_MSG));
    }
}
Example 35
Project: dev-examples-master  File: EventRESTService.java View source code
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Response createEvent(Event event) {
    Response.ResponseBuilder builder = null;
    try {
        validateEvent(event);
        ea.addEvent(event);
        // Create an "ok" response
        builder = Response.ok();
    } catch (ConstraintViolationException ce) {
        builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("name", "Name taken");
        builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("error", e.getMessage());
        builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }
    return builder.build();
}
Example 36
Project: eGov-master  File: WaterConnectionDetailsService.java View source code
@Transactional
public WaterConnectionDetails updateWaterConnection(final WaterConnectionDetails waterConnectionDetails, final Long approvalPosition, final String approvalComent, String additionalRule, final String workFlowAction, final String mode, final ReportOutput reportOutput, final String sourceChannel) throws ValidationException {
    applicationStatusChange(waterConnectionDetails, workFlowAction, mode, sourceChannel);
    if (WaterTaxConstants.APPLICATION_STATUS_CLOSERDIGSIGNPENDING.equals(waterConnectionDetails.getStatus().getCode()) && waterConnectionDetails.getCloseConnectionType() != null && workFlowAction.equals(WaterTaxConstants.APPROVEWORKFLOWACTION)) {
        waterConnectionDetails.setApplicationType(applicationTypeService.findByCode(WaterTaxConstants.CLOSINGCONNECTION));
        waterConnectionDetails.setCloseApprovalDate(new Date());
    }
    if (WaterTaxConstants.APPLICATION_STATUS_RECONNDIGSIGNPENDING.equals(waterConnectionDetails.getStatus().getCode()) && waterConnectionDetails.getCloseConnectionType().equals(WaterTaxConstants.TEMPERARYCLOSECODE) && waterConnectionDetails.getReConnectionReason() != null && workFlowAction.equals(WaterTaxConstants.APPROVEWORKFLOWACTION)) {
        waterConnectionDetails.setApplicationType(applicationTypeService.findByCode(WaterTaxConstants.RECONNECTIONCONNECTION));
        waterConnectionDetails.setConnectionStatus(ConnectionStatus.ACTIVE);
        waterConnectionDetails.setReconnectionApprovalDate(new Date());
        if (ConnectionType.NON_METERED.equals(waterConnectionDetails.getConnectionType())) {
            Installment nonMeterReconnInstallment = null;
            Boolean reconnInSameInstallment = null;
            if (checkTwoDatesAreInSameInstallment(waterConnectionDetails)) {
                final Installment nonMeterCurrentInstallment = connectionDemandService.getCurrentInstallment(WaterTaxConstants.WATER_RATES_NONMETERED_PTMODULE, null, waterConnectionDetails.getReconnectionApprovalDate());
                final Calendar cal = Calendar.getInstance();
                cal.setTime(nonMeterCurrentInstallment.getToDate());
                cal.add(Calendar.DATE, 1);
                final Date newDateForNextInstall = cal.getTime();
                nonMeterReconnInstallment = connectionDemandService.getCurrentInstallment(WaterTaxConstants.WATER_RATES_NONMETERED_PTMODULE, null, newDateForNextInstall);
                reconnInSameInstallment = Boolean.TRUE;
            } else {
                nonMeterReconnInstallment = connectionDemandService.getCurrentInstallment(WaterTaxConstants.WATER_RATES_NONMETERED_PTMODULE, null, waterConnectionDetails.getReconnectionApprovalDate());
                reconnInSameInstallment = Boolean.FALSE;
            }
            connectionDemandService.updateDemandForNonmeteredConnection(waterConnectionDetails, nonMeterReconnInstallment, reconnInSameInstallment);
        }
        updateIndexes(waterConnectionDetails, sourceChannel);
    }
    if (ConnectionType.NON_METERED.equals(waterConnectionDetails.getConnectionType()) && WaterTaxConstants.APPLICATION_STATUS_SANCTIONED.equalsIgnoreCase(waterConnectionDetails.getStatus().getCode())) {
        connectionDemandService.updateDemandForNonmeteredConnection(waterConnectionDetails, null, null);
        updateIndexes(waterConnectionDetails, sourceChannel);
    }
    // document
    if (workFlowAction != null && workFlowAction.equalsIgnoreCase(WaterTaxConstants.SIGNWORKFLOWACTION) && reportOutput != null) {
        final String fileName = WaterTaxConstants.SIGNED_DOCUMENT_PREFIX + waterConnectionDetails.getWorkOrderNumber() + ".pdf";
        final InputStream fileStream = new ByteArrayInputStream(reportOutput.getReportOutputData());
        final FileStoreMapper fileStore = fileStoreService.store(fileStream, fileName, "application/pdf", WaterTaxConstants.FILESTORE_MODULECODE);
        waterConnectionDetails.setFileStore(fileStore);
    }
    WaterConnectionDetails updatedWaterConnectionDetails = waterConnectionDetailsRepository.save(waterConnectionDetails);
    final ApplicationWorkflowCustomDefaultImpl applicationWorkflowCustomDefaultImpl = getInitialisedWorkFlowBean();
    if (waterConnectionDetails.getCloseConnectionType() != null)
        additionalRule = WaterTaxConstants.WORKFLOW_CLOSUREADDITIONALRULE;
    if (waterConnectionDetails.getReConnectionReason() != null)
        additionalRule = WaterTaxConstants.RECONNECTIONCONNECTION;
    applicationWorkflowCustomDefaultImpl.createCommonWorkflowTransition(updatedWaterConnectionDetails, approvalPosition, approvalComent, additionalRule, workFlowAction);
    // cancelled
    if (waterConnectionDetails.getCloseConnectionType() != null && waterConnectionDetails.getReConnectionReason() == null && waterConnectionDetails.getStatus().getCode().equals(WaterTaxConstants.APPLICATION_STATUS_CANCELLED) && waterConnectionDetails.getConnectionStatus().equals(ConnectionStatus.INACTIVE)) {
        waterConnectionDetails.setStatus(waterTaxUtils.getStatusByCodeAndModuleType(WaterTaxConstants.APPLICATION_STATUS_SANCTIONED, WaterTaxConstants.MODULETYPE));
        waterConnectionDetails.setConnectionStatus(ConnectionStatus.ACTIVE);
        waterConnectionDetails.setCloseConnectionType(null);
        waterConnectionDetails.setCloseconnectionreason(null);
        waterConnectionDetails.setApplicationType(applicationTypeService.findByCode(waterConnectionDetails.getPreviousApplicationType()));
        updateIndexes(waterConnectionDetails, sourceChannel);
        updatedWaterConnectionDetails = waterConnectionDetailsRepository.save(waterConnectionDetails);
    }
    // back to CLoserSanctioned Status if Reconnection is Rejected 2 times
    if (waterConnectionDetails.getReConnectionReason() != null && waterConnectionDetails.getCloseConnectionType() == WaterTaxConstants.TEMPERARYCLOSECODE && waterConnectionDetails.getStatus().getCode().equals(WaterTaxConstants.APPLICATION_STATUS_CANCELLED) && waterConnectionDetails.getConnectionStatus().equals(ConnectionStatus.INACTIVE)) {
        waterConnectionDetails.setStatus(waterTaxUtils.getStatusByCodeAndModuleType(WaterTaxConstants.APPLICATION_STATUS_CLOSERSANCTIONED, WaterTaxConstants.MODULETYPE));
        waterConnectionDetails.setConnectionStatus(ConnectionStatus.CLOSED);
        waterConnectionDetails.setReConnectionReason(null);
        waterConnectionDetails.setApplicationType(applicationTypeService.findByCode(WaterTaxConstants.CLOSINGCONNECTION));
        updateIndexes(waterConnectionDetails, sourceChannel);
        updatedWaterConnectionDetails = waterConnectionDetailsRepository.save(waterConnectionDetails);
    }
    if (!workFlowAction.equalsIgnoreCase(WFLOW_ACTION_STEP_REJECT))
        waterConnectionSmsAndEmailService.sendSmsAndEmail(waterConnectionDetails, workFlowAction);
    updateIndexes(waterConnectionDetails, sourceChannel);
    return updatedWaterConnectionDetails;
}
Example 37
Project: gwt-bean-validators-master  File: GwtSpecificValidatorCreator.java View source code
@Override
protected void compose(final ClassSourceFileComposerFactory composerFactory) {
    this.addImports(composerFactory, Annotation.class, ConstraintViolation.class, GWT.class, ValidationGroupsMetadata.class, Group.class, GroupChain.class, PathImpl.class, Node.class, GroupChainGenerator.class, GwtBeanDescriptor.class, BeanMetadata.class, GwtValidationContext.class, ArrayList.class, HashSet.class, IllegalArgumentException.class, Set.class, Collection.class, Iterator.class, List.class, ValidationException.class);
    composerFactory.setSuperclass(AbstractGwtSpecificValidator.class.getCanonicalName() + "<" + this.beanType.getQualifiedSourceName() + ">");
    composerFactory.addImplementedInterface(this.validatorType.getName());
}
Example 38
Project: java-sproc-wrapper-master  File: SimpleConstraintDescriptor.java View source code
private Map<String, Object> buildAnnotationParameterMap(final Annotation annotation) {
    final Method[] declaredMethods = annotation.annotationType().getDeclaredMethods();
    Map<String, Object> parameters = new HashMap<String, Object>(declaredMethods.length);
    for (Method m : declaredMethods) {
        try {
            parameters.put(m.getName(), m.invoke(annotation));
        } catch (IllegalAccessException e) {
            throw new ValidationException("Unable to read annotation attributes: " + annotation.getClass(), e);
        } catch (InvocationTargetException e) {
            throw new ValidationException("Unable to read annotation attributes: " + annotation.getClass(), e);
        }
    }
    return Collections.unmodifiableMap(parameters);
}
Example 39
Project: jaxrs-beanvalidation-javaee7-master  File: ValidationExceptionMapper.java View source code
@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 40
Project: jersey-master  File: ValidateOnExecutionHandler.java View source code
/**
     * Process {@link ValidateOnExecution} annotation for given method on a class hierarchy.
     *
     * @param method method to be examined.
     * @param hierarchy class hierarchy to be examined.
     * @param checkOverrides flag whether a overriding/implementing methods should also be checked.
     * @return {@code true} if the method should be validated, {@code false} if not, {@code null} if the flag cannot be
     * determined (no annotation present).
     */
private Boolean processAnnotation(final Method method, final Deque<Class<?>> hierarchy, final boolean checkOverrides) {
    // Overridden methods.
    while (!hierarchy.isEmpty()) {
        final Class<?> overriddenClass = hierarchy.removeFirst();
        final Method overriddenMethod = AccessController.doPrivileged(ReflectionHelper.findMethodOnClassPA(overriddenClass, method));
        if (overriddenMethod != null) {
            // Method.
            Set<ExecutableType> executableTypes = getExecutableTypes(overriddenMethod);
            if (!executableTypes.isEmpty()) {
                // If an overriding/implementing method is annotated with @ValidateOnExecution, throw an exception.
                if (checkOverrides && processAnnotation(method, hierarchy, false) != null) {
                    final String methodName = method.getDeclaringClass().getName() + "#" + method.getName();
                    throw new ValidationException(LocalizationMessages.OVERRIDE_CHECK_ERROR(methodName));
                }
                return validateMethod(overriddenMethod, true, executableTypes);
            }
            // Class.
            executableTypes = getExecutableTypes(overriddenClass);
            if (!executableTypes.isEmpty() && // ExecutableType#IMPLICIT on class itself does nothing.
            !(executableTypes.size() == 1 && executableTypes.contains(ExecutableType.IMPLICIT))) {
                return validateMethod(overriddenMethod, false, executableTypes);
            }
        }
    }
    return null;
}
Example 41
Project: mojarra-master  File: BeanValidator.java View source code
private static ValidatorFactory getValidatorFactory(FacesContext context) {
    ValidatorFactory validatorFactory = null;
    Object cachedObject = context.getExternalContext().getApplicationMap().get(VALIDATOR_FACTORY_KEY);
    if (cachedObject instanceof ValidatorFactory) {
        validatorFactory = (ValidatorFactory) cachedObject;
    } else {
        try {
            validatorFactory = Validation.buildDefaultValidatorFactory();
        } catch (ValidationException e) {
            throw new FacesException("Could not build a default Bean Validator factory", e);
        }
        context.getExternalContext().getApplicationMap().put(VALIDATOR_FACTORY_KEY, validatorFactory);
    }
    return validatorFactory;
}
Example 42
Project: openjpa-master  File: ValidatorImpl.java View source code
/**
     * Validates a given instance
     * 
     * @param <T> The instance to validate
     * @param arg0 The class, of type T to validate
     * @param event The event id
     * @return ValidationException if the validator produces one or more
     *         constraint violations.
     */
@Override
public <T> ValidationException validate(T arg0, int event) {
    if (!isValidating(event))
        return null;
    Set<ConstraintViolation<T>> violations = AccessController.doPrivileged(J2DoPrivHelper.validateAction(_validator, arg0, getValidationGroup(event)));
    if (violations != null && violations.size() > 0) {
        return new ValidationException(new ConstraintViolationException(// A validation constraint failure occurred for class "{0}".
        _loc.get("validate-failed", arg0.getClass().getName()).getMessage(), (Set) violations), true);
    }
    return null;
}
Example 43
Project: restjplat-master  File: DefaultRestErrorResolver.java View source code
/**
	 * 将spring中的http状�和异常互相对应 �考 spring的defaultExceptionHandler实现类似
	 * 
	 * @return
	 */
private final Map<String, String> createDefaultExceptionMappingDefinitions() {
    Map<String, String> m = new LinkedHashMap<String, String>();
    // 400
    applyDef(m, HttpMessageNotReadableException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, MissingServletRequestParameterException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, TypeMismatchException.class, HttpStatus.BAD_REQUEST);
    applyDef(m, "javax.validation.ValidationException", HttpStatus.BAD_REQUEST);
    // 404
    applyDef(m, NoSuchRequestHandlingMethodException.class, HttpStatus.NOT_FOUND);
    applyDef(m, "org.hibernate.ObjectNotFoundException", HttpStatus.NOT_FOUND);
    // 405
    applyDef(m, HttpRequestMethodNotSupportedException.class, HttpStatus.METHOD_NOT_ALLOWED);
    // 406
    applyDef(m, HttpMediaTypeNotAcceptableException.class, HttpStatus.NOT_ACCEPTABLE);
    // 409
    applyDef(m, "org.springframework.dao.DataIntegrityViolationException", HttpStatus.CONFLICT);
    // 415
    applyDef(m, HttpMediaTypeNotSupportedException.class, HttpStatus.UNSUPPORTED_MEDIA_TYPE);
    return m;
}
Example 44
Project: spring-webmvc-dynamiclogging-master  File: ErrorController.java View source code
@SuppressWarnings("deprecation")
@RequestMapping("validationFailed")
@ResponseBody
public ResponseEntity<Map> handleValidationFailure(HttpServletRequest request) {
    ValidationException ex = (ValidationException) request.getAttribute("javax.servlet.error.exception");
    log.debug("Handling", ex);
    /*
        The 1.0 javax.validation API is somewhat of a mess.  Here we get validation exceptions.
        However there are no methods that grant access to what validation failed.
        The validation mechanism uses a pluggable provider approach with no ability to access the provider.
        Hard code support for Hibernate validator 4.3.1.  But be ready for this support to "evolve" in the next release.
        As you can see the MCVE is already deprecated and won't be there in the next release (5.0).

        NOTE: 5.0 is out and the code migration is easy, however it isn't backwards compatible and the 3.2.x series
        of the spring framework has "hibernate validator" support that is statically linked to HV 4.x and breaks
        on the 5.x series of HV.
         */
    MethodConstraintViolationException mcve = (MethodConstraintViolationException) ex;
    StringBuilder errorMessage = new StringBuilder();
    errorMessage.append("Validation errors: ");
    for (MethodConstraintViolation violation : mcve.getConstraintViolations()) {
        errorMessage.append("[");
        errorMessage.append(violation.getMessage());
        errorMessage.append("]");
    }
    Map<String, String> payload = new HashMap<String, String>();
    payload.put("error", "Validation");
    payload.put("errorDetails", errorMessage.toString());
    return new ResponseEntity<Map>(payload, HttpStatus.BAD_REQUEST);
}
Example 45
Project: tatami-master  File: UserRepositoryTest.java View source code
@Test(expected = ValidationException.class)
public void shouldNotCreateAUserBecauseLoginNull() {
    String login = null;
    String firstName = "New";
    String lastName = "User";
    String avatar = "newAvatar";
    User user = new User();
    user.setLogin(login);
    user.setFirstName(firstName);
    user.setLastName(lastName);
    user.setAvatar(avatar);
    userRepository.createUser(user);
}
Example 46
Project: arquillian-safari-master  File: MemberService.java View source code
/**
     * Creates a new member from the values provided.  Performs validation, and will return a JAX-RS response with either
     * 200 ok, or with a map of fields, and related errors.
     */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createMember(Member member) {
    Response.ResponseBuilder builder = null;
    try {
        //Validates member using bean validation
        validateMember(member);
        registration.register(member);
        //Create an "ok" response
        builder = Response.ok();
    } catch (ConstraintViolationException ce) {
        builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("email", "Email taken");
        builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("error", e.getMessage());
        builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }
    return builder.build();
}
Example 47
Project: jboss-as-quickstart-master  File: MemberResourceRESTService.java View source code
/**
     * Creates a new member from the values provided. Performs validation, and will return a JAX-RS response with either 200 ok,
     * or with a map of fields, and related errors.
     */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createMember(Member member) {
    Response.ResponseBuilder builder = null;
    try {
        // Validates member using bean validation
        validateMember(member);
        registration.register(member);
        // Create an "ok" response
        builder = Response.ok();
    } catch (ConstraintViolationException ce) {
        builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("email", "Email taken");
        builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("error", e.getMessage());
        builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }
    return builder.build();
}
Example 48
Project: jdf-quickstarts-master  File: MemberResourceRESTService.java View source code
/**
     * Creates a new member from the values provided. Performs validation, and will return a JAX-RS response with either 200 ok,
     * or with a map of fields, and related errors.
     */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createMember(Member member) {
    Response.ResponseBuilder builder = null;
    try {
        // Validates member using bean validation
        validateMember(member);
        registration.register(member);
        // Create an "ok" response
        builder = Response.ok();
    } catch (ConstraintViolationException ce) {
        builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("email", "Email taken");
        builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("error", e.getMessage());
        builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }
    return builder.build();
}
Example 49
Project: KitchenSink-master  File: MemberResourceRESTService.java View source code
/**
     * Creates a new member from the values provided. Performs validation, and will return a JAX-RS response with either 200 ok,
     * or with a map of fields, and related errors.
     */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createMember(Member member) {
    Response.ResponseBuilder builder = null;
    try {
        // Validates member using bean validation
        validateMember(member);
        registration.register(member);
        // Create an "ok" response
        builder = Response.ok();
    } catch (ConstraintViolationException ce) {
        builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
        Map<String, String> responseObj = new HashMap<>();
        responseObj.put("email", "Email taken");
        builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
        Map<String, String> responseObj = new HashMap<>();
        responseObj.put("error", e.getMessage());
        builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }
    return builder.build();
}
Example 50
Project: ogm-kitchensink-master  File: MemberResourceRESTService.java View source code
/**
	 * Creates a new member from the values provided.  Performs validation, and will return a JAX-RS response with either
	 * 200 ok, or with a map of fields, and related errors.
	 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createMember(Member member) {
    Response.ResponseBuilder builder = null;
    try {
        //Validates member using bean validation
        validateMember(member);
        registration.register(member);
        //Create an "ok" response
        builder = Response.ok();
    } catch (ConstraintViolationException ce) {
        builder = createViolationResponse(ce.getConstraintViolations());
    } catch (ValidationException e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("email", "Email taken");
        builder = Response.status(Response.Status.CONFLICT).entity(responseObj);
    } catch (Exception e) {
        Map<String, String> responseObj = new HashMap<String, String>();
        responseObj.put("error", e.getMessage());
        builder = Response.status(Response.Status.BAD_REQUEST).entity(responseObj);
    }
    return builder.build();
}
Example 51
Project: Repository-master  File: CapabilityDescriptorSupport.java View source code
protected void validateUnique(@Nullable final CapabilityIdentity id, final Map<String, String> properties) {
    checkNotNull(properties);
    checkNotNull(capabilityRegistry);
    CapabilityReferenceFilter filter = capabilities().withType(type());
    Set<String> uniqueProperties = uniqueProperties();
    if (uniqueProperties != null) {
        for (String key : uniqueProperties) {
            filter.withProperty(key, properties.get(key));
        }
    }
    log.trace("Validating that unique capability of type {} and properties {}", type(), filter.getProperties());
    Collection<? extends CapabilityReference> references = capabilityRegistry.get().get(filter);
    if (!references.isEmpty() && !Objects.equals(id, references.iterator().next().context().id())) {
        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 52
Project: syncope-master  File: AbstractAnySearchDAO.java View source code
protected Pair<PlainSchema, PlainAttrValue> check(final AttributeCond cond, final AnyTypeKind kind) {
    AnyUtils attrUtils = anyUtilsFactory.getInstance(kind);
    PlainSchema schema = schemaDAO.find(cond.getSchema());
    if (schema == null) {
        LOG.warn("Ignoring invalid schema '{}'", cond.getSchema());
        throw new IllegalArgumentException();
    }
    PlainAttrValue attrValue = attrUtils.newPlainAttrValue();
    try {
        if (cond.getType() != AttributeCond.Type.LIKE && cond.getType() != AttributeCond.Type.ILIKE && cond.getType() != AttributeCond.Type.ISNULL && cond.getType() != AttributeCond.Type.ISNOTNULL) {
            schema.getValidator().validate(cond.getExpression(), attrValue);
        }
    } catch (ValidationException e) {
        LOG.error("Could not validate expression '" + cond.getExpression() + "'", e);
        throw new IllegalArgumentException();
    }
    return Pair.of(schema, attrValue);
}
Example 53
Project: tapestry5-cli-master  File: CLIParserImpl.java View source code
// Maybe some useful message here as well
private void printAndReThrow(Throwable t) throws ParseException, ValidationException {
    Options options = setupParsing();
    if (t instanceof ParseException) {
        // TODO Add some more info on error
        formatter.printHelp(commandName, options);
        throw (ParseException) t;
    } else if (t instanceof ValidationException) {
        // TODO Add some more info on error
        formatter.printHelp(commandName, options);
        throw (ValidationException) t;
    } else {
        // TODO Add some more info on error
        formatter.printHelp(commandName, options);
        // By default we wrap everything inside a ValidationException
        throw new ValidationException(t);
    }
}
Example 54
Project: tomee-master  File: Assembler.java View source code
private AppContext createApplication(final AppInfo appInfo, ClassLoader classLoader, final boolean start) throws OpenEJBException, IOException, NamingException {
    try {
        try {
            mergeServices(appInfo);
        } catch (final URISyntaxException e) {
            logger.info("Can't merge resources.xml services and appInfo.properties");
        }
        // The path is used in the UrlCache, command line deployer, JNDI name templates, tomcat integration and a few other places
        if (appInfo.appId == null) {
            throw new IllegalArgumentException("AppInfo.appId cannot be null");
        }
        if (appInfo.path == null) {
            appInfo.path = appInfo.appId;
        }
        Extensions.addExtensions(classLoader, appInfo.eventClassesNeedingAppClassloader);
        logger.info("createApplication.start", appInfo.path);
        final Context containerSystemContext = containerSystem.getJNDIContext();
        // To start out, ensure we don't already have any beans deployed with duplicate IDs.  This
        // is a conflict we can't handle.
        final List<String> used = getDuplicates(appInfo);
        if (used.size() > 0) {
            String message = logger.error("createApplication.appFailedDuplicateIds", appInfo.path);
            for (final String id : used) {
                logger.error("createApplication.deploymentIdInUse", id);
                message += "\n    " + id;
            }
            throw new DuplicateDeploymentIdException(message);
        }
        //Construct the global and app jndi contexts for this app
        final InjectionBuilder injectionBuilder = new InjectionBuilder(classLoader);
        final Set<Injection> injections = new HashSet<Injection>();
        injections.addAll(injectionBuilder.buildInjections(appInfo.globalJndiEnc));
        injections.addAll(injectionBuilder.buildInjections(appInfo.appJndiEnc));
        final JndiEncBuilder globalBuilder = new JndiEncBuilder(appInfo.globalJndiEnc, injections, appInfo.appId, null, GLOBAL_UNIQUE_ID, classLoader, appInfo.properties);
        final Map<String, Object> globalBindings = globalBuilder.buildBindings(JndiEncBuilder.JndiScope.global);
        final Context globalJndiContext = globalBuilder.build(globalBindings);
        final JndiEncBuilder appBuilder = new JndiEncBuilder(appInfo.appJndiEnc, injections, appInfo.appId, null, appInfo.appId, classLoader, appInfo.properties);
        final Map<String, Object> appBindings = appBuilder.buildBindings(JndiEncBuilder.JndiScope.app);
        final Context appJndiContext = appBuilder.build(appBindings);
        final boolean cdiActive = shouldStartCdi(appInfo);
        try {
            // Generate the cmp2/cmp1 concrete subclasses
            final CmpJarBuilder cmpJarBuilder = new CmpJarBuilder(appInfo, classLoader);
            final File generatedJar = cmpJarBuilder.getJarFile();
            if (generatedJar != null) {
                classLoader = ClassLoaderUtil.createClassLoader(appInfo.path, new URL[] { generatedJar.toURI().toURL() }, classLoader);
            }
            final AppContext appContext = new AppContext(appInfo.appId, SystemInstance.get(), classLoader, globalJndiContext, appJndiContext, appInfo.standaloneModule);
            appContext.getProperties().putAll(appInfo.properties);
            appContext.getInjections().addAll(injections);
            appContext.getBindings().putAll(globalBindings);
            appContext.getBindings().putAll(appBindings);
            containerSystem.addAppContext(appContext);
            appContext.set(AsynchronousPool.class, AsynchronousPool.create(appContext));
            final Map<String, LazyValidatorFactory> lazyValidatorFactories = new HashMap<String, LazyValidatorFactory>();
            final Map<String, LazyValidator> lazyValidators = new HashMap<String, LazyValidator>();
            final boolean isGeronimo = SystemInstance.get().hasProperty("openejb.geronimo");
            // try to not create N times the same validator for a single app
            final Map<ComparableValidationConfig, ValidatorFactory> validatorFactoriesByConfig = new HashMap<ComparableValidationConfig, ValidatorFactory>();
            if (!isGeronimo) {
                // Bean Validation
                // ValidatorFactory needs to be put in the map sent to the entity manager factory
                // so it has to be constructed before
                final List<CommonInfoObject> vfs = listCommonInfoObjectsForAppInfo(appInfo);
                final Map<String, ValidatorFactory> validatorFactories = new HashMap<String, ValidatorFactory>();
                for (final CommonInfoObject info : vfs) {
                    if (info.validationInfo == null) {
                        continue;
                    }
                    final ComparableValidationConfig conf = new ComparableValidationConfig(info.validationInfo.providerClassName, info.validationInfo.messageInterpolatorClass, info.validationInfo.traversableResolverClass, info.validationInfo.constraintFactoryClass, info.validationInfo.parameterNameProviderClass, info.validationInfo.version, info.validationInfo.propertyTypes, info.validationInfo.constraintMappings, info.validationInfo.executableValidationEnabled, info.validationInfo.validatedTypes);
                    ValidatorFactory factory = validatorFactoriesByConfig.get(conf);
                    if (factory == null) {
                        try {
                            // lazy cause of CDI :(
                            final LazyValidatorFactory handler = new LazyValidatorFactory(classLoader, info.validationInfo);
                            factory = (ValidatorFactory) Proxy.newProxyInstance(appContext.getClassLoader(), VALIDATOR_FACTORY_INTERFACES, handler);
                            lazyValidatorFactories.put(info.uniqueId, handler);
                        } catch (final ValidationException ve) {
                            logger.warning("can't build the validation factory for module " + info.uniqueId, ve);
                            continue;
                        }
                        validatorFactoriesByConfig.put(conf, factory);
                    } else {
                        lazyValidatorFactories.put(info.uniqueId, LazyValidatorFactory.class.cast(Proxy.getInvocationHandler(factory)));
                    }
                    validatorFactories.put(info.uniqueId, factory);
                }
                // validators bindings
                for (final Entry<String, ValidatorFactory> validatorFactory : validatorFactories.entrySet()) {
                    final String id = validatorFactory.getKey();
                    final ValidatorFactory factory = validatorFactory.getValue();
                    try {
                        containerSystemContext.bind(VALIDATOR_FACTORY_NAMING_CONTEXT + id, factory);
                        final Validator validator;
                        try {
                            final LazyValidator lazyValidator = new LazyValidator(factory);
                            validator = (Validator) Proxy.newProxyInstance(appContext.getClassLoader(), VALIDATOR_INTERFACES, lazyValidator);
                            lazyValidators.put(id, lazyValidator);
                        } catch (final Exception e) {
                            logger.error(e.getMessage(), e);
                            continue;
                        }
                        containerSystemContext.bind(VALIDATOR_NAMING_CONTEXT + id, validator);
                    } catch (final NameAlreadyBoundException e) {
                        throw new OpenEJBException("ValidatorFactory already exists for module " + id, e);
                    } catch (final Exception e) {
                        throw new OpenEJBException(e);
                    }
                }
                validatorFactories.clear();
            }
            // JPA - Persistence Units MUST be processed first since they will add ClassFileTransformers
            // to the class loader which must be added before any classes are loaded
            final Map<String, String> units = new HashMap<String, String>();
            final PersistenceBuilder persistenceBuilder = new PersistenceBuilder(persistenceClassLoaderHandler);
            for (final PersistenceUnitInfo info : appInfo.persistenceUnits) {
                final ReloadableEntityManagerFactory factory;
                try {
                    factory = persistenceBuilder.createEntityManagerFactory(info, classLoader, validatorFactoriesByConfig, cdiActive);
                    containerSystem.getJNDIContext().bind(PERSISTENCE_UNIT_NAMING_CONTEXT + info.id, factory);
                    units.put(info.name, PERSISTENCE_UNIT_NAMING_CONTEXT + info.id);
                } catch (final NameAlreadyBoundException e) {
                    throw new OpenEJBException("PersistenceUnit already deployed: " + info.persistenceUnitRootUrl);
                } catch (final Exception e) {
                    throw new OpenEJBException(e);
                }
                factory.register();
            }
            logger.debug("Loaded peristence units: " + units);
            // Connectors
            for (final ConnectorInfo connector : appInfo.connectors) {
                final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(classLoader);
                try {
                    // todo add undeployment code for these
                    if (connector.resourceAdapter != null) {
                        createResource(null, connector.resourceAdapter);
                    }
                    for (final ResourceInfo outbound : connector.outbound) {
                        createResource(null, outbound);
                        // set it after as a marker but not as an attribute (no getOpenejb().setConnector(...))
                        outbound.properties.setProperty("openejb.connector", "true");
                    }
                    for (final MdbContainerInfo inbound : connector.inbound) {
                        createContainer(inbound);
                    }
                    for (final ResourceInfo adminObject : connector.adminObject) {
                        createResource(null, adminObject);
                    }
                } finally {
                    Thread.currentThread().setContextClassLoader(oldClassLoader);
                }
            }
            final List<BeanContext> allDeployments = initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<BeanContext>(), null);
            if ("true".equalsIgnoreCase(SystemInstance.get().getProperty(PROPAGATE_APPLICATION_EXCEPTIONS, appInfo.properties.getProperty(PROPAGATE_APPLICATION_EXCEPTIONS, "false")))) {
                propagateApplicationExceptions(appInfo, classLoader, allDeployments);
            }
            if (cdiActive) {
                new CdiBuilder().build(appInfo, appContext, allDeployments);
                ensureWebBeansContext(appContext);
                appJndiContext.bind("app/BeanManager", appContext.getBeanManager());
                appContext.getBindings().put("app/BeanManager", appContext.getBeanManager());
            } else {
                // ensure we can reuse it in tomcat to remove OWB filters
                appInfo.properties.setProperty("openejb.cdi.activated", "false");
            }
            // now cdi is started we can try to bind real validator factory and validator
            if (!isGeronimo) {
                for (final Entry<String, LazyValidator> lazyValidator : lazyValidators.entrySet()) {
                    final String id = lazyValidator.getKey();
                    final ValidatorFactory factory = lazyValidatorFactories.get(lazyValidator.getKey()).getFactory();
                    try {
                        final String factoryName = VALIDATOR_FACTORY_NAMING_CONTEXT + id;
                        containerSystemContext.unbind(factoryName);
                        containerSystemContext.bind(factoryName, factory);
                        final String validatoryName = VALIDATOR_NAMING_CONTEXT + id;
                        try {
                            // do it after factory cause of TCKs which expects validator to be created later
                            final Validator val = lazyValidator.getValue().getValidator();
                            containerSystemContext.unbind(validatoryName);
                            containerSystemContext.bind(validatoryName, val);
                        } catch (final Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    } catch (final NameAlreadyBoundException e) {
                        throw new OpenEJBException("ValidatorFactory already exists for module " + id, e);
                    } catch (final Exception e) {
                        throw new OpenEJBException(e);
                    }
                }
            }
            startEjbs(start, allDeployments);
            // App Client
            for (final ClientInfo clientInfo : appInfo.clients) {
                // determine the injections
                final List<Injection> clientInjections = injectionBuilder.buildInjections(clientInfo.jndiEnc);
                // build the enc
                final JndiEncBuilder jndiEncBuilder = new JndiEncBuilder(clientInfo.jndiEnc, clientInjections, "Bean", clientInfo.moduleId, null, clientInfo.uniqueId, classLoader, new Properties());
                // then, we can set the client flag
                if (clientInfo.remoteClients.size() > 0 || clientInfo.localClients.size() == 0) {
                    jndiEncBuilder.setClient(true);
                }
                jndiEncBuilder.setUseCrossClassLoaderRef(false);
                final Context context = jndiEncBuilder.build(JndiEncBuilder.JndiScope.comp);
                //                Debug.printContext(context);
                containerSystemContext.bind("openejb/client/" + clientInfo.moduleId, context);
                if (clientInfo.path != null) {
                    context.bind("info/path", clientInfo.path);
                }
                if (clientInfo.mainClass != null) {
                    context.bind("info/mainClass", clientInfo.mainClass);
                }
                if (clientInfo.callbackHandler != null) {
                    context.bind("info/callbackHandler", clientInfo.callbackHandler);
                }
                context.bind("info/injections", clientInjections);
                for (final String clientClassName : clientInfo.remoteClients) {
                    containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId);
                }
                for (final String clientClassName : clientInfo.localClients) {
                    containerSystemContext.bind("openejb/client/" + clientClassName, clientInfo.moduleId);
                    logger.getChildLogger("client").info("createApplication.createLocalClient", clientClassName, clientInfo.moduleId);
                }
            }
            // WebApp
            final SystemInstance systemInstance = SystemInstance.get();
            final WebAppBuilder webAppBuilder = systemInstance.getComponent(WebAppBuilder.class);
            if (webAppBuilder != null) {
                webAppBuilder.deployWebApps(appInfo, classLoader);
            }
            if (start) {
                final EjbResolver globalEjbResolver = systemInstance.getComponent(EjbResolver.class);
                globalEjbResolver.addAll(appInfo.ejbJars);
            }
            // bind all global values on global context
            bindGlobals(appContext.getBindings());
            validateCdiResourceProducers(appContext, appInfo);
            // deploy MBeans
            for (final String mbean : appInfo.mbeans) {
                deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, appInfo.appId);
            }
            for (final EjbJarInfo ejbJarInfo : appInfo.ejbJars) {
                for (final String mbean : ejbJarInfo.mbeans) {
                    deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, ejbJarInfo.moduleName);
                }
            }
            for (final ConnectorInfo connectorInfo : appInfo.connectors) {
                for (final String mbean : connectorInfo.mbeans) {
                    deployMBean(appContext.getWebBeansContext(), classLoader, mbean, appInfo.jmx, appInfo.appId + ".add-lib");
                }
            }
            postConstructResources(appInfo.resourceIds, classLoader, containerSystemContext, appContext);
            deployedApplications.put(appInfo.path, appInfo);
            resumePersistentSchedulers(appContext);
            systemInstance.fireEvent(new AssemblerAfterApplicationCreated(appInfo, appContext, allDeployments));
            logger.info("createApplication.success", appInfo.path);
            return appContext;
        } catch (final ValidationExceptionDeploymentException |  ve) {
            throw ve;
        } catch (final Throwable t) {
            try {
                destroyApplication(appInfo);
            } catch (final Exception e1) {
                logger.debug("createApplication.undeployFailed", e1, appInfo.path);
            }
            throw new OpenEJBException(messages.format("createApplication.failed", appInfo.path), t);
        }
    } finally {
        // cleanup there as well by safety cause we have multiple deployment mode (embedded, tomcat...)
        for (final WebAppInfo webApp : appInfo.webApps) {
            appInfo.properties.remove(webApp);
        }
    }
}
Example 55
Project: xwiki-commons-master  File: DefaultBeanManager.java View source code
/**
     * @return the factory to use to get new JSR 303 validators.
     */
public ValidatorFactory getValidatorFactory() {
    if (this.validatorFactory == null) {
        try {
            this.validatorFactory = Validation.buildDefaultValidatorFactory();
        } catch (ValidationException e) {
            this.logger.debug("Unable to find default JSR 303 provider. There will be no Java bean validation.");
        }
    }
    return this.validatorFactory;
}
Example 56
Project: glassfish-main-master  File: PropertiesBagResource.java View source code
@DELETE
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_OCTET_STREAM })
@Produces({ "text/html;qs=2", MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response delete() {
    try {
        Map<String, Property> existing = getExistingProperties();
        deleteMissingProperties(existing, null);
        String successMessage = localStrings.getLocalString("rest.resource.delete.message", "\"{0}\" deleted successfully.", new Object[] { uriInfo.getAbsolutePath() });
        return ResourceUtil.getResponse(200, successMessage, requestHeaders, uriInfo);
    } catch (Exception ex) {
        if (ex.getCause() instanceof ValidationException) {
            return ResourceUtil.getResponse(400, ex.getMessage(), requestHeaders, uriInfo);
        } else {
            throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}
Example 57
Project: glassfish-master  File: PropertiesBagResource.java View source code
@DELETE
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_OCTET_STREAM })
@Produces({ "text/html", MediaType.APPLICATION_JSON + ";qs=0.5", MediaType.APPLICATION_XML + ";qs=0.5" })
public Response delete() {
    try {
        Map<String, Property> existing = getExistingProperties();
        deleteMissingProperties(existing, null);
        String successMessage = localStrings.getLocalString("rest.resource.delete.message", "\"{0}\" deleted successfully.", new Object[] { uriInfo.getAbsolutePath() });
        return ResourceUtil.getResponse(200, successMessage, requestHeaders, uriInfo);
    } catch (Exception ex) {
        if (ex.getCause() instanceof ValidationException) {
            return ResourceUtil.getResponse(400, ex.getMessage(), requestHeaders, uriInfo);
        } else {
            throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}
Example 58
Project: org.openwms-master  File: AbstractWebController.java View source code
/**
     * All general exceptions thrown by services are caught here and translated into http conform responses with a status code {@code 500
     * Internal Server Error}.
     *
     * @param ex The exception occurred
     * @return A response object wraps the server result
     */
@ExceptionHandler(Exception.class)
public ResponseEntity<Response<Serializable>> handleException(Exception ex) {
    EXC_LOGGER.error("[P] Presentation Layer Exception: " + ex.getLocalizedMessage(), ex);
    if (ex instanceof BehaviorAwareException) {
        BehaviorAwareException bae = (BehaviorAwareException) ex;
        return bae.toResponse(bae.getData());
    }
    if (ex instanceof BusinessRuntimeException) {
        BusinessRuntimeException bre = (BusinessRuntimeException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), bre.getMsgKey(), HttpStatus.INTERNAL_SERVER_ERROR.toString(), new String[] { bre.getMsgKey() }), HttpStatus.INTERNAL_SERVER_ERROR);
    }
    if (ex instanceof HttpBusinessException) {
        HttpBusinessException e = (HttpBusinessException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), e.getHttpStatus().toString()), e.getHttpStatus());
    }
    if (ex instanceof ValidationException) {
        return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.BAD_REQUEST.toString()), HttpStatus.BAD_REQUEST);
    }
    if (ex instanceof TechnicalRuntimeException) {
        TechnicalRuntimeException be = (TechnicalRuntimeException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.BAD_GATEWAY.toString()), HttpStatus.BAD_GATEWAY);
    }
    return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.toString()), HttpStatus.INTERNAL_SERVER_ERROR);
}
Example 59
Project: Payara-master  File: PropertiesBagResource.java View source code
@DELETE
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_OCTET_STREAM })
@Produces({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response delete() {
    try {
        Map<String, Property> existing = getExistingProperties();
        deleteMissingProperties(existing, null);
        String successMessage = localStrings.getLocalString("rest.resource.delete.message", "\"{0}\" deleted successfully.", new Object[] { uriInfo.getAbsolutePath() });
        return ResourceUtil.getResponse(200, successMessage, requestHeaders, uriInfo);
    } catch (Exception ex) {
        if (ex.getCause() instanceof ValidationException) {
            return ResourceUtil.getResponse(400, ex.getMessage(), requestHeaders, uriInfo);
        } else {
            throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
}
Example 60
Project: PressGangCCMSREST-master  File: RESTv1Utilities.java View source code
/**
     * Process an Error/Exception and generate a RESTEasy Exception based on the error/exception produced.
     *
     * @param transaction The transaction to handle rolling back changes.
     * @param ex          The Error/Exception to be processed.
     * @return A RESTEasy Exception containing the details of the Error.
     */
public static Failure processError(final UserTransaction transaction, final Throwable ex) {
    LOG.error("Failed to process REST request", ex);
    // Rollback if a transaction is active
    try {
        if (transaction != null) {
            /*
                    Rolling back only active transactions leads to "Error checking for a transaction" and
                    "Transaction is not active" errors.

                    From http://techblogs.agiledigital.com.au/2013/01/03/jboss-as-7-1-transaction-reaping/

                        Transaction information is stored in the thread context. Each connector can potentially share the
                        same transaction – even across requests. The transaction is removed from the thread context when it
                        is committed or rolled back.

                        When the transaction is reaped, it is marked as rollback only. This changes the status of the
                        transaction to STATUS_ROLLING_BACK – and then shortly thereafter STATUS_ROLLED_BACK. However, the
                        transaction is not actually rolled back or removed from the context of the thread. It will not be
                        removed until utx.commit() or utx.rollback() is called.

                        The base servlet would never attempt to commit or rollback the transaction because:

                        (utx.getStatus() == Status.STATUS_ACTIVE)

                        will always be false after the transaction reaper has caused the status to change to ROLLED_BACK.
                        Consequently, the transaction was never removed from the thread context and an attempt would be made
                        by TxConnectionManagerImpl (seen in the stack trace above) to re-use it. Since it had been marked
                        ROLLED_BACK it could not be re-used and an exception was thrown.
                 */
            final int status = transaction.getStatus();
            if (status != Status.STATUS_NO_TRANSACTION) {
                transaction.rollback();
            }
        }
    } catch (Throwable e) {
        return new InternalServerErrorException(e);
    }
    // We need to do some unwrapping of exception first
    Throwable cause = ex;
    while (cause != null) {
        if (cause == cause.getCause()) {
            // sometimes this can be an circular reference
            break;
        } else if (cause instanceof Failure) {
            return (Failure) cause;
        } else if (cause instanceof EntityNotFoundException) {
            return new NotFoundException(cause);
        } else if (cause instanceof ValidationException || cause instanceof CustomConstraintViolationException || cause instanceof org.hibernate.exception.ConstraintViolationException || cause instanceof RollbackException) {
            break;
        } else if (cause instanceof PersistenceException) {
            if (cause.getCause() != null && cause.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
                cause = cause.getCause();
            } else {
                break;
            }
        } else if (cause instanceof ProviderException) {
            if (cause != null && (cause instanceof ValidationException || cause instanceof PersistenceException || cause instanceof CustomConstraintViolationException)) {
                cause = cause.getCause();
            } else {
                break;
            }
        } else if (cause instanceof BatchUpdateException) {
            cause = ((SQLException) cause).getNextException();
        } else {
            cause = cause.getCause();
        }
    }
    // This is a Persistence exception with information
    if (cause instanceof ConstraintViolationException) {
        final ConstraintViolationException e = (ConstraintViolationException) cause;
        final StringBuilder stringBuilder = new StringBuilder();
        // Construct a "readable" message outlining the validation errors
        for (ConstraintViolation invalidValue : e.getConstraintViolations()) stringBuilder.append(invalidValue.getMessage()).append("\n");
        return new BadRequestException(stringBuilder.toString(), cause);
    } else if (cause instanceof EntityNotFoundException) {
        return new NotFoundException(cause);
    } else if (cause instanceof org.hibernate.exception.ConstraintViolationException) {
        return new BadRequestException(ExceptionUtilities.getRootCause(cause).getMessage());
    } else if (cause instanceof ValidationException) {
        return new BadRequestException(cause);
    } else if (cause instanceof CustomConstraintViolationException) {
        return new BadRequestException(cause.getMessage());
    } else if (cause instanceof RollbackException) {
        return new BadRequestException("This is most likely caused by the fact that two users are trying to save the same entity at the same time.\n" + "You" + " can try saving again, or reload the entity to see if there were any changes made in the background.", cause);
    } else if (cause instanceof ProviderException) {
        if (cause instanceof org.jboss.pressgang.ccms.provider.exception.NotFoundException) {
            throw new NotFoundException(cause);
        } else if (cause instanceof org.jboss.pressgang.ccms.provider.exception.InternalServerErrorException) {
            throw new InternalServerErrorException(cause);
        } else if (cause instanceof org.jboss.pressgang.ccms.provider.exception.BadRequestException) {
            throw new BadRequestException(cause);
        } else if (cause instanceof org.jboss.pressgang.ccms.provider.exception.UnauthorisedException) {
            throw new UnauthorizedException(cause);
        }
    }
    // If it's not some validation error then it must be an internal error.
    return new InternalServerErrorException(ex);
}
Example 61
Project: Raildelays-master  File: ExcelRow.java View source code
protected void validate(ExcelRow row) {
    Set<ConstraintViolation<ExcelRow>> constraintViolations = validator.validate(row);
    if (!constraintViolations.isEmpty()) {
        StringBuilder builder = new StringBuilder();
        for (ConstraintViolation<? extends ExcelRow> constraintViolation : constraintViolations) {
            builder.append("\nConstraints violations occurred: ");
            builder.append(constraintViolation.getPropertyPath());
            builder.append(' ');
            builder.append(constraintViolation.getMessage());
        }
        throw new ValidationException(builder.toString());
    }
}
Example 62
Project: Achilles-master  File: ArgumentExtractor.java View source code
static javax.validation.Validator initValidator(ConfigMap configurationMap) {
    LOGGER.trace("Extract or init Bean validation");
    Boolean enablePreMutateBeanValidation = configurationMap.getTypedOr(BEAN_VALIDATION_ENABLE, DEFAULT_ENABLE_PRE_MUTATE_BEAN_VALIDATION);
    if (enablePreMutateBeanValidation) {
        try {
            javax.validation.Validator defaultValidator = buildDefaultValidatorFactory().getValidator();
            return configurationMap.getTypedOr(BEAN_VALIDATION_VALIDATOR, defaultValidator);
        } catch (ValidationException vex) {
            throw new AchillesException("Cannot bootstrap ValidatorFactory for Bean Validation (JSR 303)", vex);
        }
    }
    return null;
}
Example 63
Project: deltaspike-solder-master  File: UIInputContainer.java View source code
/**
     * Get the default Bean Validation Validator to read the contraints for a property.
     */
private Validator getDefaultValidator(final FacesContext context) throws FacesException {
    if (!beanValidationPresent) {
        return null;
    }
    ValidatorFactory validatorFactory;
    Object cachedObject = context.getExternalContext().getApplicationMap().get(BeanValidator.VALIDATOR_FACTORY_KEY);
    if (cachedObject instanceof ValidatorFactory) {
        validatorFactory = (ValidatorFactory) cachedObject;
    } else {
        try {
            validatorFactory = Validation.buildDefaultValidatorFactory();
        } catch (ValidationException e) {
            throw new FacesException("Could not build a default Bean Validator factory", e);
        }
        context.getExternalContext().getApplicationMap().put(BeanValidator.VALIDATOR_FACTORY_KEY, validatorFactory);
    }
    return validatorFactory.getValidator();
}
Example 64
Project: faces-master  File: UIInputContainer.java View source code
/**
     * Get the default Bean Validation Validator to read the contraints for a property.
     */
private Validator getDefaultValidator(final FacesContext context) throws FacesException {
    if (!beanValidationPresent) {
        return null;
    }
    ValidatorFactory validatorFactory;
    Object cachedObject = context.getExternalContext().getApplicationMap().get(BeanValidator.VALIDATOR_FACTORY_KEY);
    if (cachedObject instanceof ValidatorFactory) {
        validatorFactory = (ValidatorFactory) cachedObject;
    } else {
        try {
            validatorFactory = Validation.buildDefaultValidatorFactory();
        } catch (ValidationException e) {
            throw new FacesException("Could not build a default Bean Validator factory", e);
        }
        context.getExternalContext().getApplicationMap().put(BeanValidator.VALIDATOR_FACTORY_KEY, validatorFactory);
    }
    return validatorFactory.getValidator();
}
Example 65
Project: occurrence-master  File: FragmentProcessor.java View source code
/**
   * Process a single record into a single Fragment and persist it, generating a new key for it if necessary.
   */
private void processSingleFragment(Set<UniqueIdentifier> uniqueIds, boolean isXml, byte[] data, OccurrenceSchemaType schema, EndpointType protocol, Integer crawlId, String unitQualifier) {
    UUID datasetKey = uniqueIds.iterator().next().getDatasetKey();
    // check for an existing key for these uniqueIds
    KeyLookupResult keyResult = null;
    final TimerContext fetchContext = findTimer.time();
    try {
        keyResult = occurrenceKeyPersister.findKey(uniqueIds);
    } catch (IllegalDataStateException e) {
        failForDataStateException(datasetKey, e);
        return;
    } catch (ServiceUnavailableException e) {
        failForServiceUnavailable(datasetKey, e);
        return;
    } finally {
        fetchContext.stop();
    }
    Fragment fragment;
    OccurrencePersistenceStatus status;
    if (keyResult == null) {
        // this is a new record, prepare to insert a new Fragment
        fragment = new Fragment(datasetKey);
        status = OccurrencePersistenceStatus.NEW;
    } else {
        // this is an existing record - fetch fragment from hbase and see if we need to do an update
        int key = keyResult.getKey();
        int attempts = 0;
        do {
            attempts++;
            LOG.debug("Attempt [{}] to fetch fragment for key [{}]", attempts, key);
            try {
                fragment = fragmentPersister.get(key);
            } catch (ValidationException v) {
                LOG.warn("The fragment for key [{}] is invalid. Ignoring this update.", v);
                updateZookeeper(datasetKey, ZookeeperConnector.CounterName.RAW_OCCURRENCE_PERSISTED_ERROR);
                return;
            } catch (ServiceUnavailableException e) {
                failForServiceUnavailable(datasetKey, e);
                return;
            }
            if (fragment == null) {
                /* this means either
              1) the key we're trying was only just assigned and the owner hasn't written their fragment yet, or
              2) our index is out of sync - it has an index entry pointing to nothing, so delete the index
                entry(ies) and proceed as if this is an insert
             So we retry a few times to get clear of 1), and then act on 2).
             Note however in POR-2807, that if for some reason deletions are not clearing lookups (i.e. POR-995)
             too conservative rates mean the system grinds to a complete halt for large datasets.
          */
                LOG.debug("Fragment for key [{}] was null, sleeping and trying again", key);
                try {
                    Thread.sleep(NULL_FRAG_RETRY_WAIT);
                } catch (InterruptedException e) {
                    LOG.info("Woken up from sleep while waiting to retry fragment get", e);
                }
            }
        } while (fragment == null && attempts <= MAX_NULL_FRAG_RETRIES);
        if (fragment == null) {
            // we're in case 2) from above
            LOG.info("Could not retrieve Fragment with key [{}] even though it exists in lookup table - deleting lookup " + "and inserting Fragment as NEW.", key);
            try {
                occurrenceKeyPersister.deleteKeyByUniqueIdentifiers(uniqueIds);
            } catch (ServiceUnavailableException e) {
                failForServiceUnavailable(datasetKey, e);
                return;
            }
            fragment = new Fragment(datasetKey);
            status = OccurrencePersistenceStatus.NEW;
        } else {
            status = OccurrencePersistenceStatus.UPDATED;
        }
    }
    // check hashes to see if this is an existing and unchanged record
    byte[] newHash = DigestUtils.md5(data);
    if (status == OccurrencePersistenceStatus.UPDATED && Arrays.equals(newHash, fragment.getDataHash())) {
        // the new record and existing record don't differ
        status = OccurrencePersistenceStatus.UNCHANGED;
    } else {
        // this is an UPDATE or NEW, but not UNCHANGED
        fragment.setData(data);
        fragment.setXmlSchema(schema);
        fragment.setProtocol(protocol);
        fragment.setDataHash(newHash);
        fragment.setHarvestedDate(new Date());
        fragment.setCrawlId(crawlId);
        fragment.setUnitQualifier(unitQualifier);
        if (isXml) {
            fragment.setFragmentType(Fragment.FragmentType.XML);
        } else {
            fragment.setFragmentType(Fragment.FragmentType.JSON);
        }
    }
    // update these in every case (including UNCHANGED)
    fragment.setHarvestedDate(new Date());
    fragment.setCrawlId(crawlId);
    if (LOG.isDebugEnabled()) {
        if (status != OccurrencePersistenceStatus.NEW) {
            StringBuilder uniques = new StringBuilder(64);
            for (UniqueIdentifier uniqueIdentifier : uniqueIds) {
                if (uniques.length() > 0) {
                    uniques.append(" ||| ");
                }
                uniques.append(uniqueIdentifier.getUniqueString());
            }
            LOG.debug("Persisting fragment of status [{}] for key [{}] uniqueIds [{}]", status.toString(), fragment.getKey() == null ? "null" : fragment.getKey().toString(), uniques.toString());
        }
    }
    final TimerContext context = persistenceTimer.time();
    try {
        if (status == OccurrencePersistenceStatus.NEW) {
            FragmentCreationResult creationResult = fragmentPersister.insert(fragment, uniqueIds);
            if (!creationResult.isKeyCreated()) {
                // we lost a race to generate the key for these uniqueIds, and now this is an update
                status = OccurrencePersistenceStatus.UPDATED;
                LOG.info("Fragment creation did not generate new key - lost race and now using existing [{}] as status [UPDATE]", fragment.getKey());
            }
        } else {
            fragmentPersister.update(fragment);
        }
    } catch (ServiceUnavailableException e) {
        failForServiceUnavailable(datasetKey, e);
        return;
    } catch (IllegalDataStateException e) {
        failForDataStateException(datasetKey, e);
    } finally {
        context.stop();
    }
    ZookeeperConnector.CounterName counterToUpdate = null;
    switch(status) {
        case UNCHANGED:
            counterToUpdate = ZookeeperConnector.CounterName.RAW_OCCURRENCE_PERSISTED_UNCHANGED;
            break;
        case NEW:
            counterToUpdate = ZookeeperConnector.CounterName.RAW_OCCURRENCE_PERSISTED_NEW;
            break;
        case UPDATED:
            counterToUpdate = ZookeeperConnector.CounterName.RAW_OCCURRENCE_PERSISTED_UPDATED;
            break;
    }
    updateZookeeper(fragment.getDatasetKey(), counterToUpdate);
    Message fragMsg = new FragmentPersistedMessage(fragment.getDatasetKey(), crawlId, status, fragment.getKey());
    final TimerContext msgContext = msgTimer.time();
    try {
        LOG.debug("Sending FragmentPersistedMessage for key [{}]", fragment.getKey());
        messagePublisher.send(fragMsg);
        msgsSent.mark();
    } catch (IOException e) {
        LOG.warn("Could not send FragmentPersistedMessage for successful persist of status [{}]", status, e);
    } finally {
        msgContext.stop();
    }
    fragmentsProcessed.mark();
}
Example 66
Project: randi2-master  File: TrialServiceImpl.java View source code
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void addResponse(Trial trial, TrialSubject subject) {
    if (subject == null) {
        throw new IllegalArgumentException("Trial subject can't be NULL");
    } else if (subject.getId() == AbstractDomainObject.NOT_YET_SAVED_ID) {
        throw new IllegalArgumentException("Trial subject must be a persistent object");
    }
    TrialSubject tmp = (TrialSubject) entityManager.createQuery("from TrialSubject t where t.id = ?").setParameter(1, subject.getId()).getSingleResult();
    if (tmp.getResponseProperty() != null) {
        throw new ValidationException("Response for trial subject with id: " + subject.getId() + " has been already saved");
    }
    trial = entityManager.find(Trial.class, trial.getId());
    logger.debug("user: " + SecurityContextHolder.getContext().getAuthentication().getName() + " added response in trial " + trial.getName());
    if (trial.getRandomizationConfiguration() instanceof ResponseAdaptiveRConfig) {
        ResponseAdaptiveRandomization algorithm = (ResponseAdaptiveRandomization) trial.getRandomizationConfiguration().getAlgorithm();
        algorithm.addResponse(subject);
        entityManager.persist(subject.getResponseProperty());
        entityManager.merge(subject);
    }
}
Example 67
Project: BatooJPA-master  File: EntityManagerFactoryImpl.java View source code
private ValidatorFactory createValidationFactory() {
    try {
        return Validation.buildDefaultValidatorFactory();
    } catch (final ValidationException e) {
        final ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(this.classloader);
        try {
            return Validation.buildDefaultValidatorFactory();
        } finally {
            Thread.currentThread().setContextClassLoader(oldClassLoader);
        }
    }
}
Example 68
Project: eclipselink.runtime-master  File: JAXBBeanValidator.java View source code
/**
     * PUBLIC:
     *
     * Initializes validator if not already initialized.
     * If mode is BeanValidationMode.AUTO, then after an unsuccessful try to
     * initialize a Validator, property {@code stopSearchingForValidator} will be set to true.
     *
     * NOTE: Property {@code stopSearchingForValidator} can be reset only by triggering
     * {@link #changeInternalState}.
     *
     * @return {@code true} if validator initialization succeeded, otherwise {@code false}.
     * @throws BeanValidationException
     *              throws {@link org.eclipse.persistence.exceptions.BeanValidationException#PROVIDER_NOT_FOUND}
     */
private boolean initValidator() throws BeanValidationException {
    if (validator == null && !stopSearchingForValidator) {
        try {
            ValidatorFactory factory = getValidatorFactory();
            validator = factory.getValidator();
            printValidatorInfo();
        } catch (ValidationException ve) {
            if (beanValidationMode == BeanValidationMode.CALLBACK) {
                beanValidationMode = BeanValidationMode.AUTO;
                throw BeanValidationException.providerNotFound(prefix, ve);
            } else {
                stopSearchingForValidator = true;
            }
        }
    }
    return validator != null;
}
Example 69
Project: jboss-jsf-api_spec-master  File: BeanValidator.java View source code
/**
     * <p class="changed_added_2_0">Verify that the value is valid
     * according to the Bean Validation constraints.</p>
     *
     * <div class="changed_added_2_0">

     * <p>Obtain a {@link ValidatorFactory} instance by calling {@link
     * javax.validation.Validation#buildDefaultValidatorFactory}.</p>

     * <p>Let <em>validationGroupsArray</em> be a <code>Class []</code>
     * representing validator groups set on the component by the tag
     * handler for this validator.  The first search component
     * terminates the search for the validation groups value.  If no
     * such value is found use the class name of {@link
     * javax.validation.groups.Default} as the value of the validation
     * groups.</p>

     * <p>Let <em>valueExpression</em> be the return from calling {@link
     * UIComponent#getValueExpression} on the argument
     * <em>component</em>, passing the literal string
     * “value” (without the quotes) as an argument.  If this
     * application is running in an environment with a Unified EL
     * Implementation for Java EE6 or later, obtain the
     * <code>ValueReference</code> from <em>valueExpression</em> and let
     * <em>valueBaseClase</em> be the return from calling
     * <code>ValueReference.getBase()</code> and <em>valueProperty</em>
     * be the return from calling
     * <code>ValueReference.getProperty()</code>.  If an earlier version
     * of the Unified EL is present, use the appropriate methods to
     * inspect <em>valueExpression</em> and derive values for
     * <em>valueBaseClass</em> and <em>valueProperty</em>.</p>

     * <p>If no <code>ValueReference</code> can be obtained, take no
     * action and return.</p>

     * <p>If <code>ValueReference.getBase()</code> return
     * <code>null</code>, take no action and return.</p>

     * <p>Obtain the {@link ValidatorContext} from the {@link
     * ValidatorFactory}.</p>

     * <p>Decorate the {@link MessageInterpolator} returned from {@link
     * ValidatorFactory#getMessageInterpolator} with one that leverages
     * the <code>Locale</code> returned from {@link
     * javax.faces.component.UIViewRoot#getLocale}, and store it in the
     * <code>ValidatorContext</code> using {@link
     * ValidatorContext#messageInterpolator}.</p>

     * <p>Obtain the {@link javax.validation.Validator} instance from
     * the <code>validatorContext</code>.</p>

     * <p>Obtain a <code>javax.validation.BeanDescriptor</code> from the
     * <code>javax.validation.Validator</code>.  If
     * <code>hasConstraints()</code> on the <code>BeanDescriptor</code>
     * returns false, take no action and return.  Otherwise proceed.</p>

     * <p>Call {@link javax.validation.Validator#validateValue}, passing
     * <em>valueBaseClass</em>, <em>valueProperty</em>, the
     * <em>value</em> argument, and <em>validatorGroupsArray</em> as
     * arguments.</p>

     * <p>If the returned <code>Set<{@link
     * ConstraintViolation}></code> is non-empty, for each element in
     * the <code>Set</code>, create a {@link FacesMessage} where the
     * summary and detail are the return from calling {@link
     * ConstraintViolation#getMessage}.  Capture all such
     * <code>FacesMessage</code> instances into a
     * <code>Collection</code> and pass them to {@link
     * ValidatorException#ValidatorException(java.util.Collection)},
     * throwing the new exception.</p>

     * </div>
     *
     * @param context {@inheritDoc}
     * @param component {@inheritDoc}
     * @param value {@inheritDoc}
     *
     * @throws ValidatorException   {@inheritDoc}
     */
public void validate(FacesContext context, UIComponent component, Object value) {
    if (context == null) {
        throw new NullPointerException();
    }
    if (component == null) {
        throw new NullPointerException();
    }
    ValueExpression valueExpression = component.getValueExpression("value");
    if (valueExpression == null) {
        return;
    }
    ValidatorFactory validatorFactory;
    Object cachedObject = context.getExternalContext().getApplicationMap().get(VALIDATOR_FACTORY_KEY);
    if (cachedObject instanceof ValidatorFactory) {
        validatorFactory = (ValidatorFactory) cachedObject;
    } else {
        try {
            validatorFactory = Validation.buildDefaultValidatorFactory();
        } catch (ValidationException e) {
            throw new FacesException("Could not build a default Bean Validator factory", e);
        }
        context.getExternalContext().getApplicationMap().put(VALIDATOR_FACTORY_KEY, validatorFactory);
    }
    ValidatorContext validatorContext = validatorFactory.usingContext();
    MessageInterpolator jsfMessageInterpolator = new JsfAwareMessageInterpolator(context, validatorFactory.getMessageInterpolator());
    validatorContext.messageInterpolator(jsfMessageInterpolator);
    javax.validation.Validator beanValidator = validatorContext.getValidator();
    Class[] validationGroupsArray = parseValidationGroups(getValidationGroups());
    // PENDING(rlubke, driscoll): When EL 1.3 is present, we won't need
    // this.
    ValueExpressionAnalyzer expressionAnalyzer = new ValueExpressionAnalyzer(valueExpression);
    ValueReference valueReference = expressionAnalyzer.getReference(context.getELContext());
    if (valueReference == null) {
        return;
    }
    if (isResolvable(valueReference, valueExpression)) {
        Set<ConstraintViolation<?>> violations = null;
        try {
            //noinspection unchecked
            violations = beanValidator.validateValue(valueReference.getBaseClass(), valueReference.getProperty(), value, validationGroupsArray);
        } catch (IllegalArgumentException iae) {
            String failureMessage = "Unable to validate expression " + valueExpression.getExpressionString() + " using Bean Validation.  Unable to get value of expression. " + " Message from Bean Validation: " + iae.getMessage();
            LOGGER.fine(failureMessage);
        }
        if (violations != null && !violations.isEmpty()) {
            ValidatorException toThrow;
            if (1 == violations.size()) {
                ConstraintViolation violation = violations.iterator().next();
                toThrow = new ValidatorException(MessageFactory.getMessage(context, MESSAGE_ID, violation.getMessage(), MessageFactory.getLabel(context, component)));
            } else {
                Set<FacesMessage> messages = new LinkedHashSet<FacesMessage>(violations.size());
                for (ConstraintViolation violation : violations) {
                    messages.add(MessageFactory.getMessage(context, MESSAGE_ID, violation.getMessage(), MessageFactory.getLabel(context, component)));
                }
                toThrow = new ValidatorException(messages);
            }
            throw toThrow;
        }
    }
}
Example 70
Project: oas-master  File: RestServiceExceptionFacade.java View source code
/**
   * @see #toResponse(Throwable)
   *
   * @param exception the exception to handle
   * @param catched the original exception that was cached. Either same as {@code error} or a (child-)
   *        {@link Throwable#getCause() cause} of it.
   * @return the response build from the exception.
   */
protected Response toResponse(Throwable exception, Throwable catched) {
    if (exception instanceof ValidationException) {
        return handleValidationException(exception, catched);
    } else if (exception instanceof ValidationErrorUserException) {
        return createResponse(exception, (ValidationErrorUserException) exception, null);
    } else {
        Class<?> exceptionClass = exception.getClass();
        for (Class<?> securityError : this.securityExceptions) {
            if (securityError.isAssignableFrom(exceptionClass)) {
                return handleSecurityError(exception, catched);
            }
        }
        return handleGenericError(exception, catched);
    }
}
Example 71
Project: oasp4j-master  File: RestServiceExceptionFacade.java View source code
/**
   * @see #toResponse(Throwable)
   *
   * @param exception the exception to handle
   * @param catched the original exception that was cached. Either same as {@code error} or a (child-)
   *        {@link Throwable#getCause() cause} of it.
   * @return the response build from the exception.
   */
protected Response toResponse(Throwable exception, Throwable catched) {
    if (exception instanceof ValidationException) {
        return handleValidationException(exception, catched);
    } else if (exception instanceof ValidationErrorUserException) {
        return createResponse(exception, (ValidationErrorUserException) exception, null);
    } else {
        Class<?> exceptionClass = exception.getClass();
        for (Class<?> securityError : this.securityExceptions) {
            if (securityError.isAssignableFrom(exceptionClass)) {
                return handleSecurityError(exception, catched);
            }
        }
        return handleGenericError(exception, catched);
    }
}
Example 72
Project: spring4-showcase-master  File: ConstraintDescriptorImpl.java View source code
@SuppressWarnings("unchecked")
private Set<Class<? extends Payload>> buildPayloadSet(T annotation) {
    Set<Class<? extends Payload>> payloadSet = newHashSet();
    Class<Payload>[] payloadFromAnnotation;
    try {
        //TODO be extra safe and make sure this is an array of Payload
        payloadFromAnnotation = ReflectionHelper.getAnnotationParameter(annotation, ConstraintHelper.PAYLOAD, Class[].class);
    } catch (ValidationException e) {
        payloadFromAnnotation = null;
    }
    if (payloadFromAnnotation != null) {
        payloadSet.addAll(Arrays.asList(payloadFromAnnotation));
    }
    return Collections.unmodifiableSet(payloadSet);
}
Example 73
Project: virgo.web-master  File: VirgoDeployerEjb.java View source code
public AppInfo deploy(String loc, StandardContext standardContext) throws OpenEJBException {
    if (loc == null) {
        throw new NullPointerException("location is null");
    }
    if (dynamicDeployer != null) {
        if (dynamicDeployer instanceof DynamicDeployerWithStandardContext) {
            ((DynamicDeployerWithStandardContext) dynamicDeployer).setStandardContext(standardContext);
        }
    }
    Properties p = new Properties();
    AppModule appModule = null;
    ClassLoader webAppClassLoader = null;
    try {
        File file = new File(loc);
        appModule = deploymentLoader.load(file);
        addAlternativeDDs(p, appModule);
        // disable resources (rename file name from resources.xml to
        // resources.xml.disabled)
        disableResourcesDescriptors(appModule);
        // set resources
        processResources(appModule, standardContext);
        //			ClassLoader old = Thread.currentThread().getContextClassLoader();
        //			Thread.currentThread().setContextClassLoader(Assembler.class.getClassLoader());
        final AppInfo appInfo = configurationFactory.configureApplication(appModule);
        //			Thread.currentThread().setContextClassLoader(old);
        if (p != null && p.containsKey(OPENEJB_DEPLOYER_FORCED_APP_ID_PROP)) {
            appInfo.appId = p.getProperty(OPENEJB_DEPLOYER_FORCED_APP_ID_PROP);
        }
        if (isAppBringingOwnPersistence(standardContext)) {
            overwritePersistenceIntegrationClassNames(appInfo);
        }
        AppContext appContext = assembler.createApplication(appInfo);
        bindOpenEjbRefsInTomcat(appInfo, appContext, standardContext);
        logMessage("Initialised enterprise container for application with context path '" + this.webContextPath + "'.", OpenEjbDeployerLogEvents.DEPLOYED_APP);
        return appInfo;
    } catch (Throwable e) {
        logMessage("Failed to initialise enterprise container for application with context path '" + this.webContextPath + "'.", OpenEjbDeployerLogEvents.FAILED_TO_DEPLOY_APP);
        if (appModule != null) {
            ClassLoaderUtil.destroyClassLoader(appModule.getJarLocation());
        }
        logger.error("Error while deploying application with real path '" + loc + "' and web context path '" + this.webContextPath + "'", e);
        if (e instanceof ValidationException) {
            throw (ValidationException) e;
        }
        if (e instanceof OpenEJBException) {
            if (e.getCause() instanceof ValidationException) {
                throw (ValidationException) e.getCause();
            }
            throw (OpenEJBException) e;
        }
        throw new OpenEJBException("Error while deploying application with real path '" + loc + "' and web context path '" + this.webContextPath + "'.", e);
    } finally {
        if (appModule != null) {
            try {
                closeOpenJars(appModule);
            } catch (Exception e) {
                logger.warn("Could not close open application jars");
            }
        }
        if (webAppClassLoader != null) {
            Thread.currentThread().setContextClassLoader(webAppClassLoader);
        }
    }
}
Example 74
Project: viritin-master  File: MBeanFieldGroup.java View source code
/**
     * A helper method that returns "bean level" validation errors, i.e. errors
     * that are not tied to a specific property/field.
     *
     * @return error messages from "bean level validation"
     */
public Collection<String> getBeanLevelValidationErrors() {
    Collection<String> errors = new ArrayList<>();
    if (getConstraintViolations() != null) {
        for (final ConstraintViolation<T> constraintViolation : getConstraintViolations()) {
            final MessageInterpolator.Context context = new MessageInterpolator.Context() {

                @Override
                public ConstraintDescriptor<?> getConstraintDescriptor() {
                    return constraintViolation.getConstraintDescriptor();
                }

                @Override
                public Object getValidatedValue() {
                    return constraintViolation.getInvalidValue();
                }

                @Override
                public <T> T unwrap(Class<T> type) {
                    throw new ValidationException();
                }
            };
            final String msg = getJavaxBeanValidatorFactory().getMessageInterpolator().interpolate(constraintViolation.getMessageTemplate(), context, getLocale());
            errors.add(msg);
        }
    }
    if (getBasicConstraintViolations() != null) {
        for (Validator.InvalidValueException cv : getBasicConstraintViolations()) {
            errors.add(cv.getMessage());
        }
    }
    return errors;
}
Example 75
Project: Broadleaf-eCommerce-master  File: BasicPersistenceModule.java View source code
@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity, Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties) throws ValidationException {
    final Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        FieldProviderResponse response = fieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (FieldProviderResponse.NOT_HANDLED != response) {
            handled = true;
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
    }
    //Order media field, map field and rule builder fields last, as they will have some validation components that depend on previous values
    Property[] sortedProperties = entity.getProperties();
    Arrays.sort(sortedProperties, new Comparator<Property>() {

        @Override
        public int compare(Property o1, Property o2) {
            BasicFieldMetadata mo1 = (BasicFieldMetadata) mergedProperties.get(o1.getName());
            BasicFieldMetadata mo2 = (BasicFieldMetadata) mergedProperties.get(o2.getName());
            boolean isLate1 = mo1 != null && mo1.getFieldType() != null && mo1.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo1.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo1.getFieldType() || SupportedFieldType.MEDIA == mo1.getFieldType() || o1.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            boolean isLate2 = mo2 != null && mo2.getFieldType() != null && mo2.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo2.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo2.getFieldType() || SupportedFieldType.MEDIA == mo2.getFieldType() || o2.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            if (isLate1 && !isLate2) {
                return 1;
            } else if (!isLate1 && isLate2) {
                return -1;
            }
            return 0;
        }
    });
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        RuntimeException entityPersistenceException = null;
        for (Property property : sortedProperties) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR) && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: " + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicBroadleafType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException("Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                Boolean mutable = metadata.getMutable();
                Boolean readOnly = metadata.getReadOnly();
                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }
                if ((mutable == null || mutable) && (readOnly == null || !readOnly)) {
                    if (value != null) {
                        handled = false;
                        PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this);
                        boolean attemptToPopulate = true;
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(), validationResult.getErrorMessage());
                                attemptToPopulate = false;
                            }
                        }
                        if (attemptToPopulate) {
                            try {
                                boolean isBreakDetected = false;
                                for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                    if (!isBreakDetected || fieldPersistenceProvider.alwaysRun()) {
                                        FieldProviderResponse response = fieldPersistenceProvider.populateValue(request, instance);
                                        if (FieldProviderResponse.NOT_HANDLED != response) {
                                            handled = true;
                                        }
                                        if (FieldProviderResponse.HANDLED_BREAK == response) {
                                            isBreakDetected = true;
                                        }
                                    }
                                }
                                if (!handled) {
                                    defaultFieldPersistenceProvider.populateValue(new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this), instance);
                                }
                            } catch (ParentEntityPersistenceExceptionjavax.validation.ValidationException |  e) {
                                entityPersistenceException = e;
                                cleanupFailedPersistenceAttempt(instance);
                                break;
                            }
                        }
                    } else {
                        try {
                            if (fieldManager.getFieldValue(instance, property.getName()) != null && (metadata.getFieldType() != SupportedFieldType.ID || setId) && metadata.getFieldType() != SupportedFieldType.PASSWORD) {
                                if (fieldManager.getFieldValue(instance, property.getName()) != null) {
                                    property.setIsDirty(true);
                                }
                                fieldManager.setFieldValue(instance, property.getName(), null);
                            }
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
            }
        }
        validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        //if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            //only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }
            //re-initialize the valid properties for the entity in order to deal with the potential of not
            //completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);
            String message = ValidationUtil.buildErrorMessage(invalid.getPropertyValidationErrors(), invalid.getGlobalValidationErrors());
            throw new ValidationException(invalid, message);
        } else if (entityPersistenceException != null) {
            throw ExceptionHelper.refineException(entityPersistenceException.getCause());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}
Example 76
Project: BroadleafCommerce-master  File: BasicPersistenceModule.java View source code
@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity, Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties) throws ValidationException {
    final Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        FieldProviderResponse response = fieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (FieldProviderResponse.NOT_HANDLED != response) {
            handled = true;
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
    }
    //Order media field, map field and rule builder fields last, as they will have some validation components that depend on previous values
    Property[] sortedProperties = entity.getProperties();
    Arrays.sort(sortedProperties, new Comparator<Property>() {

        @Override
        public int compare(Property o1, Property o2) {
            BasicFieldMetadata mo1 = (BasicFieldMetadata) mergedProperties.get(o1.getName());
            BasicFieldMetadata mo2 = (BasicFieldMetadata) mergedProperties.get(o2.getName());
            boolean isLate1 = mo1 != null && mo1.getFieldType() != null && mo1.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo1.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo1.getFieldType() || SupportedFieldType.MEDIA == mo1.getFieldType() || o1.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            boolean isLate2 = mo2 != null && mo2.getFieldType() != null && mo2.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo2.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo2.getFieldType() || SupportedFieldType.MEDIA == mo2.getFieldType() || o2.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            if (isLate1 && !isLate2) {
                return 1;
            } else if (!isLate1 && isLate2) {
                return -1;
            }
            return 0;
        }
    });
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        RuntimeException entityPersistenceException = null;
        for (Property property : sortedProperties) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR) && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: " + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicBroadleafType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException("Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                Boolean mutable = metadata.getMutable();
                Boolean readOnly = metadata.getReadOnly();
                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }
                if ((mutable == null || mutable) && (readOnly == null || !readOnly)) {
                    if (value != null) {
                        handled = false;
                        PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this);
                        boolean attemptToPopulate = true;
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(), validationResult.getErrorMessage());
                                attemptToPopulate = false;
                            }
                        }
                        if (attemptToPopulate) {
                            try {
                                boolean isBreakDetected = false;
                                for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                    if (!isBreakDetected || fieldPersistenceProvider.alwaysRun()) {
                                        FieldProviderResponse response = fieldPersistenceProvider.populateValue(request, instance);
                                        if (FieldProviderResponse.NOT_HANDLED != response) {
                                            handled = true;
                                        }
                                        if (FieldProviderResponse.HANDLED_BREAK == response) {
                                            isBreakDetected = true;
                                        }
                                    }
                                }
                                if (!handled) {
                                    defaultFieldPersistenceProvider.populateValue(new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this), instance);
                                }
                            } catch (ParentEntityPersistenceExceptionjavax.validation.ValidationException |  e) {
                                entityPersistenceException = e;
                                cleanupFailedPersistenceAttempt(instance);
                                break;
                            }
                        }
                    } else {
                        try {
                            if (fieldManager.getFieldValue(instance, property.getName()) != null && (metadata.getFieldType() != SupportedFieldType.ID || setId) && metadata.getFieldType() != SupportedFieldType.PASSWORD) {
                                if (fieldManager.getFieldValue(instance, property.getName()) != null) {
                                    property.setIsDirty(true);
                                }
                                fieldManager.setFieldValue(instance, property.getName(), null);
                            }
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
            }
        }
        validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        //if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            //only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }
            //re-initialize the valid properties for the entity in order to deal with the potential of not
            //completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);
            String message = ValidationUtil.buildErrorMessage(invalid.getPropertyValidationErrors(), invalid.getGlobalValidationErrors());
            throw new ValidationException(invalid, message);
        } else if (entityPersistenceException != null) {
            throw ExceptionHelper.refineException(entityPersistenceException.getCause());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}
Example 77
Project: commerce-master  File: BasicPersistenceModule.java View source code
@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity, Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties) throws ValidationException {
    final Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        FieldProviderResponse response = fieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (FieldProviderResponse.NOT_HANDLED != response) {
            handled = true;
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
    }
    //Order media field, map field and rule builder fields last, as they will have some validation components that depend on previous values
    Property[] sortedProperties = entity.getProperties();
    Arrays.sort(sortedProperties, new Comparator<Property>() {

        @Override
        public int compare(Property o1, Property o2) {
            BasicFieldMetadata mo1 = (BasicFieldMetadata) mergedProperties.get(o1.getName());
            BasicFieldMetadata mo2 = (BasicFieldMetadata) mergedProperties.get(o2.getName());
            boolean isLate1 = mo1 != null && mo1.getFieldType() != null && mo1.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo1.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo1.getFieldType() || SupportedFieldType.MEDIA == mo1.getFieldType() || o1.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            boolean isLate2 = mo2 != null && mo2.getFieldType() != null && mo2.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo2.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo2.getFieldType() || SupportedFieldType.MEDIA == mo2.getFieldType() || o2.getName().contains(FieldManager.MAPFIELDSEPARATOR));
            if (isLate1 && !isLate2) {
                return 1;
            } else if (!isLate1 && isLate2) {
                return -1;
            }
            return 0;
        }
    });
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager().unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        RuntimeException entityPersistenceException = null;
        for (Property property : sortedProperties) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR) && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: " + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicBroadleafType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException("Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                Boolean mutable = metadata.getMutable();
                Boolean readOnly = metadata.getReadOnly();
                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }
                if ((mutable == null || mutable) && (readOnly == null || !readOnly)) {
                    if (value != null) {
                        handled = false;
                        PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this);
                        boolean attemptToPopulate = true;
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(), validationResult.getErrorMessage());
                                attemptToPopulate = false;
                            }
                        }
                        if (attemptToPopulate) {
                            try {
                                boolean isBreakDetected = false;
                                for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                    if (!isBreakDetected || fieldPersistenceProvider.alwaysRun()) {
                                        FieldProviderResponse response = fieldPersistenceProvider.populateValue(request, instance);
                                        if (FieldProviderResponse.NOT_HANDLED != response) {
                                            handled = true;
                                        }
                                        if (FieldProviderResponse.HANDLED_BREAK == response) {
                                            isBreakDetected = true;
                                        }
                                    }
                                }
                                if (!handled) {
                                    defaultFieldPersistenceProvider.populateValue(new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this), instance);
                                }
                            } catch (ParentEntityPersistenceExceptionjavax.validation.ValidationException |  e) {
                                entityPersistenceException = e;
                                cleanupFailedPersistenceAttempt(instance);
                                break;
                            }
                        }
                    } else {
                        try {
                            if (fieldManager.getFieldValue(instance, property.getName()) != null && (metadata.getFieldType() != SupportedFieldType.ID || setId) && metadata.getFieldType() != SupportedFieldType.PASSWORD) {
                                if (fieldManager.getFieldValue(instance, property.getName()) != null) {
                                    property.setIsDirty(true);
                                }
                                fieldManager.setFieldValue(instance, property.getName(), null);
                            }
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
            }
        }
        validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        //if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            //only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }
            //re-initialize the valid properties for the entity in order to deal with the potential of not
            //completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);
            String message = ValidationUtil.buildErrorMessage(invalid.getPropertyValidationErrors(), invalid.getGlobalValidationErrors());
            throw new ValidationException(invalid, message);
        } else if (entityPersistenceException != null) {
            throw ExceptionHelper.refineException(entityPersistenceException.getCause());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}
Example 78
Project: resthub-spring-stack-master  File: ValidationContext.java View source code
/**
     * {@inheritDoc}
     */
@Override
public <T> T unwrap(Class<T> type) {
    if (type.isAssignableFrom(ValidationContext.class)) {
        return type.cast(this);
    }
    throw new ValidationException(String.format("Type %s not supported for unwrapping", type));
}
Example 79
Project: documentr-master  File: RoleExistsValidator.java View source code
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (StringUtils.isBlank(value)) {
        return true;
    }
    try {
        return userStore.getRole(value) != null;
    } catch (IOException e) {
        throw new ValidationException(e);
    }
}
Example 80
Project: graphity-core-master  File: AdultController.java View source code
@RequestMapping(value = "/adults", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public Adult create(@Valid @RequestBody Adult entity, BindingResult bindingResult) {
    // in practice we'd do a bit more than this...
    if (bindingResult.hasErrors()) {
        throw new ValidationException("oops");
    }
    return service.save(entity);
}
Example 81
Project: spring-data-neo4j-master  File: AdultController.java View source code
@RequestMapping(value = "/adults", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public Adult create(@Valid @RequestBody Adult entity, BindingResult bindingResult) {
    // in practice we'd do a bit more than this...
    if (bindingResult.hasErrors()) {
        throw new ValidationException("oops");
    }
    return service.save(entity);
}
Example 82
Project: transgalactica-master  File: HangarSeiTest.java View source code
@Test(expected = ValidationException.class)
public void testAppelServiceErreurValidation() throws RemoteBusinessException {
    sei.rechercherHangars("  ");
}
Example 83
Project: errai-master  File: NoopValidator.java View source code
@Override
public <T> Set<ConstraintViolation<T>> validate(GwtValidationContext<T> context, Object object, Class<?>... groups) throws ValidationException {
    return Collections.emptySet();
}
Example 84
Project: lab-master  File: PasswordsNotEqualValidatorTest.java View source code
@Test(expected = ValidationException.class)
public void passwordsNotEqual_InvalidPasswordField_ShouldThrowException() {
    InvalidPasswordFieldData invalid = new InvalidPasswordFieldData();
    validator.validate(invalid);
}
Example 85
Project: Restfull-Pickelink-Angular.js-master  File: EntityValidator.java View source code
/**
     * <p>
     * Validates the given Member variable and throws validation exceptions based on the type of error. If the error is standard
     * bean validation errors then it will throw a ConstraintValidationException with the set of the constraints violated.
     * </p>
     * <p>
     * If the error is caused because an existing member with the same email is registered it throws a regular validation
     * exception so that it can be interpreted separately.
     * </p>
     * 
     * @param member Member to be validated
     * @throws ConstraintViolationException If Bean Validation errors exist
     * @throws ValidationException If member with the same email already exists
     */
public <T> void validateEntity(final T entity) throws ConstraintViolationException, ValidationException {
    // Create a bean validator and check for issues.
    final Set<ConstraintViolation<T>> violations = validator.validate(entity);
    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations));
    }
}
Example 86
Project: spring-social-examples-master  File: PasswordsNotEqualValidatorTest.java View source code
@Test(expected = ValidationException.class)
public void passwordsNotEqual_InvalidPasswordField_ShouldThrowException() {
    InvalidPasswordFieldDTO invalid = new InvalidPasswordFieldDTO();
    validator.validate(invalid);
}
Example 87
Project: terasoluna-gfw-master  File: AbstractConstraintsTest.java View source code
/**
     * set {@code ExpectedException} for failed to initialize.
     * @param cls expected inner exception.
     */
protected void setExpectedFailedToInitialize(Class<?> cls) {
    thrown.expect(ValidationException.class);
    thrown.expectCause(allOf(Matchers.<Throwable>instanceOf(IllegalArgumentException.class), hasProperty("message", is(MESSAGE_INITIALIZE_ERROR)), hasProperty("cause", Matchers.<Throwable>instanceOf(cls))));
}
Example 88
Project: jcommune-master  File: ComponentHibernateDaoTest.java View source code
@Test(expectedExceptions = javax.validation.ValidationException.class)
public void testUpdateUuidNotNullViolation() {
    Component component = PersistedObjectsFactory.getDefaultComponent();
    session.save(component);
    component.setUuid(null);
    componentDao.saveOrUpdate(component);
    session.flush();
}
Example 89
Project: jTalk-master  File: ComponentHibernateDaoTest.java View source code
@Test(expectedExceptions = javax.validation.ValidationException.class)
public void testUpdateUuidNotNullViolation() {
    Component component = PersistedObjectsFactory.getDefaultComponent();
    session.save(component);
    component.setUuid(null);
    componentDao.saveOrUpdate(component);
    session.flush();
}
Example 90
Project: extended-objects-master  File: XOManagerFactoryImpl.java View source code
/**
     * Return the {@link javax.validation.ValidatorFactory}.
     *
     * @return The {@link javax.validation.ValidatorFactory}.
     */
private ValidatorFactory getValidatorFactory() {
    if (!ValidationMode.NONE.equals(validationMode)) {
        try {
            return Validation.buildDefaultValidatorFactory();
        } catch (ValidationException e) {
            LOGGER.debug("No JSR 303 Bean Validation provider available.", e);
        }
    }
    return null;
}
Example 91
Project: jooby-master  File: HbvTest.java View source code
@Test
public void conf() throws Exception {
    assertEquals(ConfigFactory.empty().withValue("err.javax.validation.ValidationException", ConfigValueFactory.fromAnyRef(400)), new Hbv().config());
}
Example 92
Project: cosmo-master  File: StandardRequestHandlerTest.java View source code
@Test
public void shouldMapValidationExceptionToForbiddenException() throws Exception {
    ValidationException ve = new ValidationException();
    CosmoDavException actual = captureExceptionForErrorResponseCausedBy(ve);
    Assert.assertTrue(actual instanceof ForbiddenException);
}
Example 93
Project: dddlib-master  File: EntityRepositoryHibernateTest.java View source code
@Test
public void testValidateFailure() {
    Dictionary dictionary = new Dictionary("", "", gender);
    try {
        dictionary.save();
        repository.flush();
        fail("应抛出异常�");
    } catch (ValidationException e) {
        System.out.println(e.getMessage());
        assertTrue(true);
    }
}