------------------------------------------------------ jdbc repositories
760592
@Process(actionType = AddJdbcRepository.class)
    public void addJdbcRepository(final AddJdbcRepository action, final Channel channel) {
        operationDelegate.onCreateResource(JDBC_REPOSITORY_ADDRESS,
                action.getProperty().getName(), action.getProperty().getValue(),
                new ChannelCallback(statementContext, channel));
    }
1019577
private void createDbFolder(File dbDir) {
		if (dbDir.exists()) {
		    return;
			//throw new JDOUserException("ZOO: Repository exists: " + dbFolder);
		}
		boolean r = dbDir.mkdirs();
		if (!r) {
			throw DBLogger.newUser("Could not create folders: " + dbDir.getAbsolutePath());
		}
	}
339843
protected void runSQL(String sql) {
		try {
			DataSource dataSource = commerceWarehousePersistence.getDataSource();

			DB db = DBManagerUtil.getDB();

			sql = db.buildSQL(sql);
			sql = PortalUtil.transformSQL(sql);

			SqlUpdate sqlUpdate = SqlUpdateFactoryUtil.getSqlUpdate(dataSource,
					sql);

			sqlUpdate.update();
		}
		catch (Exception e) {
			throw new SystemException(e);
		}
	}
602686
public void checkDataBase(boolean autoRepair)
   {
      SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);

      Connection jdbcConn = null;
      try
      {
         jdbcConn = jdbcDataContainer.getConnectionFactory().getJdbcConnection();

         for (InspectionQuery query : itemsInspectionQuery)
         {
            PreparedStatement st = null;
            ResultSet resultSet = null;
            try
            {
               st = jdbcConn.prepareStatement(query.getStatement());

               resultSet = st.executeQuery();
               if (resultSet.next())
               {
                  logDescription(query.getDescription());

                  do
                  {
                     logBrokenObjectAndSetInconsistency(getBrokenObject(resultSet, query.getFieldNames()));
                     if (autoRepair)
                     {
                        try
                        {
                           query.getRepair().doRepair(resultSet);
                           logComment("Inconsistency has been fixed");
                        }
                        catch (SQLException e)
                        {
                           logExceptionAndSetInconsistency("Inconsistency can not been fixed", e);
                        }
                     }
                  }
                  while (resultSet.next());
               }
            }
            finally
            {
               JDBCUtils.freeResources(resultSet, st, null);
            }
         }
      }
      catch (SQLException e)
      {
         logExceptionAndSetInconsistency("Unexpected exception during DB checking.", e);
      }
      catch (RepositoryException e)
      {
         logExceptionAndSetInconsistency("Unexpected exception during DB checking.", e);
      }
      finally
      {
         JDBCUtils.freeResources(null, null, jdbcConn);
      }
   }
494172
public Repositories getRepositories() {
        JSONRestClient.Response response = jsonRestClient.doGet();
        if (!response.isOK()) {
            throw new RuntimeException(JdbcI18n.invalidServerResponse.text(jsonRestClient.url(), response.asString()));
        }
        return new Repositories(response.json());
    }
974563
@Override
    public String[] getjdbcDataSources() {
        final String methodName = "getjdbcDataSources()";
        final boolean trace = TraceComponent.isAnyTracingEnabled();
        if (trace && tc.isEntryEnabled())
            Tr.entry(tc, methodName, this);

        final Collection<JDBCDataSourceMBeanImpl> c = dataSourceMBeanChildrenList.values();
        final int size = c.size();
        final String[] result = new String[size];
        int index = 0;
        for (JDBCDataSourceMBeanImpl mbeanItem : c)
            result[index++] = mbeanItem.getobjectName();

        if (trace && tc.isEntryEnabled())
            Tr.exit(tc, methodName, this);
        return result;
        //return dataSourcesList.toArray(new String[dataSourcesList.size()]);
    }
1238811
@Override
  public final synchronized DataSource lazyGetDataSource() throws Exception {
    String beanName = getDataSourceName();
    HikariDataSource dataSource =
      (HikariDataSource) getBeansMap().get(beanName);
    if (dataSource == null) {
      dataSource = new HikariDataSource();
      dataSource.setJdbcUrl(getDatabaseName());
      dataSource.setDriverClassName("org.sqlite.JDBC");
      getBeansMap().put(beanName, dataSource);
      lazyGetLogger().info(null, FactoryAppBeansSqlite.class, beanName
        + " has been created.");
    }
    return dataSource;
  }
