All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jk.data.multitent.MultiTenantSupport Maven / Gradle / Ivy

Go to download

This contains a set of API's that ease the database programming with Java, in both: JDBC and JPA Persisitnce).

There is a newer version: 7.0.0-M7
Show newest version
/*
 * Copyright 2002-2022 Dr. Jalal Kiswani. 
 * Email: [email protected]
 * Check out https://smart-api.com for more details
 * 
 * All the opensource projects of Dr. Jalal Kiswani are free for personal and academic use only, 
 * for commercial usage and support, please contact the author.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jk.data.multitent;

import java.security.Principal;

import com.jk.core.context.JKContextFactory;
import com.jk.core.logging.JKLogger;
import com.jk.core.logging.JKLoggerFactory;
import com.jk.core.util.JK;
import com.jk.data.util.JKDataAccessUtil;

// TODO: Auto-generated Javadoc
/**
 * The Class MultiTenantSupport.
 */
public class MultiTenantSupport {
	
	/** The logger. */
	static JKLogger logger = JKLoggerFactory.getLogger(MultiTenantSupport.class);

	/** The Constant TENANT_FIELD_NAME. */
	public static final String TENANT_FIELD_NAME = "tenant_id";

	/**
	 * Process sql statement.
	 *
	 * @param statement the statement
	 * @return the string
	 */
	public static String processSqlStatement(String statement) {
		logger.debug("processSqlStatement: {} {}", JK.NEW_LINE, statement);
		String currentTenant = getCurrentTenant();
		String statement2 = statement.toLowerCase().trim();
		if (currentTenant == null || currentTenant.trim().equals("")) {
			JK.error("Tenant cannot be null at this stage");
		}
		if(statement2.contains("limit")) {
			JK.error("This query is not supported yet");
		}
		if (statement2.startsWith("show columns") || statement2.startsWith("desc")) {
			return statement;
		}
		if (statement2.startsWith("drop") || statement2.startsWith("create") || statement2.startsWith("alter")) {
			// JK.error("Tenant (%s) is trying to do strtcture statement", currentTenant);
			JK.fixMe("Add security for this, to avoid playing with trstcure by a tenant at runtime");
			return statement;
		}
		if (statement2.startsWith("insert")) {
			statement = processInsertStatement(statement);
			logger.debug("Result statement :\n", statement);
			return statement;
		}
		if (statement2.startsWith("update") || statement2.startsWith("delete") || statement2.startsWith("select")) {
			statement=processConditionalStatement(statement);
			logger.debug("Result statement :\n", statement);
			return statement;
		}
		logger.error("Multitenant support failed to handle this statement : {}", JKDataAccessUtil.formatStatement(statement));
		JK.error("Tenant (%s) is trying to call illegal statement", currentTenant);
		return null;
	}

	/**
	 * Process conditional statement.
	 *
	 * @param statement the statement
	 * @return the string
	 */
	private static String processConditionalStatement(String statement) {
		JK.fixMe("refactor me");
		int whereIndex = statement.toLowerCase().indexOf("where");
		if (whereIndex == -1) {
			// no where is provided
			StringBuffer buf = new StringBuffer(statement);
			buf.append(String.format(" WHERE %s='%s' ", TENANT_FIELD_NAME, getCurrentTenant()));
			return buf.toString();
		} else {
			StringBuffer buf = new StringBuffer();
			buf.append(statement.substring(0, whereIndex + 6));
			buf.append(String.format("%s='%s' AND ", TENANT_FIELD_NAME, getCurrentTenant()));
			buf.append(statement.substring(whereIndex + 6));
			return buf.toString();
		}
	}

	/**
	 * Process insert statement.
	 *
	 * @param statement the statement
	 * @return the string
	 */
	private static String processInsertStatement(String statement) {
		int startIndex = 0;
		int indexOfLeftPerenthises = statement.indexOf(")");// index of the fields names
//		int secondIndexOfLeftPerenthise = statement.lastIndexOf(")");//
		if (!statement.toLowerCase().contains("values")) {
			// no field names are provided, only values. we just add the value to the end
			// assuming it is the end value
			StringBuffer buf = new StringBuffer();
			buf.append(statement.substring(startIndex, indexOfLeftPerenthises));
			buf.append(",'");
			buf.append(getCurrentTenant());
			buf.append("')");
			return buf.toString();
		} else {
			// field names are provided, so we need to set the field typeName,then the value
			StringBuffer buf = new StringBuffer();
			buf.append(statement.substring(startIndex, indexOfLeftPerenthises));
			buf.append(",");
			buf.append(TENANT_FIELD_NAME).append(")");

			while (true) {
				startIndex = indexOfLeftPerenthises + 1;
				indexOfLeftPerenthises = statement.indexOf(")", startIndex);
				if (indexOfLeftPerenthises == -1) {
					break;
				}
				buf.append(statement.substring(startIndex, indexOfLeftPerenthises));
				buf.append(",'");
				buf.append(getCurrentTenant()).append("')");
			}
			return buf.toString();
		}
	}

	/**
	 * Gets the current tenant.
	 *
	 * @return the current tenant
	 */
	public static String getCurrentTenant() {
		Object user = JKContextFactory.getCurrentContext().getUser();
		if(user==null) {
			return null;
		}
		 if( user instanceof String) {
			 return (String) user;
		 }
		 if(user instanceof Principal) {
			 return ((Principal)user).getName();
		 }
		 return user.toString();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy