Search in sources :

Example 31 with Person

use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project flow by vaadin.

the class BinderTest method setRequired_withCustomValidator_modelConverterBeforeValidator.

@Test
public void setRequired_withCustomValidator_modelConverterBeforeValidator() {
    TestTextField textField = new TestTextField();
    assertFalse(textField.isRequiredIndicatorVisible());
    Converter<String, String> stringBasicPreProcessingConverter = new Converter<String, String>() {

        @Override
        public Result<String> convertToModel(String value, ValueContext context) {
            if (StringUtils.isBlank(value)) {
                return Result.ok(null);
            }
            return Result.ok(StringUtils.trim(value));
        }

        @Override
        public String convertToPresentation(String value, ValueContext context) {
            if (value == null) {
                return "";
            }
            return value;
        }
    };
    AtomicInteger invokes = new AtomicInteger();
    Validator<String> customRequiredValidator = (value, context) -> {
        invokes.incrementAndGet();
        if (value == null) {
            return ValidationResult.error("Input required.");
        }
        return ValidationResult.ok();
    };
    binder.forField(textField).withConverter(stringBasicPreProcessingConverter).asRequired(customRequiredValidator).bind(Person::getFirstName, Person::setFirstName);
    binder.setBean(item);
    assertThat(textField.getErrorMessage(), isEmptyString());
    assertEquals(1, invokes.get());
    textField.setValue(" ");
    assertNotNull(textField.getErrorMessage());
    assertEquals("Input required.", componentErrors.get(textField));
    // validation is done for all changed bindings once.
    assertEquals(2, invokes.get());
    textField.setValue("value");
    assertFalse(textField.isInvalid());
    assertTrue(textField.isRequiredIndicatorVisible());
}
Also used : CoreMatchers(org.hamcrest.CoreMatchers) HasValue(com.vaadin.flow.component.HasValue) CurrentInstance(com.vaadin.flow.internal.CurrentInstance) Person(com.vaadin.flow.tests.data.bean.Person) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) StringToDoubleConverter(com.vaadin.flow.data.converter.StringToDoubleConverter) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringUtils(org.apache.commons.lang3.StringUtils) NumberFormat(java.text.NumberFormat) Assert.assertSame(org.junit.Assert.assertSame) BigDecimal(java.math.BigDecimal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) IntegerRangeValidator(com.vaadin.flow.data.validator.IntegerRangeValidator) Map(java.util.Map) After(org.junit.After) BindingBuilder(com.vaadin.flow.data.binder.Binder.BindingBuilder) UI(com.vaadin.flow.component.UI) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ExpectedException(org.junit.rules.ExpectedException) Before(org.junit.Before) StringToIntegerConverter(com.vaadin.flow.data.converter.StringToIntegerConverter) Assert.assertNotNull(org.junit.Assert.assertNotNull) DecimalFormat(java.text.DecimalFormat) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) StringToBigDecimalConverter(com.vaadin.flow.data.converter.StringToBigDecimalConverter) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) Serializable(java.io.Serializable) Objects(java.util.Objects) Converter(com.vaadin.flow.data.converter.Converter) StringLengthValidator(com.vaadin.flow.data.validator.StringLengthValidator) Stream(java.util.stream.Stream) Rule(org.junit.Rule) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) Optional(java.util.Optional) NotEmptyValidator(com.vaadin.flow.data.validator.NotEmptyValidator) Assert(org.junit.Assert) Binding(com.vaadin.flow.data.binder.Binder.Binding) TestTextField(com.vaadin.flow.data.binder.testcomponents.TestTextField) Sex(com.vaadin.flow.tests.data.bean.Sex) Matchers.containsString(org.hamcrest.Matchers.containsString) Assert.assertEquals(org.junit.Assert.assertEquals) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestTextField(com.vaadin.flow.data.binder.testcomponents.TestTextField) StringToDoubleConverter(com.vaadin.flow.data.converter.StringToDoubleConverter) StringToIntegerConverter(com.vaadin.flow.data.converter.StringToIntegerConverter) StringToBigDecimalConverter(com.vaadin.flow.data.converter.StringToBigDecimalConverter) Converter(com.vaadin.flow.data.converter.Converter) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) Matchers.containsString(org.hamcrest.Matchers.containsString) Person(com.vaadin.flow.tests.data.bean.Person) Test(org.junit.Test)

