Generate constructor.

@param schema
the schema
431555
private void generateConstructor(SQLiteDatabaseSchema schema) {
		// constructor
		MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder()
				.addParameter(DataSourceOptions.class, "options").addModifiers(Modifier.PROTECTED);
		methodBuilder.addStatement("super($S, $L, options)", schema.fileName, schema.version);
		classBuilder.addMethod(methodBuilder.build());
	}
705818
function instantiate(schema, options) {
  options = options || {};

  /**
   * Visits each sub-object using recursion.
   * If it reaches a primitive, instantiate it.
   * @param obj - The object that represents the schema.
   * @param name - The name of the current object.
   * @param data - The instance data that represents the current object.
   */
  function visit(obj, name, data) {
    if (!obj) {
      return;
    }

    var i;
    var type = getObjectType(obj);

    // We want non-primitives objects (primitive === object w/o properties).
    if (type === 'object' && obj.properties) {
      data[name] = data[name] || { };

      // Visit each property.
      for (var property in obj.properties) {
        if (obj.properties.hasOwnProperty(property)) {
          if (shouldVisit(property, obj, options)) {
            visit(obj.properties[property], property, data[name]);
          }
        }
      }
    } else if (obj.allOf) {
      for (i = 0; i < obj.allOf.length; i++) {
        visit(obj.allOf[i], name, data);
      }
    } else if (obj.$ref) {
      obj = findDefinition(schema, obj.$ref);
      visit(obj, name, data);
    } else if (type === 'array') {
      data[name] = [];
      var len = 0;
      if (obj.minItems || obj.minItems > 0) {
        len = obj.minItems;
      }

      // Instantiate 'len' items.
      for (i = 0; i < len; i++) {
        visit(obj.items, i, data[name]);
      }
    } else if (isEnum(obj)) {
      data[name] = instantiateEnum(obj);
    } else if (isPrimitive(obj)) {
      data[name] = instantiatePrimitive(obj);
    }
  }

  var data = {};
  visit(schema, 'kek', data);
  return data['kek'];
}
879201
protected function generateDataTypes(array $schema)
    {
        $directory = $this->getMappingDirectory('DataType');
        foreach ($schema['datatypes'] as $dataType => $data) {
            $this->generateDataType($dataType, $data, $directory);
        }
    }
1366977
protected void setSchema(final String schema) throws DatabaseEngineException {
        try {
            this.conn.setSchema(schema);
        } catch (final Exception e) {
            throw new DatabaseEngineException(String.format("Could not set current schema to '%s'", schema), e);
        }
    }
