<commit_before>package com.transcend.rds.worker;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonNode;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Strings;
import com.msi.tough.cf.AccountType;
import com.msi.tough.cf.json.DatabagParameter;
import com.msi.tough.core.Appctx;
import com.msi.tough.core.BaseException;
import com.msi.tough.core.DateHelper;
import com.msi.tough.core.HibernateUtil;
import com.msi.tough.core.JsonUtil;
import com.msi.tough.engine.aws.ec2.Volume;
import com.msi.tough.engine.core.CallStruct;
import com.msi.tough.engine.core.TemplateContext;
import com.msi.tough.model.AccountBean;
import com.msi.tough.model.ResourcesBean;
import com.msi.tough.model.rds.RdsDbinstance;
import com.msi.tough.model.rds.RdsDbparameterGroup;
import com.msi.tough.model.rds.RdsDbsecurityGroup;
import com.msi.tough.model.rds.RdsSnapshot;
import com.msi.tough.query.ErrorResponse;
import com.msi.tough.query.QueryUtil;
import com.msi.tough.query.ServiceRequestContext;
import com.msi.tough.query.UnsecuredAction;
import com.msi.tough.rds.ValidationManager;
import com.msi.tough.rds.json.RDSConfigDatabagItem;
import com.msi.tough.rds.json.RDSCreateTemplate;
import com.msi.tough.rds.json.RDSDatabag;
import com.msi.tough.rds.json.RDSParameterGroupDatabagItem;
import com.msi.tough.utils.AccountUtil;
import com.msi.tough.utils.CFUtil;
import com.msi.tough.utils.ChefUtil;
import com.msi.tough.utils.ConfigurationUtil;
import com.msi.tough.utils.EventUtil;
import com.msi.tough.utils.RDSQueryFaults;
import com.msi.tough.utils.RDSUtil;
import com.msi.tough.utils.rds.InstanceEntity;
import com.msi.tough.utils.rds.ParameterGroupEntity;
import com.msi.tough.utils.rds.RDSUtilities;
import com.msi.tough.utils.rds.SecurityGroupEntity;
import com.msi.tough.utils.rds.SnapshotEntity;
import com.msi.tough.workflow.core.AbstractWorker;
import com.transcend.rds.message.CreateDBInstanceActionMessage.CreateDBInstanceActionRequestMessage;
import com.transcend.rds.message.CreateDBInstanceActionMessage.CreateDBInstanceActionResultMessage;
import com.transcend.rds.message.RDSMessage.DBInstance;
import com.transcend.rds.message.RDSMessage.DBParameterGroupStatus;
import com.transcend.rds.message.RDSMessage.DBSecurityGroupMembership;
import com.transcend.rds.message.RDSMessage.Endpoint;

/**
 * @author <EMAIL>
 */