Example 32 with Person

use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project flow by vaadin.

the class BinderTest method bindingReadBean_converterThrows_exceptionHandlerSet_bindingExceptionIsThrown.

@Test(expected = BindingException.class)
public void bindingReadBean_converterThrows_exceptionHandlerSet_bindingExceptionIsThrown() {
    TestTextField testField = new TestTextField();
    setExceptionHandler();
    binder.forField(testField).withConverter(Converter.<String, String>from(name -> Result.ok(name), name -> {
        throw new NullPointerException();
    })).bind(Person::getFirstName, Person::setFirstName).read(new Person());
}
Also used : CoreMatchers(org.hamcrest.CoreMatchers) HasValue(com.vaadin.flow.component.HasValue) CurrentInstance(com.vaadin.flow.internal.CurrentInstance) Person(com.vaadin.flow.tests.data.bean.Person) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) StringToDoubleConverter(com.vaadin.flow.data.converter.StringToDoubleConverter) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringUtils(org.apache.commons.lang3.StringUtils) NumberFormat(java.text.NumberFormat) Assert.assertSame(org.junit.Assert.assertSame) BigDecimal(java.math.BigDecimal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) IntegerRangeValidator(com.vaadin.flow.data.validator.IntegerRangeValidator) Map(java.util.Map) After(org.junit.After) BindingBuilder(com.vaadin.flow.data.binder.Binder.BindingBuilder) UI(com.vaadin.flow.component.UI) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ExpectedException(org.junit.rules.ExpectedException) Before(org.junit.Before) StringToIntegerConverter(com.vaadin.flow.data.converter.StringToIntegerConverter) Assert.assertNotNull(org.junit.Assert.assertNotNull) DecimalFormat(java.text.DecimalFormat) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Matchers.isEmptyString(org.hamcrest.Matchers.isEmptyString) StringToBigDecimalConverter(com.vaadin.flow.data.converter.StringToBigDecimalConverter) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) Serializable(java.io.Serializable) Objects(java.util.Objects) Converter(com.vaadin.flow.data.converter.Converter) StringLengthValidator(com.vaadin.flow.data.validator.StringLengthValidator) Stream(java.util.stream.Stream) Rule(org.junit.Rule) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) Optional(java.util.Optional) NotEmptyValidator(com.vaadin.flow.data.validator.NotEmptyValidator) Assert(org.junit.Assert) Binding(com.vaadin.flow.data.binder.Binder.Binding) TestTextField(com.vaadin.flow.data.binder.testcomponents.TestTextField) Sex(com.vaadin.flow.tests.data.bean.Sex) Matchers.containsString(org.hamcrest.Matchers.containsString) Assert.assertEquals(org.junit.Assert.assertEquals) TestTextField(com.vaadin.flow.data.binder.testcomponents.TestTextField) Person(com.vaadin.flow.tests.data.bean.Person) Test(org.junit.Test)

Example 33 with Person

use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project molgenis by molgenis.

the class RestController method retrieveEntityCollection.

/**
 * Does a rsql/fiql query, returns the result as csv
 * <p>
 * Parameters:
 * <p>
 * q: the query
 * <p>
 * attributes: the attributes to return, if not specified returns all attributes
 * <p>
 * start: the index of the first row, default 0
 * <p>
 * num: the number of results to return, default 100, max 10000
 * <p>
 * <p>
 * Example: /api/v1/csv/person?q=firstName==Piet&attributes=firstName,lastName&start=10&num=100
 */
