Search in sources :

Example 1 with NestedNullException

use of org.apache.commons.beanutils.NestedNullException in project cloudbreak by hortonworks.

the class RequestPropertyAuthorizationFactory method calcAuthorization.

private Optional<AuthorizationRule> calcAuthorization(Object resourceObject, CheckPermissionByRequestProperty methodAnnotation, String userCrn) {
    boolean skipOnNull = methodAnnotation.skipOnNull();
    try {
        Object fieldObject = PropertyUtils.getProperty(resourceObject, methodAnnotation.path());
        AuthorizationVariableType authorizationVariableType = methodAnnotation.type();
        AuthorizationResourceAction action = methodAnnotation.action();
        if (fieldObject != null) {
            return calcAuthorizationFromObject(action, authorizationVariableType, fieldObject, userCrn);
        } else if (!methodAnnotation.skipOnNull()) {
            throw new BadRequestException(String.format("Property [%s] of the request object must not be null.", methodAnnotation.path()));
        }
    } catch (NestedNullException nne) {
        if (!skipOnNull) {
            throw new BadRequestException(String.format("Property [%s] of the request object must not be null.", methodAnnotation.path()));
        }
    } catch (NotFoundException nfe) {
        LOGGER.warn("Resource not found during permission check of resource object, this should be handled by microservice.");
    } catch (Error | RuntimeException unchecked) {
        LOGGER.error("Error happened during authorization of the request object: ", unchecked);
        throw unchecked;
    } catch (Throwable t) {
        LOGGER.error("Error happened during authorization of the request object: ", t);
        throw new AccessDeniedException("Error happened during authorization of the request object, thus access is denied!", t);
    }
    return Optional.empty();
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) BadRequestException(com.sequenceiq.cloudbreak.common.exception.BadRequestException) NestedNullException(org.apache.commons.beanutils.NestedNullException) NotFoundException(com.sequenceiq.cloudbreak.common.exception.NotFoundException) RequestObject(com.sequenceiq.authorization.annotation.RequestObject) AuthorizationResourceAction(com.sequenceiq.authorization.resource.AuthorizationResourceAction) AuthorizationVariableType(com.sequenceiq.authorization.resource.AuthorizationVariableType)

Example 2 with NestedNullException

use of org.apache.commons.beanutils.NestedNullException in project jans by JanssenProject.

the class ComplexSearchUserTest method searchAttributesParam.

