Thursday, December 18, 2014

Sample Web-service method in Groovy and how to call it

You might have heard about Webservice.

 Don't just use facebook or twitter or google! 
 Understand how things work in the background. 
 Read this short blog post I wrote to learn how the pages you see and the mobile 
 apps you use communicate with servers.  

Web service is a method of communication between two electronic devices over a network. It is a software function provided at a network address over the Web with the service always on as in the concept of utility computing. The W3C defines a Web service generally as:-
a software system designed to support interoperable machine-to-machine interaction over a network.
Read what web services are from wikipedia and read the code.

Nowadays, This is how almost all new web and mobile apps work.

 class SampleController {  
     def action(String username, String course, String password){  
         return Grade.findByUsernameAndCourseAndPassword(username, course, password)
     }  
 }  

GET
 www.mu.com/sample/action?username=biniam&course=it&password=123  

POST
 www.mu.com/sample/action  
           {  
                "username":"biniam",  
                "course":"it",  
                "password":"123"  
           }  

Tuesday, December 16, 2014

Git Commit with Header and Multi-line Body

I found this interesting answer on Stackoverflow to add Git Commit with Header and Multi-line Body and I wanted to share it.


 git commit -m "Header Comes Here" -m "Multiline body Comes Here.   
 Add a title to your commit after -m enclosed in quotes, 
 then add the body of your comment after a second -m.  
 Press ENTER before closing the quotes to add a line break.  
 Repeat as needed.  
 Then close the quotes and hit ENTER twice to apply the commit."  

Thanks Jon Crowell

Sunday, November 23, 2014

Bootstrap CSS templating in Grails.

There are three ways of integrating Bootstrap CSS templating to Grails.

1. Using twitter bootstrap plugin       grails.org/plugin/twitter-bootstrap
2. Using kick start bootstrap plugin    grails.org/plugin/kickstart-with-bootstrap
3. Manually downloading boostrap source files from getbootstrap.com and putting the files in grails-app/assets (for Grails 2.4.3 and above) or in web-app/css and web-app/js folders

There is one good blog post about using bootstrap as a default template by Iraklis at foodforcoding.com/2013/05/25/grails-with-twitter-bootstrap/ (althought the blog entry is old)
Another video by Joe Rinehart explains how to integrate Twitter Bootstrap into a Grails application (can be found at www.infoq.com/presentations/grails-twitter-bootstrap/)

The github project of twitter-boostrap plugin at https://github.com/robfletcher/twitter-bootstrap-scaffolding is also a good help.

You can also look at my simple blogging system developed in grails which uses Bootstrap 3 at https://github.com/biniama/mubs

Importing your git repository from bitbucket (or any other VCS) to GitHub

Go to 

 1. https://import.github.com/new and enter the url of the old repository
 2. give it a repository name (or it will import the name automatically)
 3. select public vs private repo
 4. Click import

Good luck!

Friday, November 21, 2014

Edit/Update Page Implementation in JQuery and Grails

I have a page with a form where a user enters first name and last name.

When the 'Edit' button is clicked, I want the button's name to change to 'Update' and the textboxes to become editable.

Then, when the user finishes editing the fields, I want to call a controller method in Grails.

What I want is to call the controller method WHEN 'UPDATE' BUTTON IS CLICKED (NOT WHEN 'EDIT' BUTTON IS CLICKED).

Here is the solution!

Friday, September 26, 2014

Using the asset pipeline grails plugin to write Page Specific Javascript

The Grails Asset-Pipeline is a plugin used for managing and processing static assets in Grails applications. 

Asset-Pipeline functions include processing and minification of both CSS and JavaScript files. It is also capable of being extended to compile custom static assets, such as CoffeeScript or LESS.

Here is one way of using the asset pipeline grails plugin to write Page Specific Javascript

specific.js // will be included by default

      var pageSpecific = function() {  
           console.log('Hello from specific page!)  
      });  
      $(document).ready(function({  
           if($(document.body).data('page') == 'specific') {  
                pageSpecific())  
           }  
      }));  

index.gsp

 <meta name='layout' content='main'/>  
 <body data-page="specific">  
      <h1>Hello from Specific!</h1>  
 </body>  

main.gsp // modify so that it passes the data-page attribute to the JS (since index.gsp uses main as a layout)

 <body data-page"${pageProperty(name:'body.data-page')}">  
      // main body content  
 </body>

