------------------------------------------------------ generic crud
429106
private void launchAddDialog(final String resourceName, final AddressTemplate template,
            final ResourceDescription resourceDescription, String... attributes) {
        DefaultWindow dialog = new DefaultWindow(Console.MESSAGES.newTitle(resourceName));
        AddResourceDialog addDialog = new AddResourceDialog(securityContext, resourceDescription,
                new AddResourceDialog.Callback() {
                    @Override
                    public void onAdd(ModelNode payload) {
                        dialog.hide();

                        String name = payload.get("name").asString();
                        ResourceAddress address = template.resolve(statementContext, name);
                        payload.get(OP).set(ADD);
                        payload.get(ADDRESS).set(address);
                        dispatcher.execute(new DMRAction(payload), new SimpleCallback<DMRResponse>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                super.onFailure(caught);
                                readFederation();
                            }

                            @Override
                            public void onSuccess(DMRResponse dmrResponse) {
                                Console.info(Console.MESSAGES.successfullyAdded(name));
                                readFederation();
                            }
                        });
                    }

                    @Override
                    public void onCancel() {
                        dialog.hide();
                    }
                }).include(attributes);

        dialog.setWidth(640);
        dialog.setHeight(480);
        dialog.setWidget(addDialog);
        dialog.setGlassEnabled(true);
        dialog.center();
    }
747222
public Crud<T, K> table(String table) {
        return new LazyCrud<T, K>(this, table);
    }
354211
private void populateComparableKeyRecord(GenericRecord source, GenericRecord target) {
    for (Field field : target.getSchema().getFields()) {
      if (field.schema().getType() == Schema.Type.UNION) {

        // Since a UNION has multiple types, we need to use induce() to get the actual type in the record.
        Object fieldData = source.get(field.name());
        Schema actualFieldSchema = GenericData.get().induce(fieldData);
        if (actualFieldSchema.getType() == Schema.Type.RECORD) {

          // If the actual type is RECORD (which may contain another UNION), we need to recursively
          // populate it.
          for (Schema candidateType : field.schema().getTypes()) {
            if (candidateType.getFullName().equals(actualFieldSchema.getFullName())) {
              GenericRecord record = new GenericData.Record(candidateType);
              target.put(field.name(), record);
              populateComparableKeyRecord((GenericRecord) fieldData, record);
              break;
            }
          }
        } else {
          target.put(field.name(), source.get(field.name()));
        }
      } else if (field.schema().getType() == Schema.Type.RECORD) {
        GenericRecord record = (GenericRecord) target.get(field.name());
        if (record == null) {
          record = new GenericData.Record(field.schema());
          target.put(field.name(), record);
        }
        populateComparableKeyRecord((GenericRecord) source.get(field.name()), record);
      } else {
        target.put(field.name(), source.get(field.name()));
      }
    }
  }
913724
function Repository(T)
{
  var mapper = this._mapper = new Mapper(T);
  this._toMany = function(x) { return mapper.toMany(x); };
  this._toSingle = function(x) { return mapper.toSingle(x); };

  // Implementation pointers
  this._get    = null;
  this._getAll = null;
  this._query  = null;
  this._add    = null;
  this._remove = null;
  this._fetch  = null;
  this._update = null;

  this._transforms = [];
}
75001
function createDbTable(t, dbInfo, callback, errorCallback) {
    t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
}
104900
def crud_for_model(model, urlprefix=None):
    
    model_lower = model.__name__.lower()

    if urlprefix is None:
        urlprefix = ''
    urlprefix += model_lower + '/'

    urls = crud_urls(
        model,
        list_view=CRUDListView.as_view(model=model),
        create_view=CRUDCreateView.as_view(model=model),
        detail_view=CRUDDetailView.as_view(model=model),
        update_view=CRUDUpdateView.as_view(model=model),
        delete_view=CRUDDeleteView.as_view(model=model),
        url_prefix=urlprefix,
    )
    return urls