823466
@Override
    public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }
344263
@Override
    public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException
    {
        checkClosed();
        throw SQLError.noSupport();
    }
1030347
@PostConstruct
    public void buildRepository() {
        try {
            LOGGER.info("Using repo config (classpath): {}", repositoryConfiguration.getURL());
            getPropertiesLoader().loadSystemProperties();

            final RepositoryConfiguration config =
                    RepositoryConfiguration.read(repositoryConfiguration.getURL());
            repository = modeShapeEngine.deploy(config);

            // next line ensures that repository starts before the factory is used.
            final org.modeshape.common.collection.Problems problems =
                    repository.getStartupProblems();
            for (final org.modeshape.common.collection.Problem p : problems) {
                LOGGER.error("ModeShape Start Problem: {}", p.getMessageString());
                // TODO determine problems that should be runtime errors
            }
        } catch (final Exception e) {
            throw new RepositoryRuntimeException(e);
        }
    }
1276244
private void generateDataSourceSingleThread(SQLiteDatabaseSchema schema, String dataSourceName) {
		// class DataSourceSingleThread
		String daoFactoryName = BindDaoFactoryBuilder.generateDaoFactoryName(schema);
		TypeSpec.Builder clazzBuilder = TypeSpec.classBuilder(DATA_SOURCE_SINGLE_THREAD_NAME)
				.addSuperinterface(TypeUtility.typeName(daoFactoryName));

		// _context field
		clazzBuilder.addField(FieldSpec.builder(SQLContextInSessionImpl.class, "_context", Modifier.PRIVATE).build());

		// constructor
		MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
		constructorBuilder.addStatement("_context=new $T($L.this)", SQLContextInSessionImpl.class, dataSourceName);

		// all dao
		for (SQLiteDaoDefinition dao : schema.getCollection()) {
			TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);

			// dao with external connections
			{
				String daoFieldName = extractDaoFieldNameForInternalDataSource(dao);
				MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("get" + dao.getName())
						.addModifiers(Modifier.PUBLIC).addJavadoc("\nretrieve dao $L\n", dao.getName())
						.returns(daoImplName);
				methodBuilder.beginControlFlow("if ($L==null)", daoFieldName);
				methodBuilder.addStatement("$L=new $T(this)", daoFieldName, daoImplName);
				methodBuilder.endControlFlow();
				methodBuilder.addStatement("return $L", daoFieldName);
				clazzBuilder.addMethod(methodBuilder.build());

				clazzBuilder.addField(FieldSpec.builder(daoImplName, daoFieldName, Modifier.PROTECTED).build());
			}
		}

		// constructor
		clazzBuilder.addMethod(constructorBuilder.build());

		// public SQLContext context()
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("context").addModifiers(Modifier.PUBLIC)
					.returns(SQLContext.class);
			methodBuilder.addAnnotation(Override.class);
			methodBuilder.addStatement("return _context");
			clazzBuilder.addMethod(methodBuilder.build());
		}

		// onSessionOpened
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionOpened")
					.addModifiers(Modifier.PROTECTED).returns(Void.TYPE);
			if (schema.hasLiveData()) {
				methodBuilder.addComment("support for live data");
				methodBuilder.addStatement("_context.onSessionOpened()");
			}

			clazzBuilder.addMethod(methodBuilder.build());
		}

		// onSessionClear
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionClear")
					.addModifiers(Modifier.PROTECTED).returns(Void.TYPE);
			if (schema.hasLiveData()) {
				methodBuilder.addComment("support for live data");
				methodBuilder.addStatement("_context.onSessionOpened()");
			}

			clazzBuilder.addMethod(methodBuilder.build());
		}

		// onSessionClosed
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSessionClosed")
					.addModifiers(Modifier.PROTECTED).returns(Void.TYPE);

			if (schema.hasLiveData()) {
				methodBuilder.addComment("support for live data");
				methodBuilder.addStatement("$T daosWithEvents=_context.onSessionClosed()",
						ParameterizedTypeName.get(Set.class, Integer.class));

				for (SQLiteDaoDefinition dao : schema.getCollection()) {

					String daoFieldName = extractDaoFieldNameForInternalDataSource(dao);
					if (dao.hasLiveData()) {
						methodBuilder.beginControlFlow("if ($L!=null && daosWithEvents.contains($L))", daoFieldName,
								dao.daoUidName);
						methodBuilder.addStatement("$L.invalidateLiveData()", daoFieldName);
						methodBuilder.endControlFlow();
					} else {
						methodBuilder.addComment("$S has no live data", daoFieldName);
					}
				}
			}

			clazzBuilder.addMethod(methodBuilder.build());
		}

		// build method bindToThread
		{
			MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("bindToThread").addModifiers(Modifier.PUBLIC)
					.returns(TypeUtility.typeName(DATA_SOURCE_SINGLE_THREAD_NAME));

			// methodBuilder.addStatement("_context.bindToThread()");
			methodBuilder.addStatement("return this");
			clazzBuilder.addMethod(methodBuilder.build());

			// build single thread daoFactory used in transaction
			classBuilder.addField(FieldSpec
					.builder(TypeUtility.typeName(DATA_SOURCE_SINGLE_THREAD_NAME), "_daoFactorySingleThread",
							Modifier.PROTECTED)
					.addJavadoc("Used only in transactions (that can be executed one for time\n")
					.initializer("new DataSourceSingleThread()").build());
		}
		
		// build transactions
		{
			SchemaUtility.generateTransaction(clazzBuilder, schema, false);
		}

		classBuilder.addType(clazzBuilder.build());

	}