Wednesday, July 23, 2014

jQuery - Enable and Disable Textbox (Make fields editable) and Update Button Value

Here is an example of making an input field editable by enabling/disabling it. The example also changes the Value of the submit button from 'Edit' to 'Update'.

You can test the code at this JSFiddle.

 <!DOCTYPE html>  
 <head>  
 <title>jQuery enable/disable button</title>  
 <script type='text/javascript' src='http://code.jquery.com/jquery.min.js'></script>  
 <script type='text/javascript'>  
 $(function(){  
    $('#submitBtn').click(function(){  
           $('.enableOnInput').prop('disabled', false);  
           $('#submitBtn').val('Update');  
    });  
 });  
 </script>  
 <style type='text/css'>  
    /* Lets use a Google Web Font :) */  
    @import url(http://fonts.googleapis.com/css?family=Finger+Paint);  
    /* Basic CSS for positioning etc */  
    body {  
      font-family: 'Finger Paint', cursive;  
      background-image: url('bg.jpg');  
    }  
    #frame {  
      width: 700px;  
      margin: auto;  
      margin-top: 125px;  
      border: solid 1px #CCC;  
      /* SOME CSS3 DIV SHADOW */  
      -webkit-box-shadow: 0px 0px 10px #CCC;  
      -moz-box-shadow: 0px 0px 10px #CCC;  
      box-shadow: 0px 0px 10px #CCC;  
      /* CSS3 ROUNDED CORNERS */  
      -moz-border-radius: 5px;  
      -webkit-border-radius: 5px;  
      -khtml-border-radius: 5px;  
      border-radius: 5px;  
      background-color: #FFF;  
    }  
    #searchInput {  
      height: 30px;  
      line-height: 30px;  
      padding: 3px;  
      width: 300px;  
    }  
    #submitBtn {  
      height: 40px;  
      line-height: 40px;  
      width: 120px;  
      text-align: center;  
    }  
    #frame h1 {  
      text-align: center;  
    }  
    #frame div {  
      text-align: center;  
      margin-bottom: 30px;  
    }  
 </style>  
 </head>  
 <body>  
   <div id='frame'>    
           <div class='search'>  
                <h1>jQuery Enable and Disable button</h1>  
                <input type='text' name='searchQuery' id='searchInput' class='enableOnInput' disabled='disabled'/>   
                <input type='submit' name='submit' id='submitBtn' value='Edit'/>  
     </div>  
   </div>  
 </body>  
 </html>  

Tuesday, July 22, 2014

Grails: CreateCriteria with Projection

Here is an example of using createCriteria() function in grails using projection of sum.

This method returns the sum of Balance in from Finance model/domain.
You can put this code in Bootstrap.groovy to run it when the program starts.

 println Finance.createCriteria().list() {  
                eq('financeType', FinanceTypeEnum.SAVINGS)  
                projections {  
                     sum('balance')  
                }  
           }  


Grails: Displaying image stored in the database on gsp

Here is a Grails implementation of displaying image stored in the database (as byte[]) on gsp.

Notes: 

  • I have spring security core plugin configured
  • The image tag calls the controller's method directly and it uses the apps url and app.name from Config.groovy and application.properties
 FILE: Domain class - SecUser  

 class SecUser extends User {  
      String firstName  
      String middleName  
      String lastName  
     byte [] userPhoto  
      Date dateCreated  
      Date lastUpdated  
      static constraints = {  
       firstName blank: false  
       middleName blank: false  
       lastName blank: false  
       userPhoto nullable: true, maxSize:1024000  
      }  
     String toString() {  
       if(firstName && middleName && lastName){  
         return "${firstName} ${middleName} ${lastName}"  
       } else {  
         return username  
       }  
   }  
 }

 FILE: MyController 
 
      class DashboardController {  
           def springSecurityService  
           def index() {  
                render(view: 'index')  
           }  
           def displayAvatarForCurrentUser() {  
                User user = springSecurityService.getCurrentUser()  
                SartUser sartUser = SartUser.findByUsername(user.username)  
                response.outputStream << sartUser.userPhoto // write the photo to the outputstream  
                response.outputStream.flush()  
           }  
      }  
 FILE: show.gsp  
      <div>  
           <sec:ifLoggedIn>  
                <img src="${grailsApplication.config?.grails?.serverURL}/dashboard/displayAvatarForCurrentUser"/>  
           </sec:ifLoggedIn>  
           %{--If the user has logged in, then the avatar will be shown.--}%  
      </div>  

 FILE: Config.groovy  

      environments {  
           development {  
                grails.logging.jul.usebridge = true  
                grails.serverURL = "http://localhost:9090/${appName}"  
           }  
           test {  
                grails.serverURL = "http://localhost/${appName}"  
           }  
           production {  
                grails.logging.jul.usebridge = false  
                // TODO: grails.serverURL = "http://www.changeme.com/${appName}"  
           }  
      } 
 
 FILE: application.properties  

      app.name=samplegrailsappname  