588679
function (values, schema, options, callback) {
    var newValues = {}
        , errors = []
        , modelList = find(schema)
        , val;

    for (var model in modelList) {
        if (_.isArray(modelList[model])) {

            if (values === undefined) {
                val = undefined;
            }
            else {
                val = values[model];
            }

            // Empty array defined in schema
            if (_.isEmpty(modelList[model])) {
                if (val) {
                    newValues[model] = val;
                }
            }
            else {
                // Set value to empty array if empty given
                if (val == undefined) {
                    if (options && options.partial == true) {
                        // Do nothing
                    }
                    else {
                        newValues[model] = [];
                    }
                }
                else {
                    // Sub model defined in schema
                    for (var thisSubSchema in modelList[model]) {
                        if (_.isArray(val)) {
                            for (var thisValue in val) {

                                // Check if type array or plain array
                                if (typeof val[thisValue] == "object") {
                                    modelCompare(val[thisValue], modelList[model][thisSubSchema], options, function (err, data) {
                                        if (err) {
                                            errors = _.union(errors, err);
                                        }
                                        if (data !== null) {
                                            if (!newValues[model]) {
                                                newValues[model] = [];
                                            }
                                            newValues[model][thisValue] = data;
                                        }
                                    });
                                }
                                else {
                                    rulesMatch(thisValue, val[thisValue], modelList[model][thisSubSchema], options, function (err, data) {
                                        if (err) {
                                            errors.push(err);
                                        }
                                        if (data !== undefined) {
                                            if (!newValues[model]) {
                                                newValues[model] = [];
                                            }
                                            newValues[model][thisValue] = data;
                                        }
                                    });
                                }
                            }
                        }
                        else {
                            modelCompare(val, modelList[model][thisSubSchema], options, function (err, data) {
                                if (err) {
                                    errors = _.union(errors, err);
                                }
                                if (data !== null) {
                                    newValues[model] = data;
                                }
                            });
                        }
                    }
                }
            }
        } else {
            // Check for definition of {} in model to allow any data for this node without validation
            if (_.isEmpty(modelList[model])) {
                for (var index in values) {
                    var filter = new RegExp("^" + model);
                    if (index.match(filter)) {
                        newValues[index] = values[index];
                    }
                }
            }
            else {
                if (values === undefined) {
                    val = undefined;
                }
                else {
                    val = values[model];
                }

                rulesMatch(model, val, modelList[model], options, function (err, data) {
                    if (err) {
                        errors.push(err);
                    }
                    if (data !== undefined) {
                        newValues[model] = data;
                    }
                });
            }
        }
    }

    if (_.isEmpty(errors)) {
        errors = null;
    }
    else {
        errors = {name: 'ValidationError', err: errors};
    }
    if (_.isEmpty(newValues)) {
        newValues = null;
    }
    callback(errors, newValues);
}
325289
protected function _crud()
    {
        if (!$this->_controller->Crud) {
            return $this->_controller->components()->load('Crud.Crud');
        }

        return $this->_controller->Crud;
    }
194866
public void addCrudService(Class clazz, BundleContext bundleContext, JcrRepository repository) throws RepositoryException {
        jcrom.map(clazz);
        JcrCrudService<? extends Object> jcromCrudService;
        jcromCrudService = new JcrCrudService<>(repository, jcrom, clazz);
        crudServiceRegistrations.put(jcromCrudService, registerCrud(bundleContext, jcromCrudService));
    }
1043164
public static <T> GenericResponseBuilder<T> created(T entity, URI location) {
    return genericResponseBuilderFactory.create(Response.Status.CREATED.getStatusCode(), entity)
        .location(location);
  }
1082513
private void generateInsert(SQLiteDatabaseSchema schema) {
		// method sign
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("insert").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(Uri.class);
		methodBuilder.addParameter(Uri.class, "uri");
		methodBuilder.addParameter(ContentValues.class, "contentValues");

		boolean hasOperation = hasOperationOfType(schema, methodBuilder, JQLType.INSERT);

		if (!hasOperation) {
			methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.DELETE);
			classBuilder.addMethod(methodBuilder.build());
			return;
		}

		defineJavadocHeaderForContentOperation(methodBuilder, "insert");

		// method code
		methodBuilder.addStatement("long _id=-1");
		methodBuilder.addStatement("$T _returnURL=null", Uri.class);
		methodBuilder.beginControlFlow("switch (sURIMatcher.match(uri))");
		for (Entry<String, ContentEntry> item : uriSet.entrySet()) {
			if (item.getValue().insert == null)
				continue;

			defineJavadocForContentUri(methodBuilder, item.getValue().insert);

			methodBuilder.beginControlFlow("case $L:", item.getValue().pathIndex);
			methodBuilder.addStatement("_id=dataSource.get$L().$L(uri, contentValues)", item.getValue().insert.getParent().getName(), item.getValue().insert.contentProviderMethodName);
			methodBuilder.addStatement("_returnURL=Uri.withAppendedPath(uri, String.valueOf(_id))");

			methodBuilder.addStatement("break");
			methodBuilder.endControlFlow();
		}

		defineJavadocFooterForContentOperation(methodBuilder);

		methodBuilder.beginControlFlow("default:");
		methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.INSERT);
		methodBuilder.endControlFlow();

		methodBuilder.endControlFlow();

		if (hasOperation) {

			if (schema.generateLog) {
				// generate log section - BEGIN
				methodBuilder.addComment("log section for content provider insert BEGIN");
				methodBuilder.beginControlFlow("if (dataSource.isLogEnabled())");

				methodBuilder.addStatement("$T.info(\"Element is created with URI '%s'\", _returnURL)", Logger.class);
				methodBuilder.addStatement("$T.info(\"Changes are notified for URI '%s'\", uri)", Logger.class);

				// generate log section - END
				methodBuilder.endControlFlow();
				methodBuilder.addComment("log section for content provider insert END");
			}
			methodBuilder.addStatement("getContext().getContentResolver().notifyChange(uri, null)");
			methodBuilder.addStatement("return _returnURL");
		}

		classBuilder.addMethod(methodBuilder.build());

	}
1291374
private GenericData map2GenericData(GenericData gdo, Map<String, Object> map) {
        for (Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() == null) {
                if (entry.getKey().equals(AuditEvent.TARGET_APPNAME)) {
                    gdo.addPair(entry.getKey(), AuditUtils.getJ2EEComponentName());
                }
            } else {
                gdo.addPair(entry.getKey(), entry.getValue().toString());
            }
        }
        if (tc.isDebugEnabled()) {
            Tr.debug(tc, "gdo: " + gdo.toString());
        }
        return gdo;
    }
797224
function(api, modelDefinition) {
		this.parentAPI = api;
		this.childModels = [];

		this.initialized = false;

		this.model = modelDefinition.model;
		this.path = this.model.tableName.toLowerCase();
		this.modelRouter = Express.Router();
		this.primaryKey = Helpers.getPrimaryKey(this.model);

		/**
		 * Array of valid columns in the class minus the primary key
		 * However the primary key is only 'not valid' to be set if it is
		 * marked as auto-generated.
		 */
		this.validColumns = _.keys(this.model.rawAttributes);

		if(this.model.rawAttributes[this.primaryKey]._autoGenerated)
			this.validColumns.splice(this.validColumns.indexOf(this.primaryKey), 1);

		this._initializeOptions(modelDefinition);
		this._initializeAssociationOptions(modelDefinition);
		this._initializeRoutes(modelDefinition);

		this.filter = Helpers.mergeTriplicate({
			// If this is filled out, don't allow these parameters to be used.
			blacklist: [],

			// If this is filled out, ONLY allow these parameters to be used.
			whitelist: [],

			// Include these fields in output
			include: [],

			// Exclude these fields from output
			exclude: []
		}, this.model.filter || {}, modelDefinition.filter || {});
	}