@GetMapping(value = "/csv/{entityTypeId}", produces = "text/csv")
@ResponseBody
public EntityCollection retrieveEntityCollection(@PathVariable("entityTypeId") String entityTypeId, @RequestParam(value = "attributes", required = false) String[] attributes, HttpServletRequest req, HttpServletResponse resp) throws IOException {
    final Set<String> attributesSet = toAttributeSet(attributes);
    EntityType meta;
    Iterable<Entity> entities;
    try {
        meta = dataService.getEntityType(entityTypeId);
        Query<Entity> q = new QueryStringParser(meta, molgenisRSQL).parseQueryString(req.getParameterMap());
        String[] sortAttributeArray = req.getParameterMap().get("sortColumn");
        if (sortAttributeArray != null && sortAttributeArray.length == 1 && StringUtils.isNotEmpty(sortAttributeArray[0])) {
            String sortAttribute = sortAttributeArray[0];
            String[] sortOrderArray = req.getParameterMap().get("sortOrder");
            Sort.Direction order = Sort.Direction.ASC;
            if (sortOrderArray != null && sortOrderArray.length == 1 && StringUtils.isNotEmpty(sortOrderArray[0])) {
                String sortOrder = sortOrderArray[0];
                switch(sortOrder) {
                    case "ASC":
                        order = Sort.Direction.ASC;
                        break;
                    case "DESC":
                        order = Sort.Direction.DESC;
                        break;
                    default:
                        throw new RuntimeException("unknown sort order");
                }
            }
            q.sort().on(sortAttribute, order);
        }
        if (q.getPageSize() == 0) {
            q.pageSize(EntityCollectionRequest.DEFAULT_ROW_COUNT);
        }
        if (q.getPageSize() > EntityCollectionRequest.MAX_ROWS) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Num exceeded the maximum of " + EntityCollectionRequest.MAX_ROWS + " rows");
            return null;
        }
        entities = () -> dataService.findAll(entityTypeId, q).iterator();
    } catch (ConversionFailedException | RSQLParserException | UnknownAttributeException | IllegalArgumentException | UnsupportedOperationException | UnknownEntityException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return null;
    } catch (MolgenisDataAccessException e) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }
    // Check attribute names
    Iterable<String> attributesIterable = Iterables.transform(meta.getAtomicAttributes(), attribute -> attribute.getName().toLowerCase());
    if (attributesSet != null) {
        SetView<String> diff = Sets.difference(attributesSet, Sets.newHashSet(attributesIterable));
        if (!diff.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown attributes " + diff);
            return null;
        }
    }
    attributesIterable = Iterables.transform(meta.getAtomicAttributes(), Attribute::getName);
    if (attributesSet != null) {
        attributesIterable = Iterables.filter(attributesIterable, attribute -> attributesSet.contains(attribute.toLowerCase()));
    }
    return new DefaultEntityCollection(entities, attributesIterable);
}
Also used : UnknownTokenException(org.molgenis.security.core.token.UnknownTokenException) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) ConversionFailedException(org.springframework.core.convert.ConversionFailedException) RestService(org.molgenis.data.rest.service.RestService) ErrorMessageResponse(org.molgenis.web.ErrorMessageResponse) LoggerFactory(org.slf4j.LoggerFactory) MultipartHttpServletRequest(org.springframework.web.multipart.MultipartHttpServletRequest) RunAsSystemAspect.runAsSystem(org.molgenis.security.core.runas.RunAsSystemAspect.runAsSystem) ENFORCED(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationSetting.ENFORCED) StringUtils(org.apache.commons.lang3.StringUtils) Attribute(org.molgenis.data.meta.model.Attribute) AuthenticationSettings(org.molgenis.security.settings.AuthenticationSettings) Valid(javax.validation.Valid) User(org.molgenis.data.security.auth.User) Matcher(java.util.regex.Matcher) ObjectError(org.springframework.validation.ObjectError) USER(org.molgenis.data.security.auth.UserMetaData.USER) AuthenticationException(org.springframework.security.core.AuthenticationException) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) DefaultEntityCollection(org.molgenis.data.support.DefaultEntityCollection) org.molgenis.data(org.molgenis.data) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException) UserAccountService(org.molgenis.security.user.UserAccountService) ConversionException(org.springframework.core.convert.ConversionException) Instant(java.time.Instant) EntityType(org.molgenis.data.meta.model.EntityType) Sets(com.google.common.collect.Sets) UserPermissionEvaluator(org.molgenis.security.core.UserPermissionEvaluator) LocalDate(java.time.LocalDate) MolgenisRSQL(org.molgenis.core.ui.data.rsql.MolgenisRSQL) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) Entry(java.util.Map.Entry) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Pattern(java.util.regex.Pattern) Authentication(org.springframework.security.core.Authentication) UserMetaData(org.molgenis.data.security.auth.UserMetaData) Iterables(com.google.common.collect.Iterables) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) java.util(java.util) ENABLED(org.molgenis.security.twofactor.auth.TwoFactorAuthenticationSetting.ENABLED) TokenParam(org.molgenis.security.token.TokenParam) ConstraintViolation(org.molgenis.data.validation.ConstraintViolation) QueryImpl(org.molgenis.data.support.QueryImpl) RSQLParserException(cz.jirutka.rsql.parser.RSQLParserException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Lists(com.google.common.collect.Lists) EntityUtils.getTypedValue(org.molgenis.data.util.EntityUtils.getTypedValue) Objects.requireNonNull(java.util.Objects.requireNonNull) Href(org.molgenis.core.ui.data.support.Href) ATTRIBUTE_META_DATA(org.molgenis.data.meta.model.AttributeMetadata.ATTRIBUTE_META_DATA) BASE_URI(org.molgenis.data.rest.RestController.BASE_URI) AttributeType(org.molgenis.data.meta.AttributeType) Logger(org.slf4j.Logger) AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) HttpServletResponse(javax.servlet.http.HttpServletResponse) SetView(com.google.common.collect.Sets.SetView) IOException(java.io.IOException) MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) ErrorMessage(org.molgenis.web.ErrorMessageResponse.ErrorMessage) HttpStatus(org.springframework.http.HttpStatus) TokenService(org.molgenis.security.core.token.TokenService) MultipartFile(org.springframework.web.multipart.MultipartFile) Transactional(org.springframework.transaction.annotation.Transactional) DefaultEntityCollection(org.molgenis.data.support.DefaultEntityCollection) RSQLParserException(cz.jirutka.rsql.parser.RSQLParserException) EntityType(org.molgenis.data.meta.model.EntityType) ConversionFailedException(org.springframework.core.convert.ConversionFailedException)

Example 34 with Person

use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project commons-lang by apache.

the class JsonToStringStyleTest method testArray.

@Test
public void testArray() {
    final Person p = new Person();
    p.name = "Jane Doe";
    p.age = 25;
    p.smoker = true;
    assertEquals("{\"name\":\"Jane Doe\",\"age\":25,\"smoker\":true,\"groups\":['admin', 'manager', 'user']}", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).append("groups", new Object() {

        @Override
        public String toString() {
            return "['admin', 'manager', 'user']";
        }
    }).toString());
}
Also used : Person(org.apache.commons.lang3.builder.ToStringStyleTest.Person) Test(org.junit.Test)

Example 35 with Person

use of org.apache.commons.lang3.builder.ToStringStyleTest.Person in project commons-lang by apache.

the class JsonToStringStyleTest method testPerson.

@Test
public void testPerson() {
    final Person p = new Person();
    p.name = "Jane Doe";
    p.age = 25;
    p.smoker = true;
    assertEquals("{\"name\":\"Jane Doe\",\"age\":25,\"smoker\":true}", new ToStringBuilder(p).append("name", p.name).append("age", p.age).append("smoker", p.smoker).toString());
}
Also used : Person(org.apache.commons.lang3.builder.ToStringStyleTest.Person) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)43 BaseTest (org.umlg.sqlg.test.BaseTest)24 StopWatch (org.apache.commons.lang3.time.StopWatch)23 StringUtils (org.apache.commons.lang3.StringUtils)21 Vertex (org.apache.tinkerpop.gremlin.structure.Vertex)20 HashMap (java.util.HashMap)18 Map (java.util.Map)17 Optional (java.util.Optional)16 BigDecimal (java.math.BigDecimal)15 Assert (org.junit.Assert)15 Locale (java.util.Locale)14 HasValue (com.vaadin.flow.component.HasValue)13 UI (com.vaadin.flow.component.UI)13 Binding (com.vaadin.flow.data.binder.Binder.Binding)13 BindingBuilder (com.vaadin.flow.data.binder.Binder.BindingBuilder)13 TestTextField (com.vaadin.flow.data.binder.testcomponents.TestTextField)13 Converter (com.vaadin.flow.data.converter.Converter)13 StringToBigDecimalConverter (com.vaadin.flow.data.converter.StringToBigDecimalConverter)13 StringToDoubleConverter (com.vaadin.flow.data.converter.StringToDoubleConverter)13 StringToIntegerConverter (com.vaadin.flow.data.converter.StringToIntegerConverter)13