Saturday, 30 May 2015

Datatables ajax bootstrap pagination with codeigniter

If you want to implement datatables with ajax using codeigniter and you can also use code if you are using core php stuff in your application.

1. You need to include required jQuery for datatables , ajax processing.
  1. <script src="<?php echo base_url(); ?>assets/js/jquery-1.11.0.min.js"></script>
  2. <script src="<?php echo base_url(); ?>assets/js/jquery.dataTables.min.js"></script>
  3. <script src="<?php echo base_url(); ?>assets/js/dataTables.bootstrap.js"></script>
  4. <script src="<?php echo base_url(); ?>assets/js/datatables/responsive/js/datatables.responsive.js">
  5. </script>
  6. <script src="<?php echo base_url(); ?>assets/js/datatables/jquery.dataTables.columnFilter.js">
  7. </script>
2. Your html source file or you can say your view file will goes like below.
  1. <div class="main-content">
  2. <div class="row"><h2>Brokers Listing</h2>
  3. <div class="panel panel-primary" data-collapsed="0">
  4. <div class="panel-body">
  5. <table class="table table-bordered table-striped datatable" id="broker_listing">
  6. <thead><tr>
  7. <th class="no-sort">#</th>
  8. <th>Broker Name</th>
  9. <th>Email</th>
  10. <th>Created Date</th>
  11. <th>Status</th>
  12. <th class="no-sort">Actions</th>
  13. </tr></thead><tbody></tbody>
  14. </table>
  15. </div>
  16. </div>
  1. <script type="text/javascript">
  2. jQuery(window).load(function(){
  3. var $ = jQuery;
  4. $("#broker_listing").dataTable({
  5. "bProcessing": true,
  6. "bServerSide": true,
  7. "sAjaxSource": baseurl+'broker/get_broker_listing',
  8. "sPaginationType": "bootstrap",
  9. "columnDefs": [ {
  10. "targets": 'no-sort',
  11. "orderable": false,
  12. }],
  13. "fnRowCallback": function(nRow, aData, iDisplayIndex) {
  14. nRow.setAttribute('id',"tr_"+aData[0]);
  15. }
  16. });
  17. });
  18. $(function() {
  19. $(document).on('click', '.removeRcords', function(event) {
  20. event.preventDefault();
  21. var idss=$(this).attr('id');
  22. var rid=idss.split("_")[1];
  23. do_remove_ajax('broker_remove',rid);
  24. });
  25. });
  26. </script>