692673
protected void createSQLDaoDefinition(SQLiteDatabaseSchema schema,
			final Map<String, TypeElement> globalBeanElements, final Map<String, TypeElement> globalDaoElements,
			String daoItem) {
		Element daoElement = globalDaoElements.get(daoItem);

		if (daoElement.getKind() != ElementKind.INTERFACE) {
			String msg = String.format("Class %s: only interfaces can be annotated with @%s annotation",
					daoElement.getSimpleName().toString(), BindDao.class.getSimpleName());
			throw (new InvalidKindForAnnotationException(msg));
		}

		M2MEntity entity = M2MEntity.extractEntityManagedByDAO((TypeElement) daoElement);

		// add to current schema generated entities too
		for (GeneratedTypeElement genItem : this.generatedEntities) {
			if (genItem.getQualifiedName().equals(entity.getQualifiedName())) {
				schema.generatedEntities.add(genItem);
			}
		}

		boolean generated = daoElement.getAnnotation(BindGeneratedDao.class) != null;

		final SQLiteDaoDefinition currentDaoDefinition = new SQLiteDaoDefinition(schema, daoItem,
				(TypeElement) daoElement, entity.getClassName().toString(), generated);

		// content provider management
		BindContentProviderPath daoContentProviderPath = daoElement.getAnnotation(BindContentProviderPath.class);
		if (daoContentProviderPath != null) {
			currentDaoDefinition.contentProviderEnabled = true;
			currentDaoDefinition.contentProviderPath = daoContentProviderPath.path();
			currentDaoDefinition.contentProviderTypeName = daoContentProviderPath.typeName();

			if (StringUtils.isEmpty(currentDaoDefinition.contentProviderTypeName)) {
				Converter<String, String> convert = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_UNDERSCORE);
				AssertKripton.assertTrue(currentDaoDefinition.getParent().contentProvider != null,
						"DAO '%s' has an inconsistent content provider definition, perhaps you forget to use @%s in data source interface?",
						currentDaoDefinition.getElement().getQualifiedName(),
						BindContentProvider.class.getSimpleName());
				currentDaoDefinition.contentProviderTypeName = currentDaoDefinition
						.getParent().contentProvider.authority + "."
						+ convert.convert(currentDaoDefinition.getSimpleEntityClassName());
			}
		}

		// dao is associated to an entity is not contained in analyzed class
		// set.
		if (!globalBeanElements.containsKey(currentDaoDefinition.getEntityClassName())
				&& !isGeneratedEntity(currentDaoDefinition.getEntityClassName())) {
			throw (new InvalidBeanTypeException(currentDaoDefinition));
		}

		schema.add(currentDaoDefinition);

		fillMethods(currentDaoDefinition, daoElement);

		// get @annotation associated to many 2 many relationship
		BindDaoMany2Many daoMany2Many = daoElement.getAnnotation(BindDaoMany2Many.class);

		// dao definition must have >0 method associated to query
		if (currentDaoDefinition.getCollection().size() == 0 && daoMany2Many == null) {
			throw (new DaoDefinitionWithoutAnnotatedMethodException(currentDaoDefinition));
		}
	}
1334782
function _constructor(self, opts) {
			var tmp;

			// Check opts validity
			var validity = SchemaObject.validate(opts, copy_definition);
			if(!validity.valid) { throw new TypeError("bad argument: " + util.inspect(validity) ); }

			// Call parent constructors
			ParentType.call(self, opts);

			// Call custom constructors
			//util.debug( util.inspect( _user_defined_constructors ));
			if(Object.prototype.hasOwnProperty.call(_user_defined_constructors, type_name)) {
				tmp = _user_defined_constructors[type_name].call(self, opts);
				if(is.def(tmp)) {
					SchemaObject.prototype._setValueOf.call(self, tmp);
				}
				//util.debug( util.inspect( tmp ) );
			}

			// Setup getters and setters if schema has properties
			//util.debug( "\ndefinition = \n----\n" + util.inspect( definition ) + "\n----\n\n" );
			if(definition && definition.properties) {
				Object.getOwnPropertyNames(definition.properties).forEach(function(key) {
					self.__defineGetter__(key, function(){
						return self.valueOf()[key];
					});
					self.__defineSetter__(key, function(val){
						// FIXME: Implement value validation and do not use `.valueOf()`!
						self.valueOf()[key] = val;
					});
				});
			}

		}
224747
function init(schema, name) {  // {{{2
/**
 * Kind constructor
 *
 * @param schema {Object|String} Schema containing the kind
 * @param name {String} Unique kind name within the schema
 *
 * @method constructor
 */

  this.name = name;  // {{{3
  /**
   * Kind name unique within a schema
   *
   * @property name
   * @type String
   */


  this.schema = typeof schema === 'string' ?  // {{{3
    O.data.schemas[schema] :
    schema
  ;
  /**
   * Schema to which the kind is assigned
   *
   * @property schema
   * @type Object
   */

  if (! this.schema) {
    throw O.log.error('Missing schema', schema);
  }

  if (this.name in this.schema.kinds) {
    throw O.log.error(this.schema, 'Duplicit kind', this.name);
  }

  this.schema.kinds[this.name] = this;

  // }}}3

//  O.callChain(this, 'init')();

//  console.log('KIND INIT', this.schema.name, this.name);
}
639125
function findOneOrCreatePlugin(schema) {
    schema.statics.findOneOrCreate = function findOneOrCreate(condition, doc, callback) {
        var self = this;

        self.findOne(condition, function(err, result ) {
            if (result) {
                callback(err, result);
            } else {
                self.create(doc, function(err, result) {
                    callback(err, result);
                });
            }
        });
    };
}
345443
protected function generateClasses(array $schema)
    {
        $this->generateDataTypes($schema);
        $this->generateProperties($schema);
        $this->generateTypes($schema);
    }