public class CreateDBInstanceActionWorker extends
		AbstractWorker<CreateDBInstanceActionRequestMessage, CreateDBInstanceActionResultMessage> {
	private final static Logger logger = Appctx
			.getLogger(CreateDBInstanceActionWorker.class.getName());
	
	   
    /**
    * We need a local copy of this doWork to provide the transactional
    * annotation.  Transaction management is handled by the annotation, which
    * can only be on a concrete class.
    * @param req
    * @return
    * @throws Exception
    */
   @Transactional
   public CreateDBInstanceActionResultMessage doWork(
           CreateDBInstanceActionRequestMessage req) throws Exception {
       logger.debug("Performing work for CreateDBInstanceAction.");
       return super.doWork(req, getSession());
   }
   
	@Override
	protected CreateDBInstanceActionResultMessage doWork0(CreateDBInstanceActionRequestMessage req,
			ServiceRequestContext context) throws Exception {

		final DBInstance dbInst = createDBInstance(req , context, false);
		CreateDBInstanceActionResultMessage.Builder resp = 
				CreateDBInstanceActionResultMessage.newBuilder();
		resp.setDbInstance(dbInst);
		return resp.buildPartial();
	}
   
   
   public DBInstance createDBInstance(final CreateDBInstanceActionRequestMessage req,
		   ServiceRequestContext context, boolean restored) {
		DBInstance resp;
		String msg = "";

		final Session sess = HibernateUtil.newSession();
		try {
			sess.beginTransaction();
			AccountBean ac = context.getAccountBean();
			// InstanceID is required
			
			if(ac == null){
				// if CreateDBInstance is called from RestoreDBInstance/ReplicateDBInstance calls, read the account now!
				throw RDSQueryFaults.InternalFailure("Account not found");
			}
			
			
			final String instID = ValidationManager.validateIdentifier(
					req.getDbInstanceIdentifier(), 64, true);

			logger.info("CreateInstance: UserID = " + ac.getId()
					+ " InstanceID = " + instID);

			{
				final RdsDbinstance eb = RDSUtil.getInstance(sess, instID,
						ac.getId());
				if (eb != null) {
					throw RDSQueryFaults.DBInstanceAlreadyExists();
				}
				final String avz = req.getAvailabilityZone();
				if (avz != null && !("".equals(avz)) && !Appctx.getConfiguration().containsKey(avz)) {
					throw RDSQueryFaults.ProvisionedIopsNotAvailableInAZ();
				}
			}

			// check to see if DBSecurityGroup exists
			final List<String> dbsecgrpsNames = req.getDbSecurityGroupsList();
			if (dbsecgrpsNames != null) {
				for (final String name : dbsecgrpsNames) {
					final RdsDbsecurityGroup r = SecurityGroupEntity
							.getSecurityGroup(sess, name, ac.getId());
					if (r == null) {
						throw RDSQueryFaults.DBSecurityGroupNotFound();
					}
				}
			}

			/*
			 * The following fully validates the request and insert the
			 * necessary database records. DBInstance record is created with
			 * status of creating. It runs as a single transaction
			 */
			final RdsDbinstance newInstRec = insertDBInstance(
					sess, req, ac);
			newInstRec.setDbinstanceStatus("creating");

			logger.debug("Creating a new databag with following inputs...\n"
					+ "AllocatedStorage: "
					+ newInstRec.getAllocatedStorage()
					+ "\n"
					+ "MasterUsername: "
					+ newInstRec.getMasterUsername()
					+ "\n"
					+ "MasterPassword: "
					+ newInstRec.getMasterUserPassword()
					+ "\n"
					+ "AutoMinorVersionUpgrade: "
					+ newInstRec.getAutoMinorVersionUpgrade()
					+ "\n"
					+ "Engine: "
					+ newInstRec.getEngine()
					+ "\n"
					+ "EngineVersion: "
					+ newInstRec.getEngineVersion()
					+ "\n"
					+ "DBName: "
					+ newInstRec.getDbName()
					+ "\n"
					+ "BackupRetentionPeriod: "
					+ newInstRec.getBackupRetentionPeriod()
					+ "\n"
					+ "PreferredBackupWindow: "
					+ newInstRec.getPreferredBackupWindow()
					+ "\n"
					+ "PreferredMaintenanceWindow: "
					+ newInstRec.getPreferredMaintenanceWindow()
					+ "\n"
					+ "LicenseModel: " + newInstRec.getLicenseModel());

			final String postWaitUrl = (String) ConfigurationUtil
					.getConfiguration(Arrays.asList(new String[] {
							"TRANSCEND_URL", newInstRec.getAvailabilityZone() }));

			
			final String servletUrl = ConfigurationUtil
					.getConfiguration(Arrays.asList(new String[] {
							"SERVLET_URL", newInstRec.getAvailabilityZone() })).toString();

	
			final RDSConfigDatabagItem configDataBagItem = new RDSConfigDatabagItem(
					"config", newInstRec.getAllocatedStorage().toString(),
					newInstRec.getMasterUsername(),
					newInstRec.getMasterUserPassword(),
					newInstRec.getAutoMinorVersionUpgrade(),
					newInstRec.getEngine(), newInstRec.getEngineVersion(),
					newInstRec.getDbName(), newInstRec
							.getBackupRetentionPeriod().toString(),
					newInstRec.getPreferredBackupWindow(),<commit_msg>Removed debug statement<commit_after>package com.transcend.rds.worker;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonNode;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Strings;
import com.msi.tough.cf.AccountType;
import com.msi.tough.cf.json.DatabagParameter;
import com.msi.tough.core.Appctx;
import com.msi.tough.core.BaseException;
import com.msi.tough.core.DateHelper;
import com.msi.tough.core.HibernateUtil;
import com.msi.tough.core.JsonUtil;
import com.msi.tough.engine.aws.ec2.Volume;
import com.msi.tough.engine.core.CallStruct;
import com.msi.tough.engine.core.TemplateContext;
import com.msi.tough.model.AccountBean;
import com.msi.tough.model.ResourcesBean;
import com.msi.tough.model.rds.RdsDbinstance;
import com.msi.tough.model.rds.RdsDbparameterGroup;
import com.msi.tough.model.rds.RdsDbsecurityGroup;
import com.msi.tough.model.rds.RdsSnapshot;
import com.msi.tough.query.ErrorResponse;
import com.msi.tough.query.QueryUtil;
import com.msi.tough.query.ServiceRequestContext;
import com.msi.tough.query.UnsecuredAction;
import com.msi.tough.rds.ValidationManager;
import com.msi.tough.rds.json.RDSConfigDatabagItem;
import com.msi.tough.rds.json.RDSCreateTemplate;
import com.msi.tough.rds.json.RDSDatabag;
import com.msi.tough.rds.json.RDSParameterGroupDatabagItem;
import com.msi.tough.utils.AccountUtil;
import com.msi.tough.utils.CFUtil;
import com.msi.tough.utils.ChefUtil;
import com.msi.tough.utils.ConfigurationUtil;
import com.msi.tough.utils.EventUtil;
import com.msi.tough.utils.RDSQueryFaults;
import com.msi.tough.utils.RDSUtil;
import com.msi.tough.utils.rds.InstanceEntity;
import com.msi.tough.utils.rds.ParameterGroupEntity;
import com.msi.tough.utils.rds.RDSUtilities;
import com.msi.tough.utils.rds.SecurityGroupEntity;
import com.msi.tough.utils.rds.SnapshotEntity;
import com.msi.tough.workflow.core.AbstractWorker;
import com.transcend.rds.message.CreateDBInstanceActionMessage.CreateDBInstanceActionRequestMessage;
import com.transcend.rds.message.CreateDBInstanceActionMessage.CreateDBInstanceActionResultMessage;
import com.transcend.rds.message.RDSMessage.DBInstance;
import com.transcend.rds.message.RDSMessage.DBParameterGroupStatus;
import com.transcend.rds.message.RDSMessage.DBSecurityGroupMembership;
import com.transcend.rds.message.RDSMessage.Endpoint;

/**
 * @author <EMAIL>
 */
public class CreateDBInstanceActionWorker extends
		AbstractWorker<CreateDBInstanceActionRequestMessage, CreateDBInstanceActionResultMessage> {
	private final static Logger logger = Appctx
			.getLogger(CreateDBInstanceActionWorker.class.getName());
	
	   
    /**
    * We need a local copy of this doWork to provide the transactional
    * annotation.  Transaction management is handled by the annotation, which
    * can only be on a concrete class.
    * @param req
    * @return
    * @throws Exception
    */
   @Transactional
   public CreateDBInstanceActionResultMessage doWork(
           CreateDBInstanceActionRequestMessage req) throws Exception {
       logger.debug("Performing work for CreateDBInstanceAction.");
       return super.doWork(req, getSession());
   }
   
	@Override
	protected CreateDBInstanceActionResultMessage doWork0(CreateDBInstanceActionRequestMessage req,
			ServiceRequestContext context) throws Exception {

		final DBInstance dbInst = createDBInstance(req , context, false);
		CreateDBInstanceActionResultMessage.Builder resp = 
				CreateDBInstanceActionResultMessage.newBuilder();
		resp.setDbInstance(dbInst);
		return resp.buildPartial();
	}
   
   
   public DBInstance createDBInstance(final CreateDBInstanceActionRequestMessage req,
		   ServiceRequestContext context, boolean restored) {
		DBInstance resp;
		String msg = "";

		final Session sess = HibernateUtil.newSession();
		try {
			sess.beginTransaction();
			AccountBean ac = context.getAccountBean();
			// InstanceID is required
			
			if(ac == null){
				// if CreateDBInstance is called from RestoreDBInstance/ReplicateDBInstance calls, read the account now!
				throw RDSQueryFaults.InternalFailure("Account not found");
			}
			
			
			final String instID = ValidationManager.validateIdentifier(
					req.getDbInstanceIdentifier(), 64, true);

			logger.info("CreateInstance: UserID = " + ac.getId()
					+ " InstanceID = " + instID);

			{
				final RdsDbinstance eb = RDSUtil.getInstance(sess, instID,
						ac.getId());
				if (eb != null) {
					throw RDSQueryFaults.DBInstanceAlreadyExists();
				}
				final String avz = req.getAvailabilityZone();
				if (avz != null && !("".equals(avz)) && !Appctx.getConfiguration().containsKey(avz)) {
					throw RDSQueryFaults.ProvisionedIopsNotAvailableInAZ();
				}
			}

			// check to see if DBSecurityGroup exists
			final List<String> dbsecgrpsNames = req.getDbSecurityGroupsList();
			if (dbsecgrpsNames != null) {
				for (final String name : dbsecgrpsNames) {
					final RdsDbsecurityGroup r = SecurityGroupEntity
							.getSecurityGroup(sess, name, ac.getId());
					if (r == null) {
						throw RDSQueryFaults.DBSecurityGroupNotFound();
					}
				}
			}

			/*
			 * The following fully validates the request and insert the
			 * necessary database records. DBInstance record is created with
			 * status of creating. It runs as a single transaction
			 */
			final RdsDbinstance newInstRec = insertDBInstance(
					sess, req, ac);
			newInstRec.setDbinstanceStatus("creating");

			final String postWaitUrl = (String) ConfigurationUtil
					.getConfiguration(Arrays.asList(new String[] {
							"TRANSCEND_URL", newInstRec.getAvailabilityZone() }));

			
			final String servletUrl = ConfigurationUtil
					.getConfiguration(Arrays.asList(new String[] {
							"SERVLET_URL", newInstRec.getAvailabilityZone() })).toString();

	
			final RDSConfigDatabagItem configDataBagItem = new RDSConfigDatabagItem(
					"config", newInstRec.getAllocatedStorage().toString(),
					newInstRec.getMasterUsername(),
					newInstRec.getMasterUserPassword(),
					newInstRec.getAutoMinorVersionUpgrade(),
					newInstRec.getEngine(), newInstRec.getEngineVersion(),
					newInstRec.getDbName(), newInstRec
							.getBackupRetentionPeriod().toString(),
					newInstRec.getPreferredBackupWindow(),
{'fraction_non_alphanumeric': 0.10421127765881513, 'fraction_numerical': 0.0007137758743754461, 'mean_word_length': 4.434833204034135, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2275183', 'n_tokens_mistral': 4943, 'n_tokens_neox': 4383, 'n_words': 792}