Wednesday, June 25, 2014

Solving Error: “syntax error near unexpected token”

Detail Error:
: command not found
: command not found
'/build.sh: line 3: syntax error near unexpected token `{
'/build.sh: line 3: `function stop_channels(){

was thrown when I run
./build.sh

The issue was I opened the .sh (shell script) in Windows OS and Windows changed the end of the line to CRLF

I found this out by running

cat --show-nonprinting filename.extension
E.g.

cat --show-nonprinting test.sh

Or open the file in Notepad++ and click on the button circled in the figure below.

windows vs linux.PNG

Then, I converted it using

dos2unix filename.extension
[Install dos2unix if required]
E.g.

dos2unix myfile.txt
dos2unix myshell.sh



Thursday, June 12, 2014

Android: Solving "Error:The SDK Build Tools revision (19.0.1) is too low. Minimum required is 19.1.0"

After upgrading Android Studio to 0.6.0, I got this error

"Error:The SDK Build Tools revision (19.0.1) is too low. Minimum required is 19.1.0"

Solution:
Open build.gradle file in your project and change the buildToolsVersion from 19.0.1 to 19.1.0 like:

android {
    compileSdkVersion 19
    buildToolsVersion '19.1.0'
}

Then, Open Android SDK Manager and update the SDK Build-tools by installing version or revision (Rev.) 19.1.

Android SDK Manager: Installing Android SDK Build-tools (Rev. 19.1)

Using Custom Fonts in Grails

I want to include a custom font and I created a folder under web-app and named it 'fonts' and I copied my font to that folder. Then,

1. I added the fonts folder to be included as a grails resource in Config.groovy like:

 // What URL patterns should be processed by the resources plugin  
      grails.resources.adhoc.patterns = ['/images/*', '/css/*', '/js/*', '/plugins/*', '/fonts/*']  
     grails.resources.adhoc.includes = ['/images/**', '/css/**', '/js/**', '/plugins/**', '/fonts/**']  

2. Since I'm using Spring security plugin for grails, I added the 'fonts*' folder to 'permitAll' category of Requestmap.

  // Request map Stored in Database

 for (String url in [  
      '/', '/index', '/index.gsp', 'favicon.ico',  
      'js*', 'css*', 'images*', 'fonts*',  
      '/login', '/login*//**',  
       '/logout', '/logout*//**'  
      ]) {  
        
      Requestmap.findOrSaveByUrlAndConfigAttribute(url, 'permitAll').save()  
 }  

Tuesday, June 10, 2014

Grails: Listing all fields/variables in a Domain/Model

In this example, I assume your domain class name is 'Research' and the full package name is 'com.package.name.Research'

Way 1:

 Research.declaredFields.each{  
      if(!it.synthetic)  
           println it.name  
 }  

Way 2:

 def names = grailsApplication.getDomainClass('com.package.name.Research').persistentProperties.collect {   
           println it.name   
      }  
   
Way 3:

 def Research domainClass = grailsApplication.getGrailsDomainClass('Research')  
 def persistentProperties = domainClass.getPersistentProperties()  
 persisentProperties.each { property ->  
      println property  
 }  
   

Thursday, June 5, 2014

Run Windows Command prompt (CMD) in Full screen mode

I got this values for running Windows CMD in full screen mode. Width=237, Height=82

Open CMD, Right click on the title bar and select Properties and set this values.

For more info, read this.

Android Tips: How to (always) show Overflow in Action bar

Here is how!

