Tuesday, December 31, 2013

Youtube embed video html code without branding and controls (seekbar, play/pause and volume)

Youtube embedded player can be adjusted a lot using the parameters available here https://developers.google.com/youtube/player_parameters. Some parameters are available on both HTML5 and flash players and some are not.

Check out https://developers.google.com/youtube/youtube_player_demo, for all availabel configuration and play with it.

For example you can hide the controllers in embedded video,

Saturday, November 30, 2013

Java :: Get last date of a month

In Java we can use the Calendar class to get day_of_month, day_of_week etc. Last day of a month varies depending on the Month and on leap year we have extra day in February. So to figure out the last day of any given month in a year, we write some code which is apparently simple.

Calendar object allows us to manipulate days, go forward or backward on the Calendar, add days, hours, minutes or seconds to any given time etc. We will use these capabilities of Calendar class to get our last_of_month.

The idea here is to get the first day of next month and then reduce one day from it, which gives us the last day of the month relative to input date.

/**
 * The trick is to add a month, set the date as 1st and then reduce a date.
 *
 * @param calendar
 */
private static void setCalendarToLastDayOfMonth(Calendar calendar) {
    calendar.add(Calendar.MONTH, 1);
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    calendar.add(Calendar.DATE, -1);
}

But, Java Calendar has a better way of doing this, by using getActualMaximum() method which is far more convenient.

private static void setCalendarToLastDayOfMonth(Calendar calendar) {
    int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    calendar.set(Calendar.DAY_OF_MONTH, lastDay);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
}

A sample calendar util class which gives you few convenient methods is given below.

/**
 * Copyright (C) 2013 Deepu Mohan Puthrote. All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses/.
 */

import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.text.ParseException;

public class CalendarUtil {

    public static void main(String[] args) throws Exception {
        String string = "January 2, 2010";

        CalendarUtil calendarUtil = new CalendarUtil();

        System.out.println(calendarUtil.getLastDateOfMonth(string));
        System.out.println(calendarUtil.getLastDateOfMonth());
    }

    public Date getLastDateOfMonth() {
        return getLastDateOfMonth(new Date());
    }

    public Date getLastDateOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return getLastDateOfMonth(calendar);
    }

    public Date getLastDateOfMonth(Calendar calendar) {
        setCalendarToLastDayOfMonth(calendar);

        return calendar.getTime();
    }

    public Date getLastDateOfMonth(String date) throws ParseException {

        return getLastDateOfMonth(date, "MMMM d, yyyy");
    }

    public Date getLastDateOfMonth(String date, String format) throws ParseException {
        return getLastDateOfMonth(date, format, Locale.US);
    }

    public Date getLastDateOfMonth(String stringDate, String format, Locale locale) throws ParseException {
         Date date = new SimpleDateFormat(format, locale).parse(stringDate);

         return getLastDateOfMonth(date);
    }    

    private static void setCalendarToLastDayOfMonth(Calendar calendar) {
        int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, lastDay);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }
}

References
http://stackoverflow.com/questions/13624442/getting-last-day-of-the-month-in-given-string-date/
http://docs.oracle.com/javase/7/docs/api/java/util/Date.html
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
http://docs.oracle.com/javase/7/docs/api/java/util/Locale.html

Monday, October 14, 2013

How to change extension of multiple files (bash script)

The following is the script I use in Macbook (Mountain Lion). It should work on most *nix shell like bash, csh, ksh etc. However, I have tested it only in bash.

Monday, October 7, 2013

Correct way to embed Flash content

This A List Apart article discusses, a correct way of embedding Flash content in HTML, while following W3C standards.

If you need valid HTML content, that passes http://validator.w3.org/, you must use <object> tag, instead of <embed> tag.

Link: http://alistapart.com/article/flashsatay/

Wednesday, October 2, 2013

JavaMail :: javax.mail.NoSuchProviderException: smtp

When you are using Java's mailapi.jar, it also expects supporting libraries like smtp.jar, imap.jar, pop3.jar, gimap.jar, dsn.jar. If you are using Java EE platform, then it is already included. But if you are getting the following error, you might have to include additional libraries, from Java mail API.

Exception in thread "main" javax.mail.NoSuchProviderException: smtp
at javax.mail.Session.getService(Session.java:746)
at javax.mail.Session.getTransport(Session.java:685)
at javax.mail.Session.getTransport(Session.java:628)
at javax.mail.Session.getTransport(Session.java:608)
at javax.mail.Session.getTransport(Session.java:663)
at javax.mail.Transport.send0(Transport.java:154)
at javax.mail.Transport.send(Transport.java:80)

