org.opentestsystem.delivery.testreg.persistence.criteria.NCESIDValidator.java Source code

Java tutorial

Introduction

Here is the source code for org.opentestsystem.delivery.testreg.persistence.criteria.NCESIDValidator.java

Source

/*******************************************************************************
 * Educational Online Test Delivery System
 * Copyright (c) 2013 American Institutes for Research
 * 
 * Distributed under the AIR Open Source License, Version 1.0
 * See accompanying file AIR-License-1_0.txt or at
 * http://www.smarterapp.org/documents/American_Institutes_for_Research_Open_Source_Software_License.pdf
 ******************************************************************************/

package org.opentestsystem.delivery.testreg.persistence.criteria;

import static org.apache.commons.beanutils.BeanUtils.getSimpleProperty;
import static org.apache.commons.beanutils.BeanUtils.setProperty;
import static org.apache.commons.lang.StringUtils.stripStart;
import static org.opentestsystem.delivery.testreg.domain.AnnotationHelper.getFieldLabel;
import static org.opentestsystem.delivery.testreg.domain.Sb11EntityUtils.getHumanReadableName;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.opentestsystem.delivery.testreg.domain.Action;
import org.opentestsystem.delivery.testreg.domain.DistrictEntity;
import org.opentestsystem.delivery.testreg.domain.FormatType;
import org.opentestsystem.delivery.testreg.domain.InstitutionEntity;
import org.opentestsystem.delivery.testreg.domain.Sb11Entity;
import org.opentestsystem.delivery.testreg.domain.search.AbstractTestRegSearchRequest;
import org.opentestsystem.delivery.testreg.domain.search.DistrictEntitySearchRequest;
import org.opentestsystem.delivery.testreg.service.impl.Sb11EntityServiceImpl;
import org.opentestsystem.shared.search.domain.SearchResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.FieldError;

@Component
public class NCESIDValidator implements Sb11BusinessValidator<Sb11Entity> {

    @Autowired
    private Sb11EntityServiceImpl<? extends Sb11Entity> sb11EntityService;

    @Resource
    private CacheManager cacheManager;

    @Override
    public Action getAction() {
        throw new UnsupportedOperationException("This operation is not supported for this object");
    }

    @Override
    public boolean supports(final Class<? extends Sb11Entity> clazz) {
        return Sb11Entity.class.isAssignableFrom(clazz);
    }

    @Override
    public List<FieldError> validate(final Sb11Entity sb11Entity) {
        switch (sb11Entity.getFormatType()) {
        case DISTRICT:
            return verifyNationwideIdentifier(sb11Entity, DistrictEntity.class);
        case INSTITUTION:
            return verifyNationwideIdentifier(sb11Entity, InstitutionEntity.class);
        default:
            return new ArrayList<>();

        }
    }

    private List<FieldError> verifyNationwideIdentifier(final Sb11Entity sb11Entity,
            final Class<? extends Sb11Entity> clazz) {
        final List<FieldError> errors = new ArrayList<>();

        try {
            final String propertyValue = getSimpleProperty(sb11Entity, "nationwideIdentifier");
            // If it is blank then not required to check for Unique
            if (!StringUtils.isEmpty(propertyValue)) {
                final String nationwideIdentifier = stripStart(propertyValue, "0");
                setProperty(sb11Entity, "nationwideIdentifier", nationwideIdentifier);

                final Sb11Entity ncesIdEntity = findByNationwideId(nationwideIdentifier,
                        sb11Entity.getFormatType());
                final Sb11Entity dbEntity = findDBEntity(sb11Entity, clazz);

                boolean existingEntity = false;
                if (ncesIdEntity != null && dbEntity != null && ncesIdEntity.getId().equals(dbEntity.getId())) {
                    existingEntity = true;
                }

                if (ncesIdEntity != null && !existingEntity) {
                    final String label = getFieldLabel(sb11Entity, "nationwideIdentifier");
                    errors.add(new FieldError(sb11Entity.getFormatType().name(), label, nationwideIdentifier, false,
                            null, null, getHumanReadableName(label) + " already exists in DB and cannot be added"));
                }
            }
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        return errors;
    }

    @SuppressWarnings("unchecked")
    private Sb11Entity findByNationwideId(final String nationwideIdentifier, final FormatType format) {

        if (format == FormatType.INSTITUTION) {
            final Cache ncesidCache = this.cacheManager.getCache("institution.ncesid");

            final ValueWrapper cacheGet = ncesidCache.get("ncesids");

            if (cacheGet != null) {

                final HashSet<String> ncesIdSet = (HashSet<String>) cacheGet.get();

                if (!ncesIdSet.contains(nationwideIdentifier)) {
                    return null;
                }
            }
        }

        final Map<String, String[]> reqMap = new HashMap<String, String[]>();
        reqMap.put(DistrictEntitySearchRequest.SEARCH_KEY_NCESID, new String[] { nationwideIdentifier });
        final AbstractTestRegSearchRequest searchRequest = new DistrictEntitySearchRequest(reqMap);
        searchRequest.setFilter(false);
        final SearchResponse<? extends Sb11Entity> response = this.sb11EntityService
                .searchDomainObjects(searchRequest, format);
        if (!CollectionUtils.isEmpty(response.getSearchResults())) {
            final Sb11Entity dbEntity = response.getSearchResults().get(0);
            return dbEntity;
        }
        return null;
    }

    private Sb11Entity findDBEntity(final Sb11Entity entity, final Class<? extends Sb11Entity> clazz) {
        Sb11Entity dbEntity = null;
        if (entity.getId() == null) {
            dbEntity = this.sb11EntityService.findByEntityIdAndStateAbbreviation(entity.getEntityId(),
                    entity.getStateAbbreviation(), clazz);
        } else {
            dbEntity = this.sb11EntityService.findById(entity.getId(), entity.getFormatType());
        }
        return dbEntity;
    }
}