620377
Schema schema() {
    if (schema == null) {
      synchronized (this) {
        if (schema == null) {
          schema = new Schema(datasource, context, strictTraceId);
        }
      }
    }
    return schema;
  }
907022
function Schema(options, descriptors) {

    if (!descriptors) {
        descriptors = options;
        options = null;
    }

    function opt(name, type) {
        var value = options[name];
        if (value !== undefined) {
            if (typeof value === type) return value;
            else throw new TypeError(current + 'options : ' + name + ': "' +
                value + '" is not of type [' + type + ']');
        }
        else return false;
    }

    var current = 'Schema: arguments: ',
        defaults = { required: false };

    if (hasValue(options)) {
        if (type(options) === 'object') {
            defaults.required = opt('required', 'boolean');
            if (opt('validator', 'function')) defaults.validator = options.validator;
        }
        else throw new TypeError(current + 'options: must be of type [object]');
    }

    current += 'descriptors: ';
    if (typeof descriptors !== 'object')
        throw new TypeError(current + 'must be of type [object]');
    if (!Array.isArray(descriptors)) {
        descriptors = this.toDescriptors(descriptors, defaults);
    }
    if (options && options.extends instanceof Schema) {
        descriptors = this.extendDescriptors(descriptors, options.extends.descriptors);
    }
    if (!descriptors.length)
        throw new TypeError(current + 'contains no values');
    else if (!(descriptors[0] instanceof Descriptor)) {
        throw new TypeError(current + 'must be instances of Descriptor class');
    }
    var instance = this;
    this.descriptors = descriptors;

}
809327
private void generateSchema(Class clazz) {
    try {
      File targetFile = new File(getGeneratedResourcesDirectory(), clazz.getName() + ".json");
      getLog().info("Generate JSON schema: " + targetFile.getName());
      SchemaFactoryWrapper schemaFactory = new SchemaFactoryWrapper();
      OBJECT_MAPPER.acceptJsonFormatVisitor(OBJECT_MAPPER.constructType(clazz), schemaFactory);
      JsonSchema jsonSchema = schemaFactory.finalSchema();
      OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValue(targetFile, jsonSchema);
    }
    catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }
634133
protected void _generate(SarlConstructor constructor, PyAppendable it, IExtraLanguageGeneratorContext context) {
		if (constructor.isStatic()) {
			generateExecutable("___static_init___", constructor, false, false, null, //$NON-NLS-1$
					getTypeBuilder().getDocumentation(constructor),
					it, context);
			it.newLine().append("___static_init___()"); //$NON-NLS-1$
		} else {
			generateExecutable("__init__", constructor, true, false, null, //$NON-NLS-1$
					getTypeBuilder().getDocumentation(constructor),
					it, context);
		}
	}
1183940
static JsonSchema initializeFromSource(final Map<String, Object> source) {

		final Object idValue = source.get(JsonSchema.KEY_ID);
		URI id               = null;

		if (idValue != null) {

			try {

				id = new URI(idValue.toString());

			} catch (URISyntaxException ex) {
				logger.warn("", ex);
			}
		}

		final StructrSchemaDefinition schema = new StructrSchemaDefinition(id);
		schema.deserialize(source);

		return schema;
	}
578101
public void generateSchema(Class... classes)
        throws JAXBException, IOException {
        if (!baseDir.exists()) {
            baseDir.mkdirs();
        }

        JAXBContext context = JAXBContext.newInstance(classes);
        context.generateSchema(this);
    }