There are several forums and discussions happening on this same issue. Surprisingly, this is a small class path issue.

To solve this error, make sure you have both mailapi.jar and smtp.jar in your classpath. Also, make sure you don't have duplicate jar files in your class path.

Reading the FAQ on Oracle's documentation will give you a better idea. http://www.oracle.com/technetwork/java/javamail/faq/index.html

References

  1. http://www.oracle.com/technetwork/java/javamail/javamail-138606.html
  2. http://www.coderanch.com/t/601387/java/java/smtp-error/
  3. http://stackoverflow.com/questions/2980408/problem-with-java-mail-no-provider-for-smtp/
  4. http://stackoverflow.com/questions/16861553/javax-mail-nosuchproviderexception-no-provider-for-smtps/
  5. https://answers.atlassian.com/questions/167299/unable-to-send-email-and-error-as-javax-mail-nosuchproviderexception/

Sunday, September 8, 2013

Get content from ace editor to a textarea

Ace editor is awesome! We get to edit code with instant syntax highlighting. But often, we have to get the content from the editor, than just typing some with syntax highlighting. Ace editor have a function to get the value editor.getSession().getValue().

Here is a demo on getting value from the editor and setting it with textarea.

Fiddle here: http://jsfiddle.net/deepumohanp/tGF6y/

References

  1. How do I make a textarea an ace editor?

Monday, September 2, 2013

Javascript :: Ace Editor Positioning with Bootstrap3

Ace editor is a fantastic option for live source code editor on the web. One problem you come across when using Ace Editor is with the default absolute positioning. Also it doesn't fit inside a container div by default. Here is how I overcame these issues.

The example from ace website uses absolute positioning by default, as show below. But luckily, ace can work perfectly with relative positioning

Saturday, August 31, 2013

Blog Update :: Bootstrap awesomeness

Yesterday, I spend some to change the blog template using Bootstrap.

Thanks to Blogger's new template editor. Now it is much easier to understand the templates.

The template was built on top of my older template Simple by Joshua Peterson. The process was simple and straight forward.

Blogger templates are mostly collection of widgets. I introduced few new divs with Bootstrap classes and removed few divs from older template. Bootstrap documentation has everything clearly explained along with examples.

I haven't tested this new template on all screens yet.

Monday, July 29, 2013

Javascript :: Pass function as parameter

Javascript allows you to pass functions as parameter to another function and that makes Javascript super awesome!. Great things can be achieved from this power.

Quote from Mozilla developer website:

In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around just like any other object.

Every Javascript function is a Function object. Hence we can pass them as arguments, like any other object.

How to do that?

Passing function as parameter is no different from passing any other object when it comes to syntax.

I am gonna try and explain that with an example (hopefully, easy to understand)

Monday, June 24, 2013

Java :: Print "Hello World" without using Semicolon (;)

This Gist shows how to print something in Java, without the use of Semicolon (;). The code is self explanatory.

https://gist.github.com/WarFox/5847999

Friday, June 14, 2013

emacs:: Show line numbers in the left margin

So, I recently started using emacs as a text editor, instead of vi. It didn't seem easy to get things up straight at start. But gradually I understood why many experienced developers prefer emacs: it is highly customisable and extensible.

vi gives you easy to use command to show line numbers, :set nu and you are done. That is not the case with emacs, and hence this blog post. You need to install linum package and enable linum-mode for this.

Make sure you have the latest version of emacs, at the time of writing 24.3, so that you have emacs package manager ready. Add marmalade and melba to the package archive list by adding the following to your ~/.emacs.d/init.el.

