Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.deephacks.tools4j.config.internal.core.admin;
 
 
 import java.util.List;
 import java.util.Map;
 
 import static org.deephacks.tools4j.config.internal.core.admin.SchemaValidator.validateSchema;

AdminCoreContext is responsible for separating the admin and runtime context so that no dependencies (compile nor runtime) exist between them.
 
 public final class AdminCoreContext extends AdminContext {
    
name of the validator class
 
     public static final String VALIDATOR_CLASSNAME = "org.deephacks.tools4j.config.internal.core.admin.Jsr303Validator";
    
API class for JSR 303 1.0 bean validation
 
     public static final String JSR303_1_0_CLASSNAME = "javax.validation.Validation";
 
     private static final Logger log = LoggerFactory.getLogger(AdminCoreContext.class);
     private static final Conversion conversion;
 
     static {
          = Conversion.get();
         .register(new BeanToObjectConverter());
         .register(new ObjectToBeanConverter());
         .register(new ClassToSchemaConverter());
     }
 
     @Inject
     private ConfigCore core;
 
     private BeanManager beanManager;
     private SchemaManager schemaManager;
     private Optional<Jsr303Validatorvalidator;
     private Optional<CacheManagercacheManager;
 
     @Override
     public List<Beanlist(String schemaName) {
         Preconditions.checkNotNull(schemaName);
         doLookup();
         Map<BeanIdBeanbeans = .list(schemaName);
         .setSchema(.getSchemas(), beans);
         return new ArrayList<>(beans.values());
     }
 
     @Override
     public List<Beanlist(String schemaNameCollection<StringinstanceIds) {
         Preconditions.checkNotNull(schemaName);
         if (instanceIds == null || instanceIds.isEmpty()) {
             return new ArrayList<>();
         }
         doLookup();
         Map<BeanIdBeanbeans = .list(schemaNameinstanceIds);
         Map<BeanIdBeanresult = new HashMap<>();
         for (String instanceId : instanceIds) {
             Bean b = beans.get(BeanId.create(instanceIdschemaName));
             result.put(b.getId(), b);
        }
        Map<StringSchemaschemas = .getSchemas();
        .setSchema(schemasresult);
        return new ArrayList<>(result.values());
    }
    @Override
    public Bean get(BeanId beanId) {
        Preconditions.checkNotNull(beanId);
        doLookup();
        Bean bean = .getEager(beanId);
        Map<StringSchemaschemas = .getSchemas();
        .setSchema(beanschemas);
        setSingletonReferences(beanschemas);
        return bean;
    }
    @Override
    public void create(Bean bean) {
        Preconditions.checkNotNull(bean);
        create(Arrays.asList(bean));
        .cache(bean);
    }
    @Override
    public void createObject(Object objectthrows AbortRuntimeException {
        createObjects(Arrays.asList(object));
    }
    @Override
    public void create(Collection<Beanbeans) {
        if (beans == null || beans.isEmpty()) {
            return;
        }
        doLookup();
        .setSchema(.getSchemas(), beans);
        validateSchema(beans);
        if (.isPresent()) {
            initReferences(beans);
            .get().validate(beans);
        }
        .create(beans);
        .cache(beans);
    }
    @Override
    public void createObjects(Collection<?> objectsthrows AbortRuntimeException {
        if (objects == null || objects.isEmpty()) {
            return;
        }
        Collection<Beanbeans = convertToBeans(objects);
        create(beans);
    }
    @Override
    public void set(Bean bean) {
        Preconditions.checkNotNull(bean);
        set(Arrays.asList(bean));
    }
    @Override
    public void setObject(Object objectthrows AbortRuntimeException {
        setObjects(Arrays.asList(object));
    }
    @Override
    public void set(Collection<Beanbeans) {
        if (beans == null || beans.isEmpty()) {
            return;
        }
        doLookup();
        .setSchema(.getSchemas(), beans);
        validateSchema(beans);
        if (.isPresent()) {
            initReferences(beans);
            validateSet(beans);
        }
        .set(beans);
        .cache(beans);
    }
    @Override
    public void setObjects(Collection<?> objectsthrows AbortRuntimeException {
        if (objects == null || objects.isEmpty()) {
            return;
        }
        Collection<Beanbeans = convertToBeans(objects);
        set(beans);
    }
    @Override
    public void merge(Bean bean) {
        Preconditions.checkNotNull(bean);
        merge(Arrays.asList(bean));
    }
    @Override
    public void mergeObject(Object objectthrows AbortRuntimeException {
        mergeObjects(Arrays.asList(object));
    }
    @Override
    public void merge(Collection<Beanbeans) {
        if (beans == null || beans.isEmpty()) {
            return;
        }
        doLookup();
        .setSchema(.getSchemas(), beans);
        validateSchema(beans);
        // ok to not have validation manager available
        if (.isPresent()) {
            validateMerge(beans);
        }
        .merge(beans);
        for (Bean bean : beans) {
            // must refresh the bean from storage since it is merged.
            Bean refreshed = .getEager(bean.getId());
            .cache(refreshed);
        }
    }
    @Override
    public void mergeObjects(Collection<?> objectsthrows AbortRuntimeException {
        if (objects == null || objects.isEmpty()) {
            return;
        }
        Collection<Beanbeans = convertToBeans(objects);
        merge(beans);
    }
    @Override
    public void delete(BeanId beanId) {
        Preconditions.checkNotNull(beanId);
        doLookup();
        .delete(beanId);
        .cacheRemove(beanId);
    }
    @Override
    public void delete(String nameCollection<Stringinstances) {
        Preconditions.checkNotNull(name);
        if (instances == null || instances.isEmpty()) {
            return;
        }
        doLookup();
        .delete(nameinstances);
        .cacheRemove(nameinstances);
    }
    @Override
    public Map<StringSchemagetSchemas() {
        doLookup();
        return .getSchemas();
    }
    @Override
    public BeanQuery newQuery(String schemaName) {
        doLookup();
        Schema schema = .getSchema(schemaName);
        Preconditions.checkNotNull(schema"Schema " + schemaName + " does not exist.");
        return .newQuery(schema);
    }
    private void initReferences(Collection<Beanbeans) {
        Map<BeanIdBeanindexed = BeanUtils.uniqueIndex(beans);
        for (Bean bean : beans) {
            for (String name : bean.getReferenceNames()) {
                List<BeanIdids = bean.getReference(name);
                if (ids == null) {
                    continue;
                }
                for (BeanId id : ids) {
                    Bean ref = indexed.get(id);
                    if (ref == null) {
                        // TODO: investigate if eager is really needed
                        ref = .getEager(id);
                        .setSchema(ref.getSchemas());
                    }
                    id.setBean(ref);
                }
            }
        }
    }
    private void validateMerge(Collection<Beanmergebeans) {
        Map<BeanIdBeanbeansToValidate = .getBeanToValidate(mergebeans);
        .setSchema(.getSchemas(), beansToValidate);
        // since we are validating mergebean predecessors, we need to make sure
        // that they see a merged reference (not unmerged reference currently in storage)
        // before validation can proceed.
        for (Bean mergebean : mergebeans) {
            ArrayList<BeanmergeBeanReferences = new ArrayList<>();
            ArrayList<Beanchecked = new ArrayList<>();
            findReferences(mergebean.getId(), beansToValidate.values(), mergeBeanReferences,
                    checked);
            // merge all references
            merge(mergeBeanReferencesmergebean);
        }
        // ready to validate
        .get().validate(beansToValidate.values());
    }
    private void validateSet(Collection<Beansetbeans) {
        Map<BeanIdBeanbeansToValidate = .getBeanToValidate(setbeans);
        .setSchema(.getSchemas(), beansToValidate);
        // since we are validating setbean predecessors, we need to make sure
        // that they see a replaced/set reference (not old reference currently in storage)
        // before validation can proceed.
        for (Bean setbean : setbeans) {
            ArrayList<BeansetBeanReferences = new ArrayList<>();
            ArrayList<Beanchecked = new ArrayList<>();
            findReferences(setbean.getId(), beansToValidate.values(), setBeanReferenceschecked);
            for (Bean ref : setBeanReferences) {
                // clearing and then merging have same
                // effect as a 'set' operation
                ref.clear();
            }
            merge(setBeanReferencessetbean);
        }
        .get().validate(beansToValidate.values());
    }

    
Does a recursive check if predecessor have a particular reference and if so return those predecessor references.
    private List<BeanfindReferences(BeanId referenceCollection<Beanpredecessors,
            ArrayList<BeanmatchesArrayList<Beanchecked) {
        for (Bean predecessor : predecessors) {
            findReferences(referencepredecessormatcheschecked);
        }
        return matches;
    }
    private void findReferences(BeanId referenceBean predecessorArrayList<Beanmatches,
            ArrayList<Beanchecked) {
        if (checked.contains(predecessor)) {
            return;
        }
        checked.add(predecessor);
        if (reference.equals(predecessor.getId()) && !matches.contains(predecessor)) {
            matches.add(predecessor);
        }
        for (BeanId ref : predecessor.getReferences()) {
            if (ref.getBean() == null) {
                continue;
            }
            if (matches.contains(ref.getBean())) {
                continue;
            }
            if (ref.equals(reference)) {
                matches.add(ref.getBean());
            }
            findReferences(referenceref.getBean(), matcheschecked);
        }
    }
    private void merge(List<BeansourcesBean mergeBean) {
        HashMap<BeanIdBeancache = new HashMap<>();
        for (Bean source : sources) {
            for (String name : mergeBean.getPropertyNames()) {
                List<Stringvalues = mergeBean.getValues(name);
                if (values == null || values.size() == 0) {
                    continue;
                }
                source.setProperty(namevalues);
            }
            for (String name : mergeBean.getReferenceNames()) {
                List<BeanIdrefs = mergeBean.getReference(name);
                if (refs == null || refs.size() == 0) {
                    source.setReferences(namerefs);
                    continue;
                }
                for (BeanId beanId : refs) {
                    Bean bean = cache.get(beanId);
                    if (bean == null) {
                        bean = .getLazy(beanId);
                        .setSchema(bean.getSchemas());
                        cache.put(beanIdbean);
                    }
                    beanId.setBean(bean);
                }
                source.setReferences(namerefs);
            }
        }
    }

    
Used for setting or creating a single bean.
    @SuppressWarnings("unused")
    private void initalizeReferences(Bean bean) {
        for (String name : bean.getReferenceNames()) {
            List<BeanIdvalues = bean.getReference(name);
            if (values == null) {
                continue;
            }
            for (BeanId beanId : values) {
                Bean ref = .getEager(beanId);
                beanId.setBean(ref);
                .setSchema(beanId.getBean(), .getSchemas());
            }
        }
    }

    
Used for setting or creating a multiple beans. We must consider that the operation may include beans that have references betewen eachother. User provided beans are prioritized and the storage is secondary for looking up references.
    @SuppressWarnings("unused")
    private void initalizeReferences(Collection<Beanbeans) {
        Map<BeanIdBeanuserProvided = BeanUtils.uniqueIndex(beans);
        for (Bean bean : beans) {
            for (String name : bean.getReferenceNames()) {
                List<BeanIdvalues = bean.getReference(name);
                if (values == null) {
                    continue;
                }
                for (BeanId beanId : values) {
                    // the does not exist in storage, but may exist in the
                    // set of beans provided by the user.
                    Bean ref = userProvided.get(beanId);
                    if (ref == null) {
                        ref = .getEager(beanId);
                    }
                    beanId.setBean(ref);
                    .setSchema(beanId.getBean(), .getSchemas());
                }
            }
        }
    }
    private void setSingletonReferences(Bean beanMap<StringSchemaschemas) {
        Schema s = bean.getSchema();
        for (SchemaPropertyRef ref : s.get(SchemaPropertyRef.class)) {
            if (ref.isSingleton()) {
                Schema singletonSchema = schemas.get(ref.getSchemaName());
                Bean singleton = .getSingleton(ref.getSchemaName());
                singleton.set(singletonSchema);
                BeanId singletonId = singleton.getId();
                singletonId.setBean(singleton);
                // recursive call.
                setSingletonReferences(singletonschemas);
                bean.setReference(ref.getName(), singletonId);
            }
        }
    }
    private void doLookup() {
        // core would already be injected in a cdi environment
        if ( == null) {
             = new ConfigCore();
        }
        if ( == null) {
             = .lookupBeanManager();
            .info("Initalize bean manager {}");
        }
        if ( == null) {
             = .lookupSchemaManager();
            .info("Initalize schema manager {}");
        }
        if ( == null) {
             = .lookupCacheManager();
            .info("Initalize cache manager {}");
        }
        if ( == null) {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            try {
                cl.loadClass();
                Class<?> clazz = cl.loadClass();
                 = Optional.of((Jsr303Validatorclazz.newInstance());
                .info("Jsr303 Bean Validation initalized");
            } catch (Exception e) {
                .info("Jsr303 Bean Validation not found on classpath.");
                 = Optional.absent();
            }
        }
    }
    private Collection<BeanconvertToBeans(Collection<?> objects) {
        ArrayList<Beanbeans = new ArrayList<>();
        for (Object object : objects) {
            if(object instanceof Bean) {
                beans.add((Beanobject);
            } else {
                Bean bean = .convert(objectBean.class);
                beans.add(bean);
            }
        }
        return beans;
    }
New to GrepCode? Check out our FAQ X