1308271
public static void generate(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws IOException {
		String className = schema.getName();

		String dataSourceName = PREFIX + className;

		className = className.replaceAll(BindDataSourceBuilder.SUFFIX, SUFFIX);
		className = PREFIX + className;

		PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
		String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, className);

		//@formatter:off
		builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT)
				.addTypeVariable(TypeVariableName.get("I"))
				.addTypeVariable(TypeVariableName.get("U"))
				.addTypeVariable(TypeVariableName.get("R"));
		//@formatter:on

		// javadoc
		builder.addJavadoc("\n<p>\nSpecialized async task to make async database operation on activity\n</p>\n");
		builder.addJavadoc("\n<p>\nUnlike standard async task, for an instance of this class can be used many time.\n</p>\n");
		builder.addJavadoc("\n<p>\nWhen method <code>execute</code> is invoked, an inner async task is created.\n</p>\n\n");
		JavadocUtility.generateJavadocGeneratedBy(builder);
		builder.addJavadoc("@param I input param\n");
		builder.addJavadoc("@param U update param\n");
		builder.addJavadoc("@param R result param\n\n");
		builder.addJavadoc("@see $T\n", className(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)));
		builder.addJavadoc("@see $T\n", className(dataSourceName));
		builder.addJavadoc("@see $T\n", BindAsyncTaskType.class);

		// build constructors
		builder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addStatement("this($T.READ)", BindAsyncTaskType.class)
				.addJavadoc("<p>\nWith this constructor, a read only database connection will be used\n</p>\n").build());

		builder.addMethod(
				MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addJavadoc("<p>\nWith this constructor it is possible to specify which type of database use in async task\n</p>\n\n")
						.addJavadoc("@param mode allows to specify if and how open a data source connection\n").addParameter(BindAsyncTaskType.class, "mode").addCode("this.mode = mode;").build());

		// define fields
		{
			FieldSpec.Builder fieldSpec = FieldSpec.builder(BindAsyncTaskType.class, "mode", Modifier.PROTECTED);
			fieldSpec.addJavadoc("Allows to specify how async task interacts with data source.\n\n");
			builder.addField(fieldSpec.build());
		}

		{
			ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.typeName("I"), TypeUtility.typeName("U"),
					TypeUtility.typeName("R"));
			FieldSpec.Builder fieldSpec = FieldSpec.builder(parameterizedTypeName, "asyncTask", Modifier.PROTECTED);
			fieldSpec.addJavadoc("Async task wrapped by this class\n\n");
			builder.addField(fieldSpec.build());
		}

		// build methods
		builder.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addJavadoc("Use this method for operations on UI-thread before start execution\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onExecute").returns(TypeUtility.typeName("R")).addParameter(TypeUtility.typeName(dataSourceName), "dataSource")
				.addJavadoc(
						"Method used to encapsulate operations on datasource\n\n@param dataSource\n\tuse it to retrieve DAO\n@return\n\tresult of operation (list, bean, etc) and execute transactions.\n")
				.addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT).addException(Throwable.class).build());
		builder.addMethod(MethodSpec.methodBuilder("onFinish").addParameter(TypeUtility.typeName("R"), "result").addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT)
				.addJavadoc("Use this method for operations on UI-thread after execution\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onProgressUpdate").addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.typeName("U")), "update").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
				.varargs().addJavadoc("Override this method to KRIPTON_DEBUG operation progress on UI-Thread\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onError").addParameter(Throwable.class, "exception").addModifiers(Modifier.PUBLIC)
				.addJavadoc("This method is invoked when <code>onExecute</code> method generate an exception.\n@param exception exception generated\n")
				.addStatement("$T.error(exception.getMessage())", Logger.class).addStatement("exception.printStackTrace()").build());

		// method execute1
		{
			MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("execute")
					.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
							.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
					.varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");

			executeBuilder.addStatement("executeOnExecutor($T.SERIAL_EXECUTOR, params)", android.os.AsyncTask.class);
			builder.addMethod(executeBuilder.build());
		}

		// method execute2
		{
			MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("executeOnExecutor").addParameter(Executor.class, "executor")
					.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
							.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
					.varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");

		//@formatter:off
		TypeSpec.Builder anonymous = TypeSpec.anonymousClassBuilder("")
				.addSuperinterface(ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.className("I"), TypeUtility.className("U"), TypeUtility.className("R")));
		anonymous.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addStatement("$L.this.onPreExecute()",className).build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("doInBackground").addModifiers(Modifier.PUBLIC).returns(TypeUtility.typeName("R")).addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
						.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value","$S", "unchecked").build())
						.build()).varargs(true)
				.addStatement("$L dataSource=$L.getInstance()", dataSourceName, dataSourceName)
				.addStatement("R result=null")
				.addStatement("boolean needToOpened=false")
				.addCode("if (mode==$T.READ) { needToOpened=true; dataSource.openReadOnlyDatabase(); } else if (mode==$T.READ_WRITE) { needToOpened=true; dataSource.openWritableDatabase();}\n", BindAsyncTaskType.class,BindAsyncTaskType.class)
				//.addStatement("$T sqlite=readOnlyTask ? dataSource.getReadableDatabase() : dataSource.getWritableDatabase()", SQLiteDatabase.class)
				.beginControlFlow("try")
				.addStatement("result=onExecute(dataSource)")
				.nextControlFlow("catch(Throwable e)")
					.addStatement("onError(e)")
				.nextControlFlow("finally")
					.beginControlFlow("if (needToOpened)")
					.addStatement("dataSource.close()")
					.endControlFlow()
				.endControlFlow()
				.addStatement("return result").build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("onProgressUpdate")
				.addModifiers(Modifier.PUBLIC)
				.addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("U"))
						, "values")
						.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value","$S", "unchecked").build())
						.build())
				.varargs(true)
				.addStatement("$L.this.onProgressUpdate(values)", className)
				.build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("onPostExecute")
				.addModifiers(Modifier.PUBLIC)
				.addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(TypeUtility.className("R"), "result").build())
				.addStatement("$L.this.onFinish(result)",className)
				.build());
		//@formatter:on

		//@formatter:off
		executeBuilder.addStatement("asyncTask=$L", anonymous.build());		
		executeBuilder.addStatement("asyncTask.executeOnExecutor(executor, params)", anonymous.build());
		builder.addMethod(executeBuilder.build());		
					
		anonymous.addMethod(MethodSpec.methodBuilder("cancel")
				.addModifiers(Modifier.PUBLIC)
				.addModifiers(Modifier.FINAL)
				.addParameter(Boolean.TYPE, "mayInterruptIfRunning")
				.beginControlFlow("if (asyncTask!=null, args)")
				.addStatement("return asyncTask.cancel(mayInterruptIfRunning)")
				.endControlFlow()
				.addStatement("return false").build());
		}

		
		// build SimpleAsyncTask
		builder.addType(TypeSpec.classBuilder("Simple")
				.addJavadoc("Simple implementation of async task. It uses read only database.\n\n")
				.addJavadoc("@see $T\n", TypeUtility.typeName(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)))
				.addJavadoc("@see $T\n", TypeUtility.typeName(dataSourceName))
				.addModifiers(Modifier.PUBLIC)
				.addModifiers(Modifier.STATIC)
				.addModifiers(Modifier.ABSTRACT)
				.addTypeVariable(TypeVariableName.get("R"))
				.superclass(
						ParameterizedTypeName.get(TypeUtility.className(className),
								TypeUtility.className("Void"), 
								TypeUtility.className("Void"), 
								TypeUtility.className("R")
								)							
				)				
				.addMethod(MethodSpec.constructorBuilder()
						.addModifiers(Modifier.PUBLIC)
						.addJavadoc("Create an simple async task allowing user to decide which kind of operation can be done on datasource")
						.addParameter(BindAsyncTaskType.class, "mode")
						.addStatement("super(mode)").build())
				.addMethod(MethodSpec.constructorBuilder()
						.addModifiers(Modifier.PUBLIC)
						.addJavadoc("Create an simple async task for data source read only operation")
						.addStatement("super($T.READ)", BindAsyncTaskType.class).build())
				.build());		
		//@formatter:on

		TypeSpec typeSpec = builder.build();
		JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);		
	}
825356
public static void main(String[] args) {
        Generator schemaGen = new Generator();
        System.exit(schemaGen.createSchema(args));
    }