@Test
public void searchAttributesParam() throws Exception {
    int count = 3;
    List<String> attrList = Arrays.asList("name.familyName", "active");
    logger.debug("Searching at most {} users using POST verb", count);
    logger.debug("Sorted by family name descending");
    logger.debug("Retrieving only the attributes {}", attrList);
    SearchRequest sr = new SearchRequest();
    sr.setFilter("name.familyName pr");
    sr.setSortBy("name.familyName");
    sr.setSortOrder("descending");
    // Generate a string with the attributes desired to be returned separated by comma
    sr.setAttributes(attrList.toString().replaceFirst("\\[", "").replaceFirst("]", ""));
    sr.setCount(count);
    Response response = client.searchUsersPost(sr);
    assertEquals(response.getStatus(), OK.getStatusCode());
    ListResponse listResponse = response.readEntity(ListResponse.class);
    if (listResponse.getResources().size() < count)
        logger.warn("Less than {} users satisfying the criteria. TESTER please check manually", count);
    else {
        // Obtain an array of results
        UserResource[] users = listResponse.getResources().stream().map(usrClass::cast).collect(Collectors.toList()).toArray(new UserResource[0]);
        assertEquals(users.length, count);
        // Build a set of all attributes that should not appear in the response
        Set<String> check = new HashSet<>();
        check.addAll(IntrospectUtil.allAttrs.get(usrClass));
        // Remove from the ALL list, those requested plus its "parents"
        for (String attr : attrList) {
            String part = attr;
            for (int i = part.length(); i > 0; i = part.lastIndexOf(".")) {
                part = part.substring(0, i);
                check.remove(part);
            }
        }
        // Remove those that are ALWAYS present (per spec)
        check.removeAll(IntrospectUtil.alwaysCoreAttrs.get(usrClass).keySet());
        // Confirm for every user, those attributes are not there
        for (UserResource user : users) {
            for (String path : check) {
                String val = null;
                try {
                    val = BeanUtils.getProperty(user, path);
                } catch (NestedNullException nne) {
                // Intentionally left empty
                } finally {
                    assertNull(val);
                }
            }
        }
        boolean correctSorting = true;
        for (int i = 1; i < users.length && correctSorting; i++) {
            String familyName = users[i - 1].getName().getFamilyName();
            String familyName2 = users[i].getName().getFamilyName();
            // First string has to be greater than or equal second
            correctSorting = familyName.compareTo(familyName2) >= 0;
        }
        if (!correctSorting) {
            // LDAP may ignore case sensitivity, try again using lowercasing
            correctSorting = true;
            for (int i = 1; i < users.length && correctSorting; i++) {
                String familyName = users[i - 1].getName().getFamilyName().toLowerCase();
                String familyName2 = users[i].getName().getFamilyName().toLowerCase();
                // First string has to be greater than or equal second
                correctSorting = familyName.compareTo(familyName2) >= 0;
            }
        }
        assertTrue(correctSorting);
    }
}
Also used : SearchRequest(io.jans.scim.model.scim2.SearchRequest) ListResponse(io.jans.scim.model.scim2.ListResponse) UserResource(io.jans.scim.model.scim2.user.UserResource) Response(javax.ws.rs.core.Response) ListResponse(io.jans.scim.model.scim2.ListResponse) NestedNullException(org.apache.commons.beanutils.NestedNullException) UserBaseTest(io.jans.scim2.client.UserBaseTest) Test(org.testng.annotations.Test)

Example 3 with NestedNullException

use of org.apache.commons.beanutils.NestedNullException in project pnc by project-ncl.

the class StreamRSQLNodeTraveller method visit.

@Override
public Boolean visit(ComparisonNode node) {
    logger.trace("Parsing ComparisonNode {}", node);
    String fieldName = node.getSelector();
    String argument = node.getArguments().get(0);
    try {
        String propertyValue = BeanUtils.getProperty(instance, fieldName);
        if (node.getOperator().equals(RSQLProducerImpl.IS_NULL)) {
            return Boolean.valueOf(propertyValue == null).equals(Boolean.valueOf(argument));
        }
        if (propertyValue == null) {
            // Null values are considered not equal
            return false;
        }
        if (node.getOperator().equals(RSQLOperators.EQUAL)) {
            return propertyValue.equals(argument);
        } else if (node.getOperator().equals(RSQLOperators.NOT_EQUAL)) {
            return !propertyValue.equals(argument);
        } else if (node.getOperator().equals(RSQLOperators.GREATER_THAN)) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            Number argumentNumber = numberFormat.parse(argument);
            return numberFormat.parse(propertyValue).intValue() > argumentNumber.intValue();
        } else if (node.getOperator().equals(RSQLOperators.GREATER_THAN_OR_EQUAL)) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            Number argumentNumber = numberFormat.parse(argument);
            return numberFormat.parse(propertyValue).intValue() >= argumentNumber.intValue();
        } else if (node.getOperator().equals(RSQLOperators.LESS_THAN)) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            Number argumentNumber = numberFormat.parse(argument);
            return numberFormat.parse(propertyValue).intValue() < argumentNumber.intValue();
        } else if (node.getOperator().equals(RSQLOperators.LESS_THAN_OR_EQUAL)) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            Number argumentNumber = numberFormat.parse(argument);
            return numberFormat.parse(propertyValue).intValue() <= argumentNumber.intValue();
        } else if (node.getOperator().equals(RSQLProducerImpl.LIKE)) {
            argument = argument.replaceAll(RSQLProducerImpl.UNKNOWN_PART_PLACEHOLDER, ".*").replaceAll("%", ".*");
            return propertyValue.matches(argument);
        } else if (node.getOperator().equals(RSQLProducerImpl.NOT_LIKE)) {
            argument = argument.replaceAll(RSQLProducerImpl.UNKNOWN_PART_PLACEHOLDER, ".*").replaceAll("%", ".*");
            return !propertyValue.matches(argument);
        } else if (node.getOperator().equals(RSQLOperators.IN)) {
            return node.getArguments().contains(propertyValue);
        } else if (node.getOperator().equals(RSQLOperators.NOT_IN)) {
            return !node.getArguments().contains(propertyValue);
        } else {
            throw new UnsupportedOperationException("Not Implemented yet!");
        }
    } catch (NestedNullException e) {
        // If a nested property is null (i.e. idRev.id is null), it is considered a false equality
        return false;
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        throw new IllegalStateException("Reflections exception", e);
    } catch (ParseException e) {
        throw new IllegalStateException("RSQL parse exception", e);
    }
}
Also used : NestedNullException(org.apache.commons.beanutils.NestedNullException) ParseException(java.text.ParseException) InvocationTargetException(java.lang.reflect.InvocationTargetException) NumberFormat(java.text.NumberFormat)