3. Your controller function will go like below
  1. public function get_broker_listing() {
  2. $this->load->model('common');
  3. $aColumns = array('broker_id' ,'name', 'email', 'created_date', 'status');
  4. $sIndexColumn = "broker_id";
  5. $sTable = "cbf_broker_registration";
  6. $iDisplayStart=$this->input->get('iDisplayStart',true);
  7. $iDisplayLength=$this->input->get('iDisplayLength',true);
  8. $iSortCol_0=$this->input->get('iSortCol_0',true);
  9. $iSortingCols=$this->input->get('iSortingCols',true);
  10. $sLimit = "";
  11. if ( isset($iDisplayStart) && $iDisplayLength != '-1' )
  12. {
  13. $sLimit = "LIMIT ". $iDisplayStart.", ".$iDisplayLength;
  14. }
  15. if ( isset($iSortCol_0))
  16. {
  17. $sOrder = "ORDER BY ";
  18. for($i=0 ; $i<intval( $iSortingCols ) ; $i++ ){
  19. if($_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
  20. {
  21. $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
  22. ".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
  23. }
  24. }
  25. $sOrder = substr_replace( $sOrder, "", -2 );
  26. if( $sOrder == "ORDER BY" ){
  27. $sOrder = "";
  28. }
  29. }
  30. $sSearch=$this->input->get('sSearch',true);
  31. $sWhere = "";
  32. if ( $sSearch != "" ){
  33. $sWhere = "WHERE (";
  34. for ( $i=0 ; $i<count($aColumns) ; $i++ ){
  35. $sWhere .= $aColumns[$i]." LIKE '%".$sSearch."%' OR ";
  36. }
  37. $sWhere = substr_replace( $sWhere, "", -3 );
  38. $sWhere .= ')';
  39. }
  40. /* Individual column filtering */
  41. for($i=0 ; $i<count($aColumns) ; $i++){
  42. if($_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != ''){
  43. if($sWhere == ""){
  44. $sWhere = "WHERE ";
  45. }else{
  46. $sWhere .= " AND ";
  47. }
  48. $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%'";
  49. }
  50. }
  51. $sEcho=$_GET['sEcho'];
  52. $result=$this->common->broker_listing($sTable, $sWhere, $sOrder, $sLimit, $aColumns,$sIndexColumn,
  53. $sEcho);
  54. echo json_encode($result);
  55. }
4. Your model function will goes like below. you can also give edit and remove functionality for that just returning Edit Link and class " removeRcords ". you can put other links as your requirement.
  1. function broker_listing($sTable, $sWhere, $sOrder, $sLimit, $aColumns,$sIndexColumn,$sEcho) {
  2. $sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
  3. FROM $sTable $sWhere $sOrder $sLimit";
  4. $rResult = $this->db->query($sQuery);
  5. $rResult_array=$rResult->result_array();
  6. $iFilteredTotal = count($rResult_array);
  7. /* Total data set length */
  8. $sQuery_TR = "SELECT COUNT(".$sIndexColumn.") AS TotalRecords FROM $sTable";
  9. $rResult_TR = $this->db->query($sQuery_TR);
  10. $rResult_array_TR=$rResult_TR->result_array();
  11. $iTotal = $rResult_array_TR[0]['TotalRecords'];
  12. $output = array("sEcho" => intval($sEcho),"iTotalRecords" => intval($iTotal),
  13. "iTotalDisplayRecords" => intval($iTotal), //$iFilteredTotal,
  14. "aaData" => array()
  15. );
  16. foreach($rResult_array as $aRow){
  17. $row = array();
  18. foreach($aColumns as $col){
  19. if($aRow[$col]=='D'){
  20. $row[] = 'Disable';
  21. }else{
  22. $row[] = $aRow[$col];
  23. }
  24. }
  25. array_push($row, '<a href="'.base_url().'admin/broker/edit_broker/'.$aRow['broker_id'].'"
  26. class="editRcords btn btn-default btn-sm btn-icon icon-left"><i class="entypo-pencil"></i>
  27. Edit</a> <a href="javascript:void(0)" id="brkr_'.$aRow['broker_id'].'"
  28. class="removeRcords btn btn-danger btn-sm btn-icon icon-left">
  29. <i class="entypo-cancel"></i> Remove</a>');
  30. $output['aaData'][] = $row;
  31. }
  32. return $output;
  33. }
5. You can setup jQuery function through out your project OR Application. you have to pass two param action_key and id for removing records.
  1. function do_remove_ajax(action_key,id){
  2. $.ajax({
  3. url baseurl+'controller/do_remove',
  4. type 'POST',
  5. data{idid,action_keyaction_key},
  6. dataType 'json',
  7. beforeSend function() {
  8. },
  9. complete function() {
  10. },
  11. success function(response) {
  12. switch (response.Mstatus) {
  13. case 'success'
  14. $("#"+response.process_id).hide();
  15. break;
  16. case 'error'
  17. showalert(response.msg,'showmessage_jscbf');
  18. break;
  19. default
  20. break;
  21. }
  22. }
  23. });
  24. }
6. Your view load function will goes like below
  1. public function view_broker() {
  2. $data['meta_title'] = 'Broker Listing';
  3. $data['meta_keywords'] = 'Broker Listing';
  4. $data['meta_desc'] = 'Broker Listing';
  5. $data['sidebarmenu'] = 'sidebar_menu';
  6. $data['top_menu'] = 'top_menu';
  7. $data['main'] = 'broker_listing';
  8. $data['footer'] = 'footer';
  9. $this->load->vars($data);
  10. $this->load->view($this->admin_dashboard);
  11. }
NOTE: Flow goes like below sidebar menu link click--->view_broker() function call---> call ajax function get_broker_listing() ---> call model function broker_listing--->controller return json formate required for datatables.

Thursday, 14 May 2015

Creating store procedure Mysql Insert

Showing you some examples of creating store procedure in mysql.
1. "At The Rate" sign used for local variable declare.
2. For calling a store procedure use function below. i am using Codeigniter.
  1. public function AddBooking(){
  2. $sql="call usp_AddBooking()";
  3. $parameters=array();
  4. $query = $this->db->query($sql,$parameters);
  5. return $query->result();
  6. }
  7. DROP PROCEDURE IF EXISTS `usp_AddBooking` $$
  8. CREATE PROCEDURE `usp_AddBooking`(
  9. IN iVendorId INT,
  10. IN iCustomerId INT,
  11. IN iServiceId INT,
  12. IN dServiceBookingTime DATETIME,
  13. IN dArrivalTime DATETIME
  14. )
  15. BEGIN
  16. DECLARE iBookingId INT default 0;
  17. BEGIN
  18. -- ERROR
  19. set ErrorCode = -999;
  20. rollback;
  21. END;
  22. DECLARE exit handler for sqlwarning
  23. BEGIN
  24. -- WARNING
  25. set ErrorCode = -888;
  26. rollback;
  27. END;
  28. START TRANSACTION;
  29. INSERT INTO skin_booking
  30. (iVendorId
  31. ,iCustomerId
  32. ,iServiceId
  33. ,dServiceBookingTime
  34. ,dArrivalTime
  35. ,eStatus
  36. ,dCreatedDate
  37. ,iBookingId
  38. )
  39. VALUES
  40. (iVendorId
  41. ,iCustomerId
  42. ,iServiceId
  43. ,dServiceBookingTime
  44. ,dArrivalTime
  45. ,'1'
  46. ,NOW()
  47. ,iBookingId
  48. );
  49. SET @iBookingId = LAST_INSERT_ID();
  50. SELECT @iBookingId as BookingId;
  51. COMMIT;
  52. END$$

Register users and login through store procedure mysql

1. Signup a user through store procedure.
2. "mysecret" here you can use your key. password will be encrypted using AES
3. You can call store procedure like below
  1. CALL`AddCustomerDetails`('David Warnor','david@gmail.com','12','male','2377.34','34343.343');
  2. CREATE PROCEDURE `AddCustomerDetails`(
  3. IN `vCustomerName` VARCHAR(50),
  4. IN `vEmail` VARCHAR(50),
  5. IN `vPassword` VARCHAR(50),
  6. IN `eGender` VARCHAR(10),
  7. IN `dLatitude` FLOAT,
  8. IN `dLongitude` FLOAT
  9. )
  10. BEGIN
  11. DECLARE ResultCount INT default 0;
  12. DECLARE skey VARCHAR(15) default 'mysecret';
  13. DECLARE eStatus INT default 1;
  14. DECLARE iCustomerId INT;
  15.  
  16. SET @ResultCount = (SELECT COUNT(iCustomerId) FROM table_name WHERE vEmail = vEmail);
  17. IF (@ResultCount > 0) THEN
  18. SET @iCustomerId = 0;
  19. SELECT @iCustomerId;
  20. ELSE
  21. INSERT INTO table_name
  22. (vCustomerName
  23. ,vEmail
  24. ,vPassword
  25. ,eGender
  26. ,dLatitude
  27. ,dLongitude
  28. ,eStatus
  29. ,dCreatedDate
  30. )
  31. VALUES
  32. (vCustomerName
  33. ,vEmail
  34. ,AES_ENCRYPT(vPassword,skey)
  35. ,eGender
  36. ,dLatitude
  37. ,dLongitude
  38. ,eStatus
  39. ,NOW()
  40. );
  41. SET @iCustomerId = LAST_INSERT_ID();
  42. SELECT @iCustomerId as CustomerId;
  43. END IF;
  44. END
1. Now above will add a entry to your mysql table let create a store procedure which will validate and check credentials.
  1. ALL `CheckLogin`('david@gmail.com', '123123', '0');
  2. CREATE PROCEDURE `CheckLogin`(
  3. IN `Email` VARCHAR(255),
  4. IN `Psw` VARCHAR(255),
  5. IN `UserType` INT(11)
  6. )
  7. BEGIN
  8. DECLARE ResultCount INT;
  9. DECLARE ResultMessage varchar(15);
  10. DECLARE skey VARCHAR(15) default 'secrets';
  11. IF (UserType = 0) THEN
  12. SET @ResultCount = (SELECT COUNT(C.iCustomerId) FROM customerdetails C
  13. WHERE C.vEmail = Email AND C.vPassword = AES_ENCRYPT(Psw,skey) AND C.eStatus = 1);
  14. IF (@ResultCount > 0) THEN #For Customer
  15. SELECT * from customerdetails C WHERE C.vEmail = Email AND C.vPassword = AES_ENCRYPT(Psw,skey)
  16. AND C.eStatus = 1;
  17. ELSE
  18. SET @ResultMessage='User not found.';
  19. SELECT @ResultMessage;
  20. END IF;
  21. ELSE
  22. SET @ResultCount = (SELECT COUNT(V.iVendorId) FROM vendor V WHERE V.vEmail = Email
  23. AND V.vPassword = AES_ENCRYPT(Psw,skey) AND V.eStatus = 1);
  24. IF (@ResultCount > 0) THEN
  25. SELECT * from vendor V WHERE V.vEmail = Email AND V.vPassword = AES_ENCRYPT(Psw,skey)
  26. AND V.eStatus = 1;
  27. ELSE
  28. SET @ResultMessage='vendor not found.';
  29. SELECT @ResultMessage;
  30. END IF;
  31. END IF;
  32. END

Monday, 11 May 2015

Ajax captcha using codeigniter php bootstrapvalidator

I will show you how you can create a captcha validation with Codeiginter based on Ajax.
1. Below is my model name as Mcaptcha
  1. class Mcaptcha extends CI_Model {
  2. protected $ci;
  3. function __construct() {
  4. // Call the Model constructor
  5. parent::__construct();
  6. $this->ci =& get_instance();
  7. }
  8. function setCaptcha(){
  9. $this->load->helper('captcha');
  10. $rand = substr(md5(microtime()),rand(0,26),5);
  11. $vals = array(
  12. 'img_path' => FCPATH.'assets/captcha/',
  13. 'img_url' => base_url().'assets/captcha/',
  14. 'expiration' => 1800,// half hour
  15. 'font_path' => FCPATH.'assets/fonts/Cabin-BoldItalic.ttf',
  16. 'img_width' => '140',
  17. 'img_height' => 30,
  18. 'word' => $rand,
  19. );
  20. $cap = create_captcha($vals);
  21. $this->ci->session->set_userdata(array('cpt'=>$rand, 'img' => $cap['time'].'.jpg'));
  22. return $cap['image'] ;
  23. }
  24. }
2. Your controller function will goes like below
  1. public function send_us_email() {
  2. $this->load->library('form_validation');
  3. $this->load->model('mcaptcha');
  4. $this->form_validation->set_error_delimiters('<span>', '</span>');
  5. $this->form_validation->set_rules('sname', 'Name', 'trim|required|max_length[20]|xss_clean');
  6. $this->form_validation->set_rules('captcha', 'Captcha', 'trim|required|max_length[5]|
  7. callback_validate_captcha|xss_clean');
  8. if ($this->form_validation->run() == FALSE){
  9. // if any fields on form not validated properly we need to unset session and unlink captcha
  10. image previously created and then regenerate captcha and passing it to Cmessage.
  11. if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
  12. unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
  13. $this->session->unset_userdata('cpt');
  14. $this->session->unset_userdata('img');
  15. $captcha = $this->mcaptcha->setCaptcha();
  16. echo json_encode(array('Mstatus'=>'error','Cmessage'=>$captcha,'msg' => validation_errors()));
  17. }else{
  18. $sname=set_value('sname');
  19. $captcha=set_value('captcha');
  20. $data=array('name'=>$sname);
  21. $send_us_a_email_template= $this->load->view('email_templates/send_us_a_email', $data, true);
  22. $this->email->from('youremail@domain.com',"YourTITLE");
  23. $this->email->to($semail);
  24. $this->email->subject('Customer Query Request');
  25. $this->email->message($send_us_a_email_template);
  26. if ($this->email->send()){
  27. // same logic above if every thing goes well.
  28. if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
  29. unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
  30. $this->session->unset_userdata('cpt');
  31. $this->session->unset_userdata('img');
  32. echo json_encode(array('Mstatus'=>'success','Cmessage'=>'We have recieved
  33. your email and we will get back to you shortly. Thanks.','msg'=>''));
  34. }else{
  35. echo json_encode(array('Mstatus'=>'error','Cmessage'=>'','msg' => 'Error
  36. in processing your query. Please try later.'));
  37. }
  38. }
  39. }
3. Below is call back function to validate captcha enter by user.
  1. public function validate_captcha($str){
  2. if($str != $this->session->userdata['cpt']){
  3. $this->form_validation->set_message('validate_captcha', 'Wrong captcha code,
  4. hmm are you the Terminator?');
  5. return false;
  6. }else{
  7. return true;
  8. }
  9. }
4. Your jQuery goes like below
  1. $(document).ready(function() {
  2. $('#submit-link-form').bootstrapValidator({
  3. message: 'This value is not valid',
  4. feedbackIcons: {
  5. valid: 'glyphicon glyphicon-ok',
  6. invalid: 'glyphicon glyphicon-remove',
  7. validating: 'glyphicon glyphicon-refresh'
  8. },
  9. fields: {
  10. linkname: {
  11. validators: {
  12. notEmpty: {
  13. message: 'The name is required.'
  14. },
  15. stringLength: {
  16. min: 4,
  17. message: 'Name must be 4 characters long.'
  18. }
  19. }
  20. },
  21. scaptcha: {
  22. validators: {
  23. notEmpty: {
  24. message: 'Captcha verification is required.'
  25. }
  26. }
  27. }
  28. }
  29. })
  30. .on('success.form.bv', function(e) {
  31. e.preventDefault();
  32. var $form = $(e.target);
  33. var bv = $form.data('bootstrapValidator');
  34. $.ajax({
  35. url: $form.attr('action')+'?time='+timestamp,
  36. type: $form.attr('method'),
  37. data: $form.serialize(),
  38. dataType:'json',
  39. beforeSend: function() {
  40. },
  41. complete: function() {
  42. },
  43. success: function(response){
  44. switch(response.Mstatus){
  45. case 'success':
  46. break;
  47. case 'error':
  48. break;
  49. default:
  50. break;
  51. }
  52. }
  53. });
  54. });
  55. });
5. Your bootstrap model popup will looks like below
  1. <div class="container">
  2. <div class="modal fade animate1 faster-modal" id="send-us-email-modal" tabindex="-1" role="dialog"
  3. aria-labelledby="sendusemailLabel" aria-hidden="true">
  4. <div class="modal-dialog">
  5. <div class="modal-content">
  6. <div class="modal-header">
  7. <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span>
  8. <span class="sr-only">Close</span></button>
  9. <h4 class="modal-title" id="sendusemailLabel">Send Us Email</h4>
  10. </div>
  11. <div class="modal-body">
  12. <?php echo form_open(base_url().'root/send_us_email',array('id' =>'send-us-email-form',
  13. 'name' =>'send-us-email-form','method'=>'post'));?>
  14. <div class="faster-ajax-loader faster_ajax_loader" style="display:none;"></div>
  15. <aside class="form-group">
  16. <div class="popup_message"></div>
  17. </aside>
  18. <aside class="form-group">
  19. <input type="text" class="form-control required" placeholder="Your Name" name="sname" id="sname" />
  20. </aside>
  21. <aside class="form-group form-capcha"> <span class="generated-capcha"><img
  22. src="<?php echo base_url();?>images/default.jpg" width="140" height="30" alt="Verification Code">
  23. </span><a href="javascript:void(0);" title="Refresh Verification Code">
  24. <span class="glyphicon glyphicon-refresh refresh-regenerate"></span></a> </aside>
  25. <aside class="form-group">
  26. <input class="form-control text required" id="captcha" type="text" name="captcha" value=""
  27. placeholder="Verification Code" />
  28. </aside>
  29. <aside class="form-group">
  30. <input type="submit" class="btn-features animate1" value="Send Us Email" />
  31. </aside>
  32. </form>
  33. </div>
  34. </div>
  35. </div>
  36. </div>
  37. </div>
6. If you would like to refresh captcha if it is not visible properly to users then refresh captcha on Link / Image click .Your js code will goes like below
  1. $(function(){
  2. $(document).on('click', '.refresh-regenerate', function(){
  3. var myformclick=$(this).closest('form').attr('id');
  4. $.ajax({
  5. url: baseurl+"root/generate_captcha",
  6. type: "POST",
  7. data: "cap=1",
  8. cache: false,
  9. dataType:'json',
  10. beforeSend: function() {
  11. $("#"+myformclick).find(".faster_ajax_loader").css('display','block');
  12. },
  13. complete: function() {
  14. $("#"+myformclick).find(".faster_ajax_loader").css('display','none');
  15. },
  16. success: function(response){
  17. $("#"+myformclick).find(".generated-capcha").html(response.Cmessage);
  18. }
  19. });
  20. });
  21. });
7. I am calling generate_captcha function so that on each click new captcha image will be generated.
  1. public function generate_captcha(){
  2. if(file_exists(FCPATH."assets/captcha/".$this->session->userdata['img']))
  3. unlink(FCPATH."assets/captcha/".$this->session->userdata['img']);
  4. $this->load->model('mcaptcha');
  5. $this->session->unset_userdata('cpt');
  6. $this->session->unset_userdata('img');
  7. $captcha = $this->mcaptcha->setCaptcha();
  8. echo json_encode(array('Mstatus'=>'success','Cmessage'=>$captcha,'msg' => validation_errors()));
  9. }

Creating subdomain on amazon ubuntu Ec2

1. Create a directory from command line
  1. sudo touch /var/www/your-directory
2. Create a conf file on location /etc/apache2/site-available/
  1. i. sudo touch /etc/apache2/site-available/your-directory-name.domainname.com.conf
  2. ii. Just copy 000-default.config data to newly created file above
  3. sudo cp /etc/apache2/site-available/000-default.conf
  4. /etc/apache2/site-available/your-directory-name.domainname.com.conf
  5. iii. open file for edit
  6. sudo nano /etc/apache2/site-available/your-directory-name.domainname.com.conf
  7. and replace
  8.  
  9. DocumentRoot /var/www/your-directory-name
  10.  
  11. iv. sudo service apache2 reload.
  12. v. sudo service apache2 restart.
3. After above process go to amazon hosted zone just follow below steps
  1. 1. create a records set put name of your choice in name required fields
  2. 2. put www.yourdomain.com. in value and save records set.

Minify your javascript files offline with uglifyjs

You can compress or minify your Javascript / jQuery code by visiting to resources which is available but if you want to use it on your localhost so you can use it and run like below on windows.
  1. 1. Installed Node.js
  2. 2. Set envirnment variable
  3. NODE_PATH
  4. C:\Program Files\nodejs\UglifyJS\bin\uglify;C:\Program Files\nodejs\node.exe;
  5. 3. Download uglify master from gits and put in folder
  6. C:\Program Files\nodejs\uglifyjs
  7. 4. run command
  8. Run npm -g install uglify-js
  9. final if you want to minify js
  10. 5. Run uglifyjs -o app.min.js app.js
Note: app.min.js is your name and app.js is your source js which you want to compress OR minify.

Tomcat 8.0.21 running in ubuntu 14.04 TLS

I am explaining every step to run tomcat in ubuntu 8.0.21 and how to setup your projects and running Servlets ,Jsp.
1. Install JDK 7 before installing tomcat.
  1. sudo apt-get install openjdk-7-jdk
2. Download the latest version of tomcat tomcat.apache.org , i downloaded Apache Tomcat 8.0.21
  1. I rename dowonload folder to "apache-tomcat"
  2. and move it to location /usr/local/apache-tomcat
  3. go to /usr/local/apache-tomcat/conf/tomcat-users.xml
  4. or you can edit from terminal sudo nano /usr/local/apache-tomcat/conf/tomcat-users.xml
  5. place below lines & save. [ctrl+^+x then press Y]
  6. <role rolename="manager-gui">
  7. <role rolename="admin-gui">
  8. <user password="rohit" roles="manager-gui,admin-gui" username="rohit">
  9. </user>
  10. </role>
  11. </role>
3. We have to create a bash file for running and stoping tomcat. Create a new file tomcat8021 in /etc/init.d/ and add the below code
  1. #!/bin/bash
  2. export CATALINA_HOME=/usr/local/apache-tomcat
  3. PATH=/sbin:/bin:/usr/sbin:/usr/bin
  4. start() {
  5. sh $CATALINA_HOME/bin/startup.sh
  6. }
  7. stop() {
  8. sh $CATALINA_HOME/bin/shutdown.sh
  9. }
  10. case $1 in
  11. start|stop) $1;;
  12. restart) stop; start;;
  13. *) echo "Run as $0 "; exit 1;;
  14. esac
4. Give 755 permission
  1. sudo chmod 755 /etc/init.d/tomcat8021
5. For starting stoping tomcat
  1. sudo /etc/init.d/tomcat8021 start / stop
6. We need to set Classpath and java home varibale to work properly. so i edited the file call environment place below lines there.
  1. sudo nano /etc/environment
  2. CLASSPATH=.:/usr/lib/jvm/default-java/bin:/usr/local/apache-tomcat/lib/servlet-api.jar
  3. JAVA_HOME=/usr/lib/jvm/default-java

Creating a new project in ubuntu 14.04 TLS

1. I created a folder called store in /usr/local/apache-tomcat/
2. store(Project Folder) ---> WEB-INF ---> classes(DIR) , lib(DIR) , web.xml (file)
3. web.xml file looks like below
  1. <web-app>
  2. <servlet>
  3. <servlet-name>HelloWorld</servlet-name>
  4. <servlet-class>HelloWorld</servlet-class>
  5. </servlet>
  6. <servlet-mapping>
  7. <servlet-name>HelloWorld</servlet-name>
  8. <url-pattern>/HelloWorld</url-pattern>
  9. </servlet-mapping>
  10. </web-app>
4. Inside classes folder your source file HelloWorld.java will be store for compiling it use below command
  1. mangel@mangel-desktop:/usr/local/apache-tomcat/webapps/store/WEB-INF/classes$
  2. javac -classpath /usr/local/apache-tomcat/lib/servlet-api.jar HelloWorld.java
5. After compile .class file created by above command , then you need to create a context file ,
  1. Go to cd /usr/local/apache-tomcat/conf/Catalina/localhost/ from terminal.
  2. sudo nano store.xml (store is the name of your project folder).
  3. Just paste below line
  4. <!-- Store Context -->
  5. <context debug="0" docbase="store" path="/store" reloadable="true">
  6. </context>
So above all configure manually. just open locahost:8080/store/HelloWord.

Creating subdomain on Digital Ocean

Directory
  1. html refers to main site.
  2. demo , blog outside html (folder) refers to subdomain.
1. Create a directory from command line
  1. sudo touch /var/www/your-directory
2. Create a conf file on location /etc/apache2/site-available/
  1. sudo touch /etc/apache2/sites-available/your-directory-name.domainname.com.conf
  2. Just copy 000-default.config data to newly created file above by below command
  3. sudo cp /etc/apache2/sites-available/000-default.conf
  4. /etc/apache2/site-available/your-directory-name.domainname.com.conf
  5. open file for edit
  6. sudo nano /etc/apache2/sites-available/your-directory-name.domainname.com.conf
  7. and replace
  8. DocumentRoot /var/www/your-directory-name
  9. sudo service apache2 reload.
  10. sudo service apache2 restart.
3. After above proceee go to amazon hosted zone just follow below steps.
  1. Create a records set put name of your choice in name required fields
  2. Put www.yourdomain.com. in value and save records set. it will take 10-15 min to process by amazon.