1017822
public function editAction(Request $request, $id)
    {
        $configuration = $this->getConfiguration($request);
        $dispatcher = $configuration->getEventDispatcher();
        $om = $this->getObjectManager();

        if (!$configuration->getFormType()) {
            throw new \RuntimeException('You must set the formType on the CRUD configuration');
        }

        $object = $this->findObject($request, $id);
        $form = $this->createForm($configuration->getFormType(), $object, $configuration->getFormOptions());

        $event = new PreSubmitEvent($configuration, $request, $object, $form);
        $dispatcher->dispatch(CrudEvents::PRE_SUBMIT, $event);

        if ($event->hasResponse()) {
            return $event->getResponse();
        }

        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $om->persist($object);

                $event = new PreFlushEvent($configuration, $request, $object);
                $dispatcher->dispatch(CrudEvents::PRE_FLUSH, $event);

                if ($event->hasResponse()) {
                    return $event->getResponse();
                }

                $event = new PostFlushEvent($configuration, $request, $object);

                try {
                    $om->flush();
                    $this->addFlash('success', sprintf('flash.%s.edit.success', $configuration->getName()));
                } catch (\Exception $e) {
                    $event->setException($e);
                    $this->addFlash('error', sprintf('flash.%s.edit.error', $configuration->getName()));
                }

                $dispatcher->dispatch(CrudEvents::POST_FLUSH, $event);

                if ($event->hasResponse()) {
                    return $event->getResponse();
                }

                return $this->redirectToRoute(
                    $configuration->getRoutePrefix() . 'index',
                    $configuration->getRouteParameters()
                );
            } else {
                $event = new ValidationFailedEvent($configuration, $request, $object, $form);
                $dispatcher->dispatch(CrudEvents::VALIDATION_FAILED, $event);

                if ($event->hasResponse()) {
                    return $response;
                }
            }
        }

        return $this->render($this->getTemplate($request, 'edit'), array_merge([
            'base_template' => $this->getTemplate($request, 'base'),
            'config' => $configuration,
            'form'   => $form->createView(),
            'object' => $object,
        ], $configuration->getTemplateVariables()));
    }
932914
protected function genericUpdateSeo(ModelCriteria $query, UpdateSeoEvent $event, EventDispatcherInterface $dispatcher = null)
    {
        if (null !== $object = $query->findPk($event->getObjectId())) {
            $object
                //for backward compatibility
                ->setDispatcher($dispatcher !== null ? $dispatcher : $event->getDispatcher())

                ->setLocale($event->getLocale())
                ->setMetaTitle($event->getMetaTitle())
                ->setMetaDescription($event->getMetaDescription())
                ->setMetaKeywords($event->getMetaKeywords())

                ->save()
            ;

            // Update the rewritten URL, if required
            try {
                $object->setRewrittenUrl($event->getLocale(), $event->getUrl());
            } catch (UrlRewritingException $e) {
                throw new FormValidationException($e->getMessage(), $e->getCode());
            }

            $event->setObject($object);
        }

        return $object;
    }