Example 4 with NestedNullException

use of org.apache.commons.beanutils.NestedNullException in project displaytag by hazendaz.

the class LookupUtil method getBeanProperty.

/**
 * <p>
 * Returns the value of a property in the given bean.
 * </p>
 * <p>
 * Handle <code>NestedNullException</code> returning nulls and other exceptions returning
 * <code>ObjectLookupException</code>.
 * </p>
 *
 * @param bean
 *            javabean
 * @param name
 *            name of the property to read from the javabean
 *
 * @return Object
 *
 * @throws ObjectLookupException
 *             for errors while retrieving a property in the bean
 */
public static Object getBeanProperty(final Object bean, final String name) throws ObjectLookupException {
    Validate.notNull(bean, "No bean specified");
    Validate.notNull(name, "No name specified");
    if (LookupUtil.log.isDebugEnabled()) {
        LookupUtil.log.debug("getProperty [{}] on bean {}", name, bean);
    }
    try {
        return LookupUtil.getProperty(bean, name);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        throw new ObjectLookupException(LookupUtil.class, bean, name, e);
    } catch (final NestedNullException nne) {
        // don't throw exceptions for nulls
        return null;
    } catch (final IllegalArgumentException e) {
        // don't throw exceptions for nulls; the bean and name have already been checked; this is being thrown when
        // the bean property value is itself null.
        LookupUtil.log.debug("Caught IllegalArgumentException from beanutils while looking up " + name + " in bean " + bean, e);
        return null;
    }
}
Also used : ObjectLookupException(org.displaytag.exception.ObjectLookupException) NestedNullException(org.apache.commons.beanutils.NestedNullException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Aggregations

NestedNullException (org.apache.commons.beanutils.NestedNullException)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 RequestObject (com.sequenceiq.authorization.annotation.RequestObject)1 AuthorizationResourceAction (com.sequenceiq.authorization.resource.AuthorizationResourceAction)1 AuthorizationVariableType (com.sequenceiq.authorization.resource.AuthorizationVariableType)1 BadRequestException (com.sequenceiq.cloudbreak.common.exception.BadRequestException)1 NotFoundException (com.sequenceiq.cloudbreak.common.exception.NotFoundException)1 ListResponse (io.jans.scim.model.scim2.ListResponse)1 SearchRequest (io.jans.scim.model.scim2.SearchRequest)1 UserResource (io.jans.scim.model.scim2.user.UserResource)1 UserBaseTest (io.jans.scim2.client.UserBaseTest)1 NumberFormat (java.text.NumberFormat)1 ParseException (java.text.ParseException)1 Response (javax.ws.rs.core.Response)1 ObjectLookupException (org.displaytag.exception.ObjectLookupException)1 AccessDeniedException (org.springframework.security.access.AccessDeniedException)1 Test (org.testng.annotations.Test)1