Generate schema.

@param schema
the schema
@throws FileNotFoundException
the file not found exception
@throws IOException
Signals that an I/O exception has occurred.
776397
private static void generateSchema(SQLiteDatabaseSchema schema) throws FileNotFoundException, IOException {
		// when we run in JUNIT of Kripton, we don't have to generate schemas
		// if (BindDataSourceSubProcessor.JUNIT_TEST_MODE)
		// return;
		if (!schema.generateSchema)
			return;

		// and now, write schema.create.v and schema.drop.v
		String schemaCreation = defineFileName(schema);

		String schemaLocation = KriptonOptions.getSchemaLocation();

		File schemaCreatePath = new File(schemaLocation).getAbsoluteFile();
		File schemaCreateFile = new File(schemaLocation, schemaCreation).getAbsoluteFile();
		schemaCreatePath.mkdirs();

		AnnotationProcessorUtilis.infoOnGeneratedFile(BindDataSource.class, schemaCreateFile);
		FileOutputStream fos = new FileOutputStream(schemaCreateFile);
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

		bw.write("------------------------------------------------------------------------------------\n");
		bw.write("--\n");
		bw.write("-- Filename: " + schemaCreation + "\n");
		bw.write("--\n");
		bw.write(String.format("-- Date: %s", (new Date()).toString()) + "\n");
		bw.write("--\n");
		if (!BindDataSourceSubProcessor.JUNIT_TEST_MODE) {
			bw.write(String.format("-- This file was generated by Kripton Annotation Processor v. %s\n",
					Version.getVersion()));
			bw.write(String.format("--\n"));
		}
		bw.write("------------------------------------------------------------------------------------\n");
		bw.newLine();
		for (String sql : schema.sqlForCreate) {
			bw.write(sql);
			bw.newLine();
		}
		bw.close();
	}
561564
def generate_default_schema(output):
    """"""
    original_path = os.path.join(os.path.dirname(__file__),
                                 'data',
                                 'randomnames-schema.json')
    shutil.copyfile(original_path, output)
324231
def get_schema(schema_type):
    '''
    '''

    schema_file = "{}-schema.json".format(schema_type)
    file_path = os.path.join(_default_schema_dir, schema_file)

    if not os.path.isfile(file_path):
        raise RuntimeError('Schema file \'{}\' does not exist, is not readable, or is not a file'.format(file_path))

    return fileio.read_schema(file_path)
300918
private void initSchema(final SchemaManager schemaManager, final CoreSession adminSession, final StructrPartition partition) throws Exception {

		final URL url            = SchemaEntityFactory.class.getProtectionDomain().getCodeSource().getLocation();
		final JarFile jarFile    = new JarFile(new File(url.toURI()));
		final List<String> names = new LinkedList<>();

		for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {

			final ZipEntry zipEntry = e.nextElement();
			final String name = zipEntry.getName();

			if (name.startsWith("schema/") && name.endsWith(".ldif")) {

				names.add(name);
			}
		}

		Collections.sort(names, new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {

				// first sort key: number of slashes (level)
				Integer s1 = StringUtils.countMatches(o1, "/");
				Integer s2 = StringUtils.countMatches(o2, "/");

				if (s1.equals(s2)) {

					// secondary sort key: string length
					Integer l1 = o1.length();
					Integer l2 = o2.length();

					if (l1.equals(l2)) {

						// tertiary sort key: the string values
						return o1.compareTo(o2);
					}

					return l1.compareTo(l2);
				}

				return s1.compareTo(s2);
			}

		});

		for (final String name : names) {

			try (final LdifReader reader = new LdifReader(jarFile.getInputStream(jarFile.getEntry(name)))) {

				for (final LdifEntry entry : reader) {

					final Entry schemaEntry  = new DefaultEntry(schemaManager, entry.getEntry());
					final Dn dn              = schemaEntry.getDn();

					if (!partition.hasEntry(new HasEntryOperationContext(adminSession, dn))) {

						logger.info("Importing {}...", name);
						partition.add(new AddOperationContext(adminSession, schemaEntry));
					}
				}
			}
		}
	}
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);		
	}
974063
public void addDBDefinitionFile(InputStream schemaStream) throws IOException
    {
        _torqueSchemata.put("schema"+_torqueSchemata.size()+".xml",
                            readStreamCompressed(schemaStream));
    }
40476
public static <T> void mergeFrom(Reader r, T message, Schema<T> schema)
            throws IOException
    {
        mergeFrom(r, message, schema, DEFAULT_INPUT_FACTORY);
    }
1121728
def add_schema(self, schema):
        

        # serialize instances of SchemaNode before parsing
        if isinstance(schema, SchemaNode):
            schema = schema.to_schema()

        for subschema in self._get_subschemas(schema):
            # delegate to SchemaType object
            schema_generator = self._get_generator_for_schema(subschema)
            schema_generator.add_schema(subschema)

        # return self for easy method chaining
        return self
195668
protected void addCitrusSchema(String schemaName) throws IOException, SAXException, ParserConfigurationException {
        Resource resource = new PathMatchingResourcePatternResolver().getResource("classpath:com/consol/citrus/schema/" + schemaName + ".xsd");
        if (resource.exists()) {
            addXsdSchema(resource);
        }
    }