930269
protected void createRepositoryInternally(String backupId, RepositoryEntry rEntry, String rToken,
      DBCreationProperties creationProps) throws RepositoryConfigurationException, RepositoryCreationException
   {
      if (rpcService != null)
      {
         String stringRepositoryEntry = null;
         try
         {
            JsonGeneratorImpl generatorImpl = new JsonGeneratorImpl();
            JsonValue json = generatorImpl.createJsonObject(rEntry);
            stringRepositoryEntry = json.toString();
         }
         catch (JsonException e)
         {
            throw new RepositoryCreationException("Can not serialize repository entry: " + e.getMessage(), e);
         }

         // notify coordinator node to create repository
         try
         {
            Object result =
               rpcService.executeCommandOnCoordinator(createRepository, true, backupId, stringRepositoryEntry, rToken,
                  creationProps);

            if (result != null)
            {
               if (result instanceof Throwable)
               {
                  throw new RepositoryCreationException("Can't create repository " + rEntry.getName(),
                     (Throwable)result);
               }
               else
               {
                  throw new RepositoryCreationException("createRepository command returned uknown result type.");
               }
            }
         }
         catch (RPCException e)
         {
            Throwable cause = (e).getCause();
            if (cause instanceof RepositoryCreationException)
            {
               throw (RepositoryCreationException)cause;
            }
            else if (cause instanceof RepositoryConfigurationException)
            {
               throw (RepositoryConfigurationException)cause;
            }
            else
            {
               throw new RepositoryCreationException(e.getMessage(), e);
            }
         }

         // execute startRepository at all cluster nodes (coordinator will ignore this command)
         try
         {
            List<Object> results =
               rpcService.executeCommandOnAllNodes(startRepository, true, stringRepositoryEntry, creationProps);

            for (Object result : results)
            {
               if (result != null)
               {
                  if (result instanceof Throwable)
                  {
                     throw new RepositoryCreationException("Repository " + rEntry.getName()
                        + " created on coordinator, but can not be started at other cluster nodes", ((Throwable)result));
                  }
                  else
                  {
                     throw new RepositoryCreationException("startRepository command returns uknown result type");
                  }
               }
            }
         }
         catch (RPCException e)
         {
            throw new RepositoryCreationException("Repository " + rEntry.getName()
               + " created on coordinator, can not be started at other cluster node: " + e.getMessage(), e);
         }
      }
      else
      {
         try
         {
            createRepositoryLocally(backupId, rEntry, rToken, creationProps);
         }
         finally
         {
            pendingRepositories.remove(rToken);
         }
      }
   }
1261059
private Map<String, JcrRepository> loadRepositories() {
        Map<String, JcrRepository> list = new HashMap<>();
        Set<String> names = RepositoryManager.getJcrRepositoryNames();

        for (String repositoryId : names) {
            try {
                Repository repository = RepositoryManager.getRepository(repositoryId);
                list.put(repositoryId, new JcrMsRepository(repository, pathManager, typeManager, typeHandlerManager));
                log.debug("--- loaded repository " + repositoryId);
            } catch (NoSuchRepositoryException e) {
                // should never happen;
            }
        }

        return list;
    }
