Wednesday, November 20, 2013

Eclipse : Birt : Build JDBC:MYSQL connection

For connecting the reports to mysql database was fun.
For that I followed the birt-installation-and-configuration which was easy to understand.

Now as per the tutorial for adding external file
Select Project > right click > properties > Classpath > Add external JARs and go to path /usr/share/java folder(For Ubuntu and for windows please check the link above).



Once this is done we create the new data source with mysql connection.
Navigator(in sidebar) > Data Source > Right Click > New Data Source

 

Once data source name is given click Next and
Select com.mysql.jdbc.Driver(v5.1)
Database URL add : jdbc:mysql://your_host_name/your_db_name
User Name and Password of the connection
Click on Test Connection
It should display dialog box as shown in the image below indicating that the connection is successfully build.

Monday, October 7, 2013

Liferay : Portlets : Task cannot continue because ECJ is not installed

While going through Liferay Portal 6.0 - Development Guide : Creating a Portlet I got error on running ant task.
Task cannot continue because ECJ is not installed.
ECJ was automatically installed. Please rerun your task.


After searching for solution got Solve ECJ error in liferay IDE on Liferay Solutions.

Just followed the steps suggested.
Window -> Preferences -> Ant -> Runtime 
Then Ant Home Button and  Add external jar called ecj.jar which was in plugin-sdk-folder-path/lib



And After running the Ant Task portlet deployed successfully.

Monday, September 9, 2013

SQL : Stored Procedures : Next working date

Working on stored procedures is fun. For 1 functionality, wanted to get next working date which will exclude saturday sundays and dates from holiday list table.

I got really nice solution on mysql-stored-procedure-for-computing. But only draw back was Recursive limit. But tried the solution added in comments.

Checked and it worked fine. Only change done in this solution that if no date provided for function it should take current date. And parameter numDays removed.

So if current date is 2013-09-04. 2013-09-05 and 2013-09-06 in holiday list table. 2013-09-07 is Saturday and 2013-09-08 Sunday.








The output should be















And instead of both functions changed one to stored procedure as below.
Stored Procedure : sp_get_next_working_date
/**
Stored Procedure : sp_get_next_working_date
Parameter : p_date as date
Description : Returns next working date excluding Saturday/ Sunday OR Date in holiday list table.
Dependency : Function fn_check_date_if_in_holiday_list 
**/

BEGIN
  DECLARE next_working_date DATE;
  SET next_working_date = p_date;

  IF p_date = 0 THEN 
    SET next_working_date = DATE(NOW()); 
  END IF;
  SET next_working_date = DATE_ADD(next_working_date, INTERVAL 1 DAY);

  WHILE fn_check_date_if_in_holiday_list(next_working_date) DO 
    SET next_working_date = DATE_ADD(next_working_date, INTERVAL 1 DAY);
  END WHILE;

  SELECT next_working_date;
END
Function : fn_check_date_if_in_holiday_list
/**
Function : fn_check_date_if_in_holiday_list
Parameter : p_date as date
Description : Checks if date is Saturday/ Sunday OR in holiday list table.
Dependent : sp_get_next_working_date
**/

DETERMINISTIC
BEGIN
  DECLARE dayOfWeek INT DEFAULT 0;
  DECLARE result BIT DEFAULT false;
  DECLARE holidayCount INT DEFAULT 0;

  SET dayOfWeek = DAYOFWEEK(p_date);
  SELECT COUNT(*) from TBLholidays where holiday_date = p_date INTO holidayCount;

  IF dayOfWeek = 7 or dayOfWeek = 1 or holidayCount > 0 THEN 
    SET result = true;
  END IF;

  RETURN result;
END

Thursday, September 5, 2013

Rails : Tasks : Truncate db with 1 command

Back to rails is fun.

Working on some project I wanted to clean the database to clear all junk data added while testing.

But wanted to do that with 1 command and checking if I can get clear database without opening pgadmin or run several commands like drop/ create/ migrate. And I also added seeds in the project to get default data for functionality.

I checked rake --tasks. Check below screen-shot with selected text.












That was the command which I was looking for. It worked. But it thrown error first that it can not drop database as per the notes in --tasks. But it first truncated/ migrated and at last the seeds were added to the tables. Easy....:). Loved it....:D

Wednesday, August 28, 2013

SQL : CASE statements

Using conditions in SQL statements is really useful. Specially when we need to compare 1 value based on conditions with multiple columns.