271118
def _locate_schemas(self, schemas, skip_missing_schemas):
        
        for schema in schemas:
            if schema == os.path.abspath(schema):
                schema_file = schema
            else:
                schema_file = os.path.join(self.paths.schemas, schema)

            if os.path.isfile(schema_file):
                # Absolute path: use it.
                yield schema_file
            elif skip_missing_schemas:
                logger.warning("Unable to locate schema %s at %s", schema, schema_file)
            else:
                raise PathError("Unable to locate schema %s at %s" % (schema, schema_file))
954917
public void doSchema(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        setHeaders(rsp);
        rsp.setContentType("application/xml");
        StreamResult r = new StreamResult(rsp.getOutputStream());
        new SchemaGenerator(new ModelBuilder().get(bean.getClass())).generateSchema(r);
        r.getOutputStream().close();
    }
994808
def compile_schema(self, schema):
        
        compiler = self.get_schema_compiler(schema)

        if compiler is None:
            raise SchemaError(_(u'Unsupported schema data type {!r}').format(type(schema).__name__))

        return compiler(schema)
1123419
function load(schema) {
  var obj;
  if (typeof schema == 'string' && schema !== 'null') {
    try {
      obj = JSON.parse(schema);
    } catch (err) {
      // No file loading here.
    }
  }
  if (obj === undefined) {
    obj = schema;
  }
  return obj;
}
818394
protected function saveSchemaFile($schema, $settings)
    {
        $schemaFile = $this->getSchemaFilename($settings);
        $this->getOutput()->writeln(sprintf('Save schema file: %s', basename($schemaFile)));
        $fileExt = pathinfo($schemaFile, PATHINFO_EXTENSION);

        if ($fileExt === 'php') {
            $content = var_export($schema, true);
            $content = "<?php\n\nreturn " . $content . ';';
        } elseif ($fileExt === 'json') {
            $content = json_encode($schema, JSON_PRETTY_PRINT);
        } else {
            throw new Exception(sprintf('Invalid schema file extension: %s', $fileExt));
        }
        file_put_contents($schemaFile, $content);
    }
185710
private void initSchemaPartition() throws Exception {
        final InstanceLayout instanceLayout = this.service.getInstanceLayout();

        final File schemaPartitionDirectory = new File(instanceLayout.getPartitionsDirectory(), "schema");

        /*
         * Extract the schema on disk (a brand new one) and load the registries
         */
        if (schemaPartitionDirectory.exists()) {
            System.out.println("schema partition already exists, skipping schema extraction");
        } else {
            final SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor(instanceLayout.getPartitionsDirectory());
            extractor.extractOrCopy();
        }

        final SchemaLoader loader = new LdifSchemaLoader(schemaPartitionDirectory);
        final SchemaManager schemaManager = new DefaultSchemaManager(loader);

        /*
         * We have to load the schema now, otherwise we won't be able
         * to initialize the Partitions, as we won't be able to parse
         * and normalize their suffix Dn
         */
        schemaManager.loadAllEnabled();

        final List<Throwable> errors = schemaManager.getErrors();

        if (errors.size() != 0) {
            throw new Exception(I18n.err(I18n.ERR_317,
                                         Exceptions.printErrors(errors)));
        }

        this.service.setSchemaManager(schemaManager);

        /*
         * Init the LdifPartition with schema
         */
        final LdifPartition schemaLdifPartition = new LdifPartition(schemaManager);
        schemaLdifPartition.setPartitionPath(schemaPartitionDirectory.toURI());

        /*
         * The schema partition
         */
        final SchemaPartition schemaPartition = new SchemaPartition(schemaManager);
        schemaPartition.setWrappedPartition(schemaLdifPartition);
        this.service.setSchemaPartition(schemaPartition);
    }
1254453
protected void addImportedSchemas(Schema schema) throws WSDLException, IOException, TransformerException, TransformerFactoryConfigurationError {
        for (Object imports : schema.getImports().values()) {
            for (SchemaImport schemaImport : (Vector<SchemaImport>)imports) {
                // Prevent duplicate imports
                if (!importedSchemas.contains(schemaImport.getNamespaceURI())) {
                    importedSchemas.add(schemaImport.getNamespaceURI());
                    Schema referencedSchema = schemaImport.getReferencedSchema();

                    if (referencedSchema != null) {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        Source source = new DOMSource(referencedSchema.getElement());
                        Result result = new StreamResult(bos);

                        TransformerFactory.newInstance().newTransformer().transform(source, result);
                        Resource schemaResource = new ByteArrayResource(bos.toByteArray());

                        addImportedSchemas(referencedSchema);
                        schemaResources.add(schemaResource);
                    }
                }
            }
        }
    }
1111766
public static void generate(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
		BindDaoFactoryBuilder visitor = new BindDaoFactoryBuilder(elementUtils, filer, schema);
		visitor.buildDaoFactoryInterface(elementUtils, filer, schema);
		String daoFactoryName = BindDaoFactoryBuilder.generateDaoFactoryName(schema);

		BindDataSourceBuilder visitorDao = new BindDataSourceBuilder(elementUtils, filer, schema);
		visitorDao.buildDataSource(elementUtils, filer, schema, daoFactoryName);

		generateSchema(schema);
	}