780528
public static void configureCacheStore(MappedParametrizedObjectEntry parameterEntry,
                                          String dataSourceParamName, String dataColumnParamName, String idColumnParamName, String timeColumnParamName, String dialectParamName)
      throws RepositoryException
   {
      String dataSourceName = parameterEntry.getParameterValue(dataSourceParamName, null);

      String dialect = parameterEntry.getParameterValue(dialectParamName, DBConstants.DB_DIALECT_AUTO).toUpperCase();

      // if data source is defined, then inject correct data-types.
      // Also it cans be not defined and nothing should be injected
      // (i.e. no cache loader is used (possibly pattern is changed, to used another cache loader))
      DataSource dataSource;
      try
      {
         dataSource = (DataSource)new InitialContext().lookup(dataSourceName);
      }
      catch (NamingException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }

      String blobType;
      String charType;
      String timeStampType;
      try
      {
         blobType = JDBCUtils.getAppropriateBlobType(dataSource);
         if (dialect.startsWith(DBConstants.DB_DIALECT_MYSQL) && dialect.endsWith("-UTF8"))
         {
            charType = "VARCHAR(255)";
         }
         else
         {
            charType = JDBCUtils.getAppropriateCharType(dataSource);
         }
         timeStampType = JDBCUtils.getAppropriateTimestamp(dataSource);
      }
      catch (SQLException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }

      // set parameters if not defined
      // if parameter is missing in configuration, then
      // getParameterValue(INFINISPAN_JDBC_CL_DATA_COLUMN, INFINISPAN_JDBC_CL_AUTO)
      // will return INFINISPAN_JDBC_CL_AUTO. If parameter is present in configuration and
      //equals to "auto", then it should be replaced
      // with correct value for given database
      if (parameterEntry.getParameterValue(dataColumnParamName, "auto").equalsIgnoreCase("auto"))
      {
         parameterEntry.putParameterValue(dataColumnParamName, blobType);
      }

      if (parameterEntry.getParameterValue(idColumnParamName, "auto").equalsIgnoreCase("auto"))
      {
         parameterEntry.putParameterValue(idColumnParamName, charType);
      }

      if (parameterEntry.getParameterValue(timeColumnParamName, "auto").equalsIgnoreCase("auto"))
      {
         parameterEntry.putParameterValue(timeColumnParamName, timeStampType);
      }
   }
908113
@Override
  public Map<String, JdbcType> retrieveDateColumns(String database, String table)
      throws SQLException {
    Map<String, JdbcType> targetDataTypes =
        ImmutableMap.<String, JdbcType>builder().put("DATE", JdbcType.DATE).put("TIME WITH TIME ZONE", JdbcType.TIME)
            .put("TIME WITHOUT TIME ZONE", JdbcType.TIME).put("TIMESTAMP WITH TIME ZONE", JdbcType.TIMESTAMP)
            .put("TIMESTAMP WITHOUT TIME ZONE", JdbcType.TIMESTAMP).build();

    ImmutableMap.Builder<String, JdbcType> dateColumnsBuilder = ImmutableMap.builder();

    try (PreparedStatement pstmt = this.conn
        .prepareStatement(INFORMATION_SCHEMA_SELECT_SQL_PSTMT, ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY)) {
      pstmt.setString(1, database);
      pstmt.setString(2, table);
      log.info("Retrieving column type information from SQL: " + pstmt);
      try (ResultSet rs = pstmt.executeQuery()) {
        if (!rs.first()) {
          throw new IllegalArgumentException("No result from information_schema.columns");
        }
        do {
          String type = rs.getString("data_type").toUpperCase();
          JdbcType convertedType = targetDataTypes.get(type);
          if (convertedType != null) {
            dateColumnsBuilder.put(rs.getString("column_name"), convertedType);
          }
        } while (rs.next());
      }
    }
    return dateColumnsBuilder.build();
  }
935141
protected IJdbcHelper buildJdbcHelper() {
        if (dataSource == null) {
            throw new IllegalStateException("Data source is null.");
        }
        DdthJdbcHelper jdbcHelper = new DdthJdbcHelper();
        jdbcHelper.setDataSource(getDataSource()).init();
        return jdbcHelper;
    }
410158
public void jdbc(String driver, String url, String user, String password) {
        connectionWrapper.setConnectionSpec(new ConnectionJdbcSpec(driver, url, user, password));
    }