For example I have 1 table called tasks. Where I need to check the given date parameter should be greater than or equal to multiple columns based on the current tasks category.

I can easily do that by code. Can be ROR or PHP. But if we can get the data directly from database it gets really fast for any language.

In this situation CASE statements are really useful.

In this example I need to compare parameter date to start_date column if category is 'appointment' and to end_date if category is 'todo'.
SELECT * FROM tasks 
WHERE '2013-09-02' >=
CASE 
  WHEN tasks.category='appointment' THEN (date(start_date))
  WHEN tasks.category='todo' THEN (date(end_date))
END

Monday, August 26, 2013

Rails/ PHP : Ubuntu : Add autostart on system boot

There is never a thought of starting an application if working in PHP.
But for one of the project we were using node.js and if the PC gets restarted we have to manually start the node.js.

I have done this before for my local rails application previously(http://stefanwienert.net) and applied the same for this issue.

First added .conf file
sudo gedit /etc/init/run_nodejs.conf
This will open default editor with new file called run_nodejs.conf
Now add following text to the file
description "Run Node JS"

start on (net-device-up and local-filesystems)
stop on runlevel [016]
chdir /path_to_nodejs

setuid user_name  # set to the user, which should run the app
exec sudo -u user_name  "/path_to_nodejs/nodejs.sh"

respawn
## give up if I respawn 3 times in 60 seconds...
respawn limit 3 60
Now create 1 .sh file named nodejs.sh at location /path_to_nodejs.

and in nodejs.sh add following commands, to start node js services.

Also give permissions to the file as chmod +x nodejs.sh to make is executable.
and then just check with (.conf file name for following command)
sudo start run_nodejs
You can also restart and stop the service.

As I mentioned I have done this for rails application.
But had 1 issue. By default I have 1.9.3 ruby version for other projects and for only local project I am using 2.0.0.

In demoapp.sh I have added following code
#!/bin/bash
PATH=$PATH:/home/supriya/.rvm/bin
source "/home/supriya/.rvm/scripts/rvm"
source ".rvmrc" 

rvm use 2.0.0
rails s # -p port_u_want -e env_u_want
So with these commands after starting my pc I get my local demoapp project always running with 2.0.0 and no worries about the default gemset.
And while working on project I can run log with if any error checking
sudo tail -f /var/log/upstart/demoapp.log

Tuesday, July 23, 2013

Collection : Thenewboston (Video Tutorials)

Most of people find video tutorials very helpful more than reading books. As we understand more with watching practical examples.

Looking forward to other technologies I found a very useful site TheNewBoston by Bucky Roberts, who provides video tutorials for multiple languages like java, android, php, ruby and more.
Just go to tutorials section and check the list, for technologies you want to learn.

Sunday, June 16, 2013

PHP : Excel Reader

Reading excel sheets now a days is not that big challenge, but reading it with very advanced formulas is definitely a very big challenge. One of team really spent a very pressured day to work on this functionality.

We used PHPExcel but was not reading values from other sub-sheet while performing getCalculatedValue(). Everything else was working fine. Like dynamically adding new values and generating the excel. After opening the new excel it worked like the original with new values. But the main functionality which we wanted, was getCalculatedValue() to display the calculations on web page.

After checking other plugins we found one more excel reader at devzone.zend.com. Tried with our excel sheet which worked like a charm.

Really useful for getting advanced formulas calculated values. There is also a excel writer but I didn't check it yet.
The only limitation to this plugin is that it do not work with xlsx file.

Thursday, May 30, 2013

CakePHP = Rails Framework

As I said in previous posts I really miss rails framework while working for PHP web applications. Just looking around the best sites on rails I found that CakePHP has a similar framework like rails.

Was really excited to get hands on it. Downloaded the latest version of the framework and started the application. But crashed with several warnings like 'Warning: _cake_core_ cache was unable to write...'

After reading warnings and checking around for solution, found, that need to provide writable permissions to tmp in app folder chmod -R 777 app/tmp which really helped for starting the project smoothly. Also found the answer which is helpful for other errors.

Until now I found that it contains functions similar to rails like beforeFilter() and so on, although I am not yet familiar with this framework. But it contains many function which I tried to build in my framework like render or helpers.

I am really going to love this if it works like rails, and will have no complaints about PHP.

Thursday, May 16, 2013

QA : 3 : How to implement the twitter authentication in rails 3.2?

Question from Bala Chandar :

How to implement the twitter authentication in rails 3.2?

Answer :

There is a gem available for twitter authentication oauth-plugin by Pelle Braendgaard

Please check the link Twitter Authentication Settings.

Friday, April 12, 2013

Collection : Javascript : Using select tags for date selection

Now a days generally most of sites use calendar dialog boxes for selecting a date in forms. We get all functionality for that including leap years and 30 or 31 days depending on the month. But how can we get these all when we are using simple drop downs or select is the question. Well we can use javascript to validate the fields.
In this post we will use jquery for validating 3 dropdowns which are year, month and date. As I was working on PHP the example will hold PHP code.

In this example consider that we are working on employee joining form and we want to add a joining date.
In html
<div id="joiningDate">
  <?php 
    $joining_date = select_tag("employees[joining_date][month]", unserialize(MONTHS), date('F'), array('class' => 'month'));
    $joining_date .= select_tag("employees[joining_date][date]", unserialize(DAYS), date('j'), array(class' => 'date'));
    $joining_date .= select_tag("employees[joining_date][year]", array("2012", "2013", "2014", "2015", '2016', '2017'), date('Y'), array('class' => 'year'));
    echo $joining_date;
  ?>
</div>
Note : For select_tag please check Collection : PHP : select_tag

Define some constants for long arrays.
Constants
defined('MONTHS') or define("MONTHS", serialize(array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')));
defined('DAYS') or define('DAYS', serialize(array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31')));
Finally the javascript function which will actually play the magic in html. Check the comments for explanation. In Javascript file
$(document).ready(function(){
  validateDateFields('#joiningDate');
});

function validateDateFields(divID){
  // Jquery objects of date and month fields in new function
  var dateField = $(divID).find('select.date');
  var monthField = $(divID).find('select.month');

  // Months hash for adding or removing the options tags 
  var monthsHash = {
    'January' : 1, 
    'February' : 2, 
    'March' : 3, 
    'April' : 4, 
    'May' : 5, 
    'June' : 6, 
    'July' : 7, 
    'August' : 8, 
    'September' : 9, 
    'October' : 10, 
    'November' : 11, 
    'December' : 12
  };
  // Months with 31 days
  var fullMonth = [1, 3, 5, 7, 8, 10, 12];
  
  // Current values of the fields
  var dateVal = dateField.val();
  var monthVal = monthField.val();
  var yearVal = $(divID).find('select.year').val();
  
  // Check current year if leap year
  var isLeap = new Date(yearVal, 1, 29).getMonth() == 1;
  // Date field child node with options 29, 30 and 31
  var dateOption29 = dateField.children('option[value=29]');
  var dateOption30 = dateField.children('option[value=30]');
  var dateOption31 = dateField.children('option[value=31]');
  // defining other variable 
  var appendOptions;
    
  if(monthsHash[monthVal]==2){
    // First : If selected month in 2 or February
    if(isLeap){
      // If the selected year is leap year
      if(dateOption29.length == 0){
        // If date field child nodes do not have any option with value 29
        dateField.append('<option value=29>29</option>');        
      }
    }else{
      // If its not a leap year remove date field child node option with value 29
      dateOption29.remove();
    }
    // In month 2 or february by default remove date field child options with value 30 and 31
    dateOption30.remove();
    dateOption31.remove();
  }else if($.inArray(monthsHash[monthVal], fullMonth) > -1){
    // If the selected month is of 31 days 
    if(dateOption31.length == 0){
      // If option with value 31 do not exist 
      if(dateOption29.length == 0){
        // If option with value 29 do not exist 
        appendOptions += '<option value=29>29</option> <option value=30>30</option>';
      }else if(dateOption30.length == 0){
        // If option with value 30 do not exist 
        appendOptions += '<option value=30>30</option>';
      }
      appendOptions += '<option value=31>31</option>';
      // append options which do not exist in date field child nodes
      dateField.append(appendOptions);
    }
  }else{
    // If the selected month is of 30 days 
    if(dateOption29.length == 0){
      // If option with value 29 do not exist 
      dateField.append('<option value=29>29</option> <option value=30>30</option>');
    }else if(dateOption30.length == 0){
      // If option with value 30 do not exist 
      dateField.append('<option value=30>30</option>');
    }else if(dateOption31.length > 0){
      // If option with value 31 exist
      dateOption31.remove();
    }
  }
  
  // Add other code for updating any values here.
}

Thursday, March 28, 2013

PHP : Apple Push Notification (APN)

Hope you have read my previous post for Rails 3 : APN on Rails in which I tried apn_on_rails gem for sending notification to apple devices. I have also added the link for ManiacDev.Com in which you will get the steps for certification creation which are the most important steps for notifications.

Now for sending notification in PHP there is a great example available at raywenderlich.com : Apple Push Notification Services Tutorial: Part 1/2. You can download the example file at from given link in the post.



This is a PHP sample code. Just change the deviceToken, passphrase and message variables. Make changes as per your requirement. But again I faced some certification errors which were : ssl_connect returned=1 errno=0 state=sslv3 read finished a sslv3 alert certificate unknown and Neither PUB key nor PRIV key:: nested asn1 error. Nothing else got the wrong certificate generated. Just get the required certificate and you are good to go.
I really loved it.

Tuesday, March 5, 2013

Rails : Code : Split Records

I was very much impressed when I saw the split entry functionality in time-sheet project we were using. I wanted to try out same in ROR. But I will also try this out in PHP now. First we will look at ROR code.

Assume that we are creating a time-sheet project and we need to split the duration and considering, we already have the rails project with authentication, and now we generate a new section 'Time Records', which will store the records of users with duration.
I am running scaffold so we will have all views, controller and model.
 rails g scaffold time_records description:text duration:float parent_id:integer


Run migration to add table in database.
 rake db:migrate
Now we will add new record



This is a basic setup what we need till now. Once this base is complete we will start with actual requirement. Now first we need to add a anchor tag (link) with which the functionality will work. SO I have added it in index page.



In this example I am using javascript function for ajax call but it is not complusory, we can directly use send the user to the form page with out javascript. So I am using onclick attribute for calling a function.
<%= link_to 'Split', '#', :onClick => "split_duration_for_entry('split_#{time_record.id}', #{time_record.id})" %>
In that function
/* this is for spliting the duration */
function split_duration_for_entry( div, id ){
  var divid = "#"+div
  var classes = jQuery(".split_box");

  jQuery(classes).each(function(){
    var thisid = $(this).parent('td').attr('id')
    var v = jQuery("#"+thisid).next().val();
    jQuery("#"+thisid).html("<a href='#' onClick=\"split_duration_for_entry('"+thisid+"', "+id+")\">Split</a>")
  });

  actual_duration = $('#split_'+id).prev('td').html();
  jQuery.ajax({
    type: 'GET',
    url: '/time_records/split_entries_div',
    data:{'record_id' : id, 'actual_duration': actual_duration},
    success: function(transform){
      jQuery(divid).html(transform);
    }
  });
}

So this function will
  • Hide opened split duration divs if open.
  • Send the parameters(id and duration) to split_entries_div action in our controller.
  • Once the action is called display the partial with data and links.

In controller
def split_entries_div
  id = params[:record_id].to_i
  time_record = TimeRecord.find(id)
  render partial: "split_entries", locals: {record_id: id, old_duration: time_record.duration.to_f}, layout: false
end 
So here comes the partial.
  
<div class="split_box">
  <div>
    <%= hidden_field_tag "actual_duration#{record_id}", params[:actual_duration] %>
    <%= text_field_tag "old_duration_#{record_id}", params[:actual_duration], size: 5 %>
    <%= text_field_tag "new_duration_#{record_id}", 0, size: 5 %>
  </div>
  <div>
    <%= link_to 'Split', "#this", onClick: "split_entries(this, #{record_id})" %>
    <%= link_to "Cancel", "#this", onClick: "cancel_split_entry(this, #{record_id})" %>
  </div>
</div>
In CSS
.split_box{
  background: none repeat scroll 0 0 #EFEFEF;
  border: 4px solid #CCCCCC;
  width: 100px;
}

In this partial we will have
  • 2 main text fields which will contain the old duration for updating the original record and new duration for which we will be creating a new record.
  • 1 hidden field to keep the original duration so if the validation is called then we can again store the original duration value to old duration field.
  • 2 anchor tags for calling actual functionality and canceling the div poped up.



First the main functionality. Actual spliting/ updating the entry will be performed if the user clicks the split link. On which 'split_entries' function is called by passing record's id.

function split_entries( id ){
  var newrecrd;
  var new_record_val = jQuery("#new_duration_"+id).val();
  var old_record_val = jQuery("#old_duration_"+id).val();
  
  var actual = $("#actual_duration"+id).val();
  var total = parseFloat(old_record_val) + parseFloat(new_record_val);
  
  if(parseFloat(actual) < total ) {
    alert("Total duration for OLD and New records can not be greater than original value");
    jQuery("#old_duration_"+id).val(actual);
    jQuery("#new_duration_"+id).val(0);
    return false; 
  }else if(parseFloat(old_record_val) < 24){
    if(new_record_val==0 || new_record_val==""){
      newrecrd = false
    }else{
      newrecrd = true
    }

    cancel_split_entry(id);

    jQuery.ajax({
      type: 'GET',
      url: '/time_records/split_entries',
      data:{
        'newrecrd' : newrecrd,
        'old_id' : id,
        'old_duration': parseFloat(old_record_val).toFixed(2),
        'new_record_val' : parseFloat(new_record_val).toFixed(2)
      },
      success: function(transport){
        window.location.reload();
      }
    });
  }else {
    alert("Duration can not be greater than 24 hrs. Enter valid duration");
    return false;
  }
}

I have added some validations to this functionality
  • Duration can not be greater than 24 hours OR
  • The total of both value can not be greater that the original duration
We can just remove/ modify these validation as per our requirement

Other than that
  • If it passes the validation it will first check if the new duration value should not be blank or equal to 0. This will set true or false to local variable 'newrecrd' which will be passes to the action as parameter via ajax.
  • Original record is will be passes and old_id.
  • Both new duration and old duration will be passed to the action.
  
# split duration
  def split_entries
    @time_record = TimeRecord.find(params[:old_id].to_i)
    description = @time_record.description
    @time_record.update_attributes(description: description, duration: params[:old_duration])
    if params[:newrecrd]=='true'
      TimeRecord.create(description: description, duration: params[:new_record_val], parent_id: @time_record.id)
    end
    redirect_to :back
  end
In which get the original record and update the duration
  • if params[:newrecrd] is true then create a new record with new duration value.
And now in routes add
resources :time_records do 
  collection do 
    get 'split_entries'
    get 'split_entries_div'
  end
end



Once the set up is done restart the application and check the output


Get the code at Github : Split-Records

Friday, March 1, 2013

Collection : Dabblet

There are many tools now a days to check your HTML and CSS code directly in browser for quick development. Tools like Firebug or inbuilt developer tools in browsers helps a lot, to check instant changes and don't have to wait for loading the page each time for small changes.

Dabblet is also a very useful tool to develop and test your CSS and HTML code.



This supports the modern versions of browsers like chrome, firefox and safari. But do not support IE.



You can get more information on dabbel help page. Advantage of this is that you don't have to keep the file on local machine. You can just save it on the gist.github.com as anonymous or you can also sign in with your account for storing the changes.




The output can be viewed at http://dabblet.com/gist/5062815 or you can just view the code at github.com/anonymous/5062815. Also you can view the whole page result at result.dabblet.com.



Now as I have mentioned earlier that dabble do not support IE but you can just check the output after storing the changes to github.

Friday, February 22, 2013

PHP : MVC : Framework

I really missed rails framework and available helpers a lot while working on PHP.
But I really learned a lot while finding the similar functionalities in PHP.
I tried the some of the available PHP frameworks but didn't find anything like rails.

So I started to define helpers and functions for my current PHP project.
Currently it's not complete but working with minor bugs.
Bugs like
  If I try to call view without .php extension it works fine, but with .php extension it crashes.

Still missing the actual flow of MVC (model, views and controller)(need to work on it).

Folder structure for this application is as follows:
  
app    
    |- assets    
        |- fonts
        |- images
        |- javascripts
        |- stylesheets
    |- classes
    |- helpers
    |- views
        |- Folder
  config
    |- config.php
    |- constants.php
    |- database.php
    |- path_includes.php
    |- routes.php
  docs
  includes
    |- classes
        |- application.class.php
    |- helpers
        |- common_helper.php
    |- php
        |- active_queries.php
        |- authentication.php
        |- base.php
        |- structure.php
        |- word_plurals.php
  lib
  index.php
  login.php
  logout.php
  navigation.php
  session_settings.php
  signin.php
  ReadMe.txt
  
Need to do lots of changes.
I have uploaded the code to GitHub. If anyone can help me to solve the current bug that will be a great help.

Monday, January 14, 2013

PHP : API : Documentation

Documentation is very necessary for every project. I usually add comments for every function in my project but getting the whole summary to one place was important.

In rails I knew how to do it but in php?
I came across apigen for php project 'professional API documentation tool'.
Really great to see the result. Loved it.

So we need to download the pack from apigen.org



Extract it to required path and then follow the steps given at blogs.oracle.com. Nice post.

Thats it and we are ready with the api for our projects.