214533
private static <T, ID, I extends GenericDAO<T, ID>> Class<? extends I> completeDAO(Class<T> modelClass,
                                                                                       Class<I> daoInterface,
                                                                                       Class<? extends QueryModelDAO<T, ID>> partialDAOClass,
                                                                                       boolean accessControlEnabled,
                                                                                       boolean metricsEnabled) {
        try {
            ClassPool pool = ClassPool.getDefault();

            pool.insertClassPath(new ClassClassPath(daoInterface));

            CtClass fullDAOCtClass = pool.makeClass(String.format("%s$%d", daoInterface.getName(), count.incrementAndGet()));
            CtClass partialDAOCtClass = pool.get(partialDAOClass.getName());
            CtClass daoInterfaceCtClass = pool.get(daoInterface.getName());

            fullDAOCtClass.setSuperclass(partialDAOCtClass);
            fullDAOCtClass.addInterface(daoInterfaceCtClass);

            buildConstructor(fullDAOCtClass, accessControlEnabled);
            buildNeededMethods(fullDAOCtClass, partialDAOCtClass, daoInterfaceCtClass, modelClass, accessControlEnabled, metricsEnabled);

            return ClassLoadingUtil.toClass(fullDAOCtClass);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
160866
public function replaceTemplateTypesWithStandins(
        array &$template_types,
        array &$generic_params,
        Codebase $codebase = null,
        Type\Union $input_type = null,
        bool $replace = true,
        bool $add_upper_bound = false,
        int $depth = 0
    ) {
        $keys_to_unset = [];

        foreach ($this->types as $key => $atomic_type) {
            if ($atomic_type instanceof Type\Atomic\TTemplateParam
                && isset($template_types[$key][$atomic_type->defining_class ?: ''])
            ) {
                $template_type = $template_types[$key][$atomic_type->defining_class ?: ''][0];

                if ($template_type->getId() !== $key) {
                    $replacement_type = $template_type;

                    if ($replace) {
                        if ($replacement_type->hasMixed()
                            && !$atomic_type->as->hasMixed()
                        ) {
                            foreach ($atomic_type->as->getTypes() as $as_atomic_type) {
                                $this->types[$as_atomic_type->getKey()] = clone $as_atomic_type;
                            }
                        } else {
                            foreach ($replacement_type->getTypes() as $replacement_atomic_type) {
                                $this->types[$replacement_atomic_type->getKey()] = clone $replacement_atomic_type;
                            }

                            foreach ($replacement_type->getTypes() as $replacement_key => $_) {
                                if ($replacement_key !== $key) {
                                    $keys_to_unset[] = $key;
                                }
                            }
                        }

                        if ($input_type) {
                            $generic_param = clone $input_type;
                            $generic_param->setFromDocblock();

                            if (isset($generic_params[$key][$atomic_type->defining_class ?: ''][0])) {
                                $existing_depth = $generic_params[$key][$atomic_type->defining_class ?: ''][1] ?? -1;
                                if ($existing_depth > $depth) {
                                    continue;
                                }

                                if ($existing_depth === $depth) {
                                    $generic_param = Type::combineUnionTypes(
                                        $generic_params[$key][$atomic_type->defining_class ?: ''][0],
                                        $generic_param,
                                        $codebase
                                    );
                                }
                            }

                            $generic_params[$key][$atomic_type->defining_class ?: ''] = [
                                $generic_param,
                                $depth
                            ];
                        }
                    } elseif ($add_upper_bound && $input_type) {
                        if ($codebase
                            && TypeAnalyzer::isContainedBy(
                                $codebase,
                                $input_type,
                                $replacement_type
                            )
                        ) {
                            $template_types[$key][$atomic_type->defining_class ?: ''][0] = clone $input_type;
                        }
                    }
                }
            } elseif ($atomic_type instanceof Type\Atomic\TTemplateParamClass
                && isset($template_types[$atomic_type->param_name])
            ) {
                if ($replace) {
                    $class_string = new Type\Atomic\TClassString($atomic_type->as, $atomic_type->as_type);

                    $keys_to_unset[] = $key;

                    $this->types[$class_string->getKey()] = $class_string;

                    if ($input_type) {
                        $valid_input_atomic_types = [];

                        foreach ($input_type->getTypes() as $input_atomic_type) {
                            if ($input_atomic_type instanceof Type\Atomic\TLiteralClassString) {
                                $valid_input_atomic_types[] = new Type\Atomic\TNamedObject(
                                    $input_atomic_type->value
                                );
                            } elseif ($input_atomic_type instanceof Type\Atomic\TTemplateParamClass) {
                                $valid_input_atomic_types[] = new Type\Atomic\TTemplateParam(
                                    $input_atomic_type->param_name,
                                    $input_atomic_type->as_type
                                        ? new Union([$input_atomic_type->as_type])
                                        : ($input_atomic_type->as === 'object'
                                            ? Type::getObject()
                                            : Type::getMixed())
                                );
                            } elseif ($input_atomic_type instanceof Type\Atomic\TClassString) {
                                if ($input_atomic_type->as_type) {
                                    $valid_input_atomic_types[] = clone $input_atomic_type->as_type;
                                } elseif ($input_atomic_type->as !== 'object') {
                                    $valid_input_atomic_types[] = new Type\Atomic\TNamedObject(
                                        $input_atomic_type->as
                                    );
                                }
                            }
                        }

                        if ($valid_input_atomic_types) {
                            $generic_param = new Union($valid_input_atomic_types);
                            $generic_param->setFromDocblock();
                        } else {
                            $generic_param = Type::getMixed();
                        }

                        $generic_params[$atomic_type->param_name][$atomic_type->defining_class ?: ''] = [
                            $generic_param,
                            $depth
                        ];
                    }
                }
            } else {
                $matching_atomic_type = null;

                if ($input_type && $codebase) {
                    foreach ($input_type->types as $input_key => $atomic_input_type) {
                        if ($input_key === $key) {
                            $matching_atomic_type = $atomic_input_type;
                            break;
                        }

                        if ($input_key === 'Closure' && $key === 'callable') {
                            $matching_atomic_type = $atomic_input_type;
                            break;
                        }

                        if (($atomic_input_type instanceof Type\Atomic\TArray
                                || $atomic_input_type instanceof Type\Atomic\ObjectLike)
                            && $key === 'iterable'
                        ) {
                            $matching_atomic_type = $atomic_input_type;
                            break;
                        }

                        if (strpos($input_key, $key . '&') === 0) {
                            $matching_atomic_type = $atomic_input_type;
                            break;
                        }

                        if ($key === 'callable') {
                            $matching_atomic_type = TypeAnalyzer::getCallableFromAtomic(
                                $codebase,
                                $atomic_input_type
                            );

                            if ($matching_atomic_type) {
                                break;
                            }
                        }

                        if ($atomic_input_type instanceof TNamedObject && $atomic_type instanceof TNamedObject) {
                            try {
                                $classlike_storage =
                                    $codebase->classlike_storage_provider->get($atomic_input_type->value);

                                if ($atomic_input_type instanceof TGenericObject
                                    && isset($classlike_storage->template_type_extends[strtolower($key)])
                                ) {
                                    $matching_atomic_type = $atomic_input_type;
                                    break;
                                }

                                if (isset($classlike_storage->template_type_extends[strtolower($key)])) {
                                    $extends_list = $classlike_storage->template_type_extends[strtolower($key)];

                                    $new_generic_params = [];

                                    foreach ($extends_list as $key => $value) {
                                        if (is_string($key)) {
                                            $new_generic_params[] = $value;
                                        }
                                    }

                                    $matching_atomic_type = new TGenericObject(
                                        $atomic_input_type->value,
                                        $new_generic_params
                                    );
                                    break;
                                }
                            } catch (\InvalidArgumentException $e) {
                                // do nothing
                            }
                        }
                    }
                }

                $atomic_type->replaceTemplateTypesWithStandins(
                    $template_types,
                    $generic_params,
                    $codebase,
                    $matching_atomic_type,
                    $replace,
                    $add_upper_bound,
                    $depth + 1
                );
            }
        }

        if ($replace) {
            foreach ($keys_to_unset as $key) {
                unset($this->types[$key]);
            }

            if (!$this->types) {
                throw new \UnexpectedValueException('Cannot remove all keys');
            }

            $this->id = null;
        }
    }