(require 'package)                                                                                                      
(add-to-list 'package-archives                                                                                          
    '("marmalade" . "http://marmalade-repo.org/packages/") t)                                                           
(add-to-list 'package-archives                                                                                          
  '("melpa" . "http://melpa.milkbox.net/packages/") t)                                                                  
(package-initialize)                                                                                                    

Saturday, May 11, 2013

Turn off unlimited trailing whitespace in IntelliJ IDEA

By default, IntelliJ IDEA allows you to click any where on the editor and type. Some users find it annoying. If you are new to IntelliJ, you may find it a bit difficult to change the setting. This is available in the Virtual Space section of Editor Settings in IDEA preferences.

Turn it of by going to File menu -> Settings -> Editor -> Virtual Space and uncheck 'Allow placement of caret after end of line'.

Peace of mind.

Wednesday, March 27, 2013

Java :: Count the number of times a method is called

How to find how many times a method is used?

A general answer to this question would be something like this:

   public class MyClass {

     static int count = 0;

     public void myMethod() {
       count++;
     }

  }

Using static int would seem a perfect solution. Static will share the instance variable count among all instances of MyClass.

However, problem occurs in a multi threaded environment, as the count incrementation is not synchronised.

Tuesday, March 26, 2013

Java :: How to convert primitive char to String in Java

Char is 16 bit unsigned data type in Java used to store characters and String is an immutable array of char. In Java you cannot cast a primitive char element to String.

Below I have given five methods to convert a char to String. Also I have included common mistakes that gives compile time errors.

Thursday, March 21, 2013

Java :: Check whether two Strings are equal without using the equality(==) operator or the equals() method.

You can exploit the uniqueness property of Set Collection to accomplish this.

Observe the following code:

/**
 * Returns true if the given strings are equal. else returns false.
 *
 */ 
public boolean isEquals(String one, String two) {
    Set<String> temp = new HashSet<String>();
    temp.add(one);
    temp.add(two);

    return (temp.size() == 1);
}

The size of set will be greater than 1 only if the given strings are different. Ofcourse the add method will internally use equals() and hashCode() methods.

Thursday, March 7, 2013

Spring Roo :: Adjust text box size/width

Spring Roo uses Dojo's dijit.form.ValidationTextbox widget by default. This means only way to adjust textbox size is to adjust the width of widget. And this has to be done with widget attributes using Spring.addDecoration(); available in spring-js.

        Spring.addDecoration(new Spring.ElementDecoration({
            elementId : '_${sec_field}_id',
            widgetType : 'dijit.form.ValidationTextBox',
            widgetAttrs : {
                  promptMessage: '${sec_field_validation}',
                  invalidMessage: '${sec_field_invalid}',
                  required : ${required},
                  style: 'width: ${width}',
                  ${sec_validation_regex} missingMessage : '${sec_field_required}'
        }}));

Here I have used a new attribute width, which is added to input.tagx.

Usage:


Spring Roo input.tagx with adjustable width attribute

You may use the above gist as is or with modification

Wednesday, February 20, 2013

Spring Roo :: Adjusting Textarea rows and cols (width and height)

If you have been using Spring Roo for rapid application development, you know how messy things can get when you need UI customization. You could try to override the default standard.css for most cases. But things like adjusting the rows and columns in Textarea is not that easy.

Spring Roo uses Apache Tiles, jspx, tagx and Dojo extensively for UI manipulation. So customization can be a a bit hard, when you are a beginner. I had to set rows and columns for textarea in the form as it always defaulted to rows="3" and cols="20".

textarea.tagx can be found at the following location.

src/main/webapp/WEB-INF/tags/form/fields/textarea.tagx

I tried editing the textarea.tagx file to add cols and rows attributes to the form:textarea tag.


But this gets overridden when viewed in the browser. This behaviour is because dijit.form.SimpleTextarea widget is applied to the textarea after the DOM is loaded. So we have to set cols and rows as the dijit.form.SimpleTextarea widget's attributes.

    Spring.addDecoration(new Spring.ElementDecoration({
       elementId : '_${sec_field}_id', 
       widgetType : 'dijit.form.SimpleTextarea', 
       widgetAttrs : {
           cols: ${cols},
           disabled : ${disabled}, 
           rows: ${rows}
       }
    }));

I have done modification in textarea.tagx to include cols and rows as attributes. The full textarea.tagx can be found in the following gist.

Please note: The file is given .jsp extension to enable formatting in the gist. You just need textarea.tagx.

Copy and paste this code to your existing textarea.tagx to enjoy the benefits of cols and rows attributes.

Usage

Use this tagx as you would use the shipped textarea.tagx, with the new attributes


Friday, January 25, 2013

Linux :: Port is in use but pid not visible

Problem: A port is being used by some process but the pid of process is not visible

When the process is started by root, other users not in the root group cannot view the process ids. So when you do:

netstat -atnp

process id will not be visible to normal user.

You have to run netstat command with sudo, to view all process ids.

sudo netstat -atnp

A scenario I came across is when Apache tomcat was started as a Java service with jsvc command. The daemon.sh was run by the root user, so the process belonged to root.

Wednesday, January 16, 2013

Programming :: When to use Interfaces in your application

There are several advantages in utilising the features of Interfaces in general programming. As you may already know, interfaces define a set of functionality as a rule or a contract. When you implement an interface all of these functionality must be implemented in the concrete class.

The ideas discussed here can be applied using any programming language that supports Interfaces. Java has been used in examples for simplicity.

In general when one writes a simple program, one may not think about the need of using an Interface. But when you are building a larger system or a library which keeps evolving, it is a good idea to use Interface. A particular advantage of using interface in Java is that it allows multiple inheritance.

The full power of Interface is utilized when dependency injection techniques is used to inject required implementation on run time. Using references to interfaces instead of their concrete implementation classes helps in minimising ripple effects, as the user of an interface reference doesn't have to worry about the changes in the underlying concrete implementation.

To give an example consider our application has a layered architecture with Controller layer on top then Service layer, Repository layer and domain layer in that order. Here controller layer interacts with service layer and service layer interacts with repository layer. Each layer is aware of the services provided by the layer below it. We expose this information using Interface and hide the concrete implementation.

Let us say we have a UserRegistrationService, which registers a new user in our system. Our requirement is to save the user information in a relational database and also in xml files. If we were not using interface, the UserRegistrationService may be implemented with two functions saveToXML() and saveToDatabase().

public class UserRegistrationService {

    public void saveToXML(UserInfo userInfo) {
        //save to xml using service exposed by Repository layer
    }

    public void saveToDatabase(UserInfo userInfo) {
        //save to db using service exposed by Repository layer
    }
}

In this case, the UserRegistrationController should be aware of the concrete implementation of these two functions in UserRegistrationService to use them.

//Controller becomes complicated when additional features are required
public class UserRegistrationController {

    //Controller should be aware of the implementation when no Interface is used
    UserRegistrationService userRegistrationService = new UserRegistrationService();

    public void processRequest(UserInfo userInfo) {
        this.saveToXml(userInfo);
    }

    private void saveToXml(UserInfo userInfo) {
        userRegistrationService.saveToXml(userInfo);
    }

    private void saveToDatabase(UserInfo userInfo) {
        userRegistrationService.saveToDatabase();
    }
}

If an additional functionality to save the information as JSON is required then you will have to add a new function saveToJson() in the Service class as well as make changes in the Controller. This adds lots of complication to maintenance of our huge application with hundreds of controllers and services.

When using interface this becomes much simpler. We define our UserRegistrationService like this:

public interface UserRegistrationService {

    public void save();
}

The controller layer is only aware of this interface, which has a save method.

Let us say we have two implementations like the following:

public class UserRegistraionServiceXmlImpl implements UserRegistrationService {

    @Override
    public void save(UserInfo userInfo) {
        //save to xml using service exposed by Repository layer
    }
}

public class UserRegistraionServiceRelDbImpl implements UserRegistrationService {

    @Override
    public void save(UserInfo userInfo) {
        //save to relational db using service exposed by Repository layer
    }
}

Here we can choose any of these two implementation on run time using dependency injection. One may use @Inject or @Resource annotation to mark an implementation is to be injected. If using Spring, one may also use Xml bean definitions.

//Controller becomes much simpler when using Interfaces in the service layer
public class UserRegistrationController {

    @Resource(name = "userRegistrationServiceXmlImpl")
    UserRegistrationService userRegistrationService;

    public void processRequest(UserInfo userInfo) {
        userRegistrationService.save(userInfo);
    }

    public void setUserRegistrationService(UserRegistrationService userRegistrationService) {
        this.userRegistrationService = userRegistrationService;
    }
}

Now when we need to add the additional functionality of saving to Json, we just add another implementation and select that implementation to be injected. (You may use an IOC{Inversion Of Control} container like Spring to achieve this seamlessly.)

public class UserRegistraionServiceJsonImpl implements UserRegistrationService {

    @Override
    public void save(UserInfo userInfo) {
        //save to json using service exposed by Repository layer
    }
}

This highly reduces the software modification and extension cost. As changes in one layer does not effect other layer and new functionalities are made available to other layers immediately.

Thus using interface gives you more power over extending and maintaining your application, utilise abstraction and implement good software development practices.

Related Posts Plugin for WordPress, Blogger...