try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField =                        ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if(menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

Tuesday, June 3, 2014

Parsing and Formatting a Date in Groovy/Grails

If you have a string variable containing a date value such as 2014-06-03T11:03:44.779+03, then:

First -  Convert it to Date using "parse" method of SimpleDateFormat
Seond - Format the Date using the format you want such as "yyyy-MM-dd" or "yyyy/MM/dd" or any other.

Code

import java.text.SimpleDateFormat
import java.text.DateFormat

String mydate = "2014-06-03T11:03:44.779+03"

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd")

Date parsedDate = formatter.parse(mydate)

Date formattedDate = formatter.format(parsedDate)

/* In one line
    Date parsedAndFormattedDate  =  formatter.format(formatter.parse(mydate))
*/

Wednesday, April 23, 2014

Android: How to call another activity when a button is pressed and close the first activity

Here is a complete class that shows how another activity is called when a button in the first activity is pressed.
public class FirstActivity extends Activity implements View.OnClickListener {

    Button goToSecondActivityButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.first_activity);

        ((TextView) findViewById(R.id.textRecommendationMessage)).setText("This is the first activity");

        goToSecondActivityButton= (Button) findViewById(R.id.button_go_to_second_activity);
        goToSecondActivityButton.setOnClickListener(this);
    }

     @Override
     public void onClick(View view) {

         goToSecondActivity();
    }

    private void goToSecondActivity() {

        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
        startActivity(intent);
        finish();
    }
}

Thursday, April 10, 2014

How to Reset the Root Password in MySql Database

Run the following commands separately to change/reset your 'root' user password in MySql database.

Some Info:

There is a database called 'mysql' in MySql which is the default database. It is where Users such as 'root' are stored.
In this script, it is assumed that your new password is 'MyNewPassword'. Hence, replace that with what ever you want your password to be.

UPDATE mysql.user 
SET Password=PASSWORD('MyNewPassword') 
WHERE User='root';

FLUSH PRIVILEGES;

More info can be found here.

Thursday, April 3, 2014

Android Emulator Shortcuts

These are the list of Android Emulator shortcuts for Windows.

Ctrl+F11 Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
1. Main Device Keys
Home Home Button
F2 Left Softkey / Menu / Settings button (or Page up)
Shift+f2 Right Softkey / Star button (or Page down)
Esc Back Button
F3 Call/ dial Button
F4 Hang up / end call button
F5 Search Button
2. Other Device Keys
Ctrl+F5 Volume up (or + on numeric keyboard with Num Lock off) Ctrl+F6 Volume down (or + on numeric keyboard with Num Lock off) F7 Power Button Ctrl+F3 Camera Button
Ctrl+F11 Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
F8 Toggle cell network
F9 Toggle code profiling
Alt+Enter Toggle fullscreen mode

Wednesday, February 26, 2014

Eclipse IDE and One Tip

Eclipse is an integrated development environment (IDE). It contains a base workspace and an extensible plug-in system for customizing the environment. Written mostly in Java, Eclipse can be used to develop applications [From Wikipedia].


Major Flavors of Eclipse


The Spring Tool Suite is an Eclipse-based development environment that is customized for developing Spring applications. It provides a ready-to-use environment to implement, debug, run, and deploy your Spring applications, including integrations for Pivotal tc Server, Pivotal Cloud Foundry, Git, Maven, AspectJ, and more.

The Groovy/Grails Tool Suite™ (GGTS) provides the best Eclipse-powered development environment for building Groovy and Grails applications.

TIP

How do I turn off "Automatically Switch to Debug Perspective" mode in Eclipse or its flavours?

1. Go to Preferences -> Run/Debug -> Perspectives -> 

2. Select 'NEVER' for the option of 'Open the associated perspective when application suspends'

Reading a Record/Row from SQLServer Database Using C#

First, Set up your connectionString and use the following code snippet in a method.

using (SqlConnection con = new SqlConnection(connectionString))
{

    con.Open();

    SqlCommand cmd = new SqlCommand("SELECT userid, username, email, city FROM USERS where username=@username and password=@password", con);
    cmd.Paramters.AddWithValue("@username", username);
    cmd.Parameters.AddWithValue("@password", password);
    cmd.CommandType = CommandType.Text;

    UserInfo info = new UserInfo();

    using (SqlDataReader rdr = cmd.ExecuteReader())
    {

        if (rdr.HasRows)
        {
            rdr.Read(); // get the first row

            info.UserID = rdr.GetInt32(0);
            info.UserName = rdr.GetString(1);
            info.Email = rdr.GetString(2);
            info.City = rdr.GetString(3);
        }
    }
}
Acknowledgement to: Tim of StackOverFlow.com