Localization(I10N) and Internationalization(I18N) in JavaScript

In recent days I’ve been looking for a plug-in for my JQuery Mobile Application so I can easily and quickly add localization and internationalization. There are several possibilities to do it.

One of them is Globalize,  a JavaScript library for globalization and localization. Enables complex culture-aware number and date parsing and formatting for hundreds of different languages and countries. It has also an extensible system for localization.

Default culture is “en” also English, if you add globalize.js in your project. You can add globalize.culture.de-DE.js for German to change the parsing and formatting settings.

For translation you must expand it a little. For example ;

Globalize.addCultureInfo( "de", {
    messages: {
        "label_settings": "Einstellungen",
        "error_empty_username": "Bitte ein Benutzername eingeben", 
        "error_empty_email": "Bitte ein E-Mail eingeben", 
        "error_empty_password": "Bitte ein Password eingeben"
    }
});

Globalize.addCultureInfo( "en", {
    messages: {
        "label_settings": "Settings",
        "error_empty_username": "Please enter your username", 
        "error_empty_email": "Please enter your e-mail", 
        "error_empty_password": "Please enter your password"
    }
});

 

Information can be retrieved as follows :

console.log( Globalize.localize( "label_settings", "de" ) ); // Einstellungen
console.log( Globalize.localize( "label_settings", "en" ) ); // Settings

// assuming a culture where "," is the group separator
// and "." is the decimal separator
console.log(Globalize.parseInt( "1,234.56" )); // 1234

console.log(Globalize.parseDate( "1/2/2003" )); // Thu Jan 02 2003

console.log(Globalize.format( new Date(1955,10,5), "dddd MMMM d, yyyy" )); // "Saturday November 5, 1955"

 

Apache Shiro JDBC Realm

In my previous post I wrote something about Apache Shiro. Now I want to give a small example of how you create a JDBC realm, which makes both Authentication and Authorization.

public class CustomSecurityRealm extends JdbcRealm {

	/**
	 * The default query used to retrieve account data for the user.
	 */
	protected static final String DEFAULT_AUTHENTICATION_QUERY = "SELECT pass FROM user WHERE username = ?";

	/**
	 * The default query used to retrieve the roles that apply to a user.
	 */
	protected static final String DEFAULT_USER_ROLES_QUERY = 
			// from user self
			"SELECT r.role_name FROM user_roles ur "
			+ "JOIN user u USING(user_id) "
			+ "JOIN roles r USING(role_id) "
			+ "WHERE u.username = ? = ? "
			+ "UNION "
			// from his groups
			+ "SELECT r.role_name FROM user_roles_groups urg "
			+ "JOIN user u ON(urg.user_id=u.user_id) "
			+ "JOIN roles_groups_roles rgr USING(roles_group_id) "
			+ "JOIN roles r ON(rgr.role_id = r.role_id) "
			+ "WHERE u.username = ? ";

    protected String authenticationQuery = DEFAULT_AUTHENTICATION_QUERY;

    protected String userRolesQuery = DEFAULT_USER_ROLES_QUERY;

    protected boolean permissionsLookupEnabled = false;	

    private static final Logger log = LoggerFactory.getLogger(CustomSecurityRealm.class);

	/**
	 * jndiDataSourceName
	 */
	protected String jndiDataSourceName;

	public CustomSecurityRealm() {
		super();
	}

	public String getJndiDataSourceName() {
		return jndiDataSourceName;
	}

	public void setJndiDataSourceName(String jndiDataSourceName) {
		this.jndiDataSourceName = jndiDataSourceName;
		this.dataSource = getDataSourceFromJNDI(jndiDataSourceName);
	}

	private DataSource getDataSourceFromJNDI(String jndiDataSourceName) {
		try {
			InitialContext ic = new InitialContext();
			return (DataSource) ic.lookup(jndiDataSourceName);
		} catch (NamingException e) {
			log.error("JNDI error while retrieving " + jndiDataSourceName, e);
			throw new AuthorizationException(e);
		}
	}

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        // Null username is invalid
        if (username == null) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }

        Connection conn = null;
        AuthenticationInfo info = null;
        try {
            conn = dataSource.getConnection();

            String password = getPasswordForUser(conn, username);

            if (password == null) {
                throw new UnknownAccountException("No account found for user [" + username + "]");
            }

            info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());

        } catch (SQLException e) {
            final String message = "There was a SQL error while authenticating user [" + username + "]";
            log.error(message, e);

            // Rethrow any SQL errors as an authentication exception
            throw new AuthenticationException(message, e);
        } finally {
            JdbcUtils.closeConnection(conn);
        }

        return info;
    }	

	private String getPasswordForUser(Connection conn, String username)
			throws SQLException {

		PreparedStatement ps = null;
		ResultSet rs = null;
		String password = null;
		try {
			ps = conn.prepareStatement(authenticationQuery);
			ps.setString(1, username);

			// Execute query
			rs = ps.executeQuery();

			// Loop over results - although we are only expecting one result,
			// since usernames should be unique
			boolean foundResult = false;
			while (rs.next()) {

				// Check to ensure only one row is processed
				if (foundResult) {
					throw new AuthenticationException(
							"More than one user row found for user ["
									+ username + "]. Usernames must be unique.");
				}

				password = rs.getString(1);

				foundResult = true;
			}
		} finally {
			JdbcUtils.closeResultSet(rs);
			JdbcUtils.closeStatement(ps);
		}

		return password;
	}

    protected Set getRoleNamesForUser(Connection conn, String username) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        Set roleNames = new LinkedHashSet();

        try {
            ps = conn.prepareStatement(userRolesQuery);
            ps.setString(1, username);
            ps.setString(2, username);

            // Execute query
            rs = ps.executeQuery();

            // Loop over results and add each returned role to a set
            while (rs.next()) {

                String roleName = rs.getString(1);

                // Add the role to the list of names if it isn't null
                if (roleName != null) {
                    roleNames.add(roleName);
                } else {
                    if (log.isWarnEnabled()) {
                        log.warn("Null role name found while retrieving role names for user [" + username + "]");
                    }
                }
            }
        } finally {
            JdbcUtils.closeResultSet(rs);
            JdbcUtils.closeStatement(ps);
        }

        return roleNames;
    }	

}

 

This requires some settings in shiro.ini

 

[main]
# realms to be used
customSecurityRealm=com.pinateknoloji.security.CustomSecurityRealm
customSecurityRealm.jndiDataSourceName=java:app/jdbc/mysql-ds

# specify login page
authc.loginUrl = /login.xhtml?faces-redirect=true
# redirect after successful login
# authc.successUrl  = /restricted/dashboard.xhtml?faces-redirect=true

[urls]

# enable certificateFilter filter for all application pages
/rest/** = authcBasic
/restricted/** = authc

Full Ajax-CRUD Rails Application – Customers Demo

I have changed the Customer App from Cem Ikta and written a full ajax crud web application with Ruby on Rails.

Features : base ajax CRUD functions, list, bootstap style will-paginate,  ajax search, sorting, flash messages, form validation etc.

 

Customers App has the following technology stack:

 

Full source code on GitHub

 

Customers App screenshots:

 

 

 

Bootstrap2 style will_paginate

# config/initializers/will_paginate.rb

require 'will_paginate/view_helpers/action_view'

module WillPaginate
  module ActionView
    def will_paginate(collection = nil, options = {})
      options, collection = collection, nil if collection.is_a? Hash

      collection ||= infer_collection_from_controller
      options[:renderer] ||= BootstrapLinkRenderer
      options[:class] = 'pagination pagination-centered'
      options[:previous_label] = '< rel_value(page))
        else
          link(page, "#", :class => 'active')
        end
      end

      def gap
        tag (:li, link(super, '#'), :class => 'disabled')
      end

      def previous_page
        num = @collection.current_page > 1 && @collection.current_page - 1
        previous_or_next_page(num, @options[:previous_label], @options[:previous_page_class])
      end

      def next_page
        num = @collection.current_page < @collection.total_pages && @collection.current_page + 1         previous_or_next_page(num, @options[:next_label], @options[:next_page_class])       end       def previous_or_next_page(page, text, classname)         if page           link(text, page)         else           link(text, "#", :class => 'disabled')
        end
      end

      def html_container(html)
        tag(:div, tag(:ul, html), container_attributes)
      end

      private

      def link(text, target, attributes = {})
        if target.is_a? Fixnum
          attributes[:rel] = rel_value(target)
          target = url(target)
        end

        unless target == "#"
          attributes[:href] = target
        end

        classname = attributes[:class]
        attributes.delete(:classname)
        attributes.delete(:class)
        tag(:li, tag(:a, text, attributes), :class => classname)
      end

    end
  end
end

 

For more info ;

https://github.com/yrgoldteeth/bootstrap-will_paginate/blob/master/config/initializers/will_paginate.rb

https://github.com/mislav/will_paginate/issues/158

 

Categories: Rails Tags: , ,

Glassfish Server Tools – Missing classpath entry Error

Who has created a project in Eclipse with JSF2 and has chosen as a target runtime as GlassFish, get the following error message;

Missing classpath entry …glassfishmodulesjsf-api.jar

The reason for this is that the current Oracle Glassfish Server Tools has a bug and doesn’t recognize Glassfish 3.1.2. This has been corrected and approved as jar. You just have to download and copy to “eclipse/plugin/” .  Make it work properly, you must replace the version number of plug-in with the new in following files ;

Version number to replace : 3.2.3.201106220649  –> 4.2.1.201112152311

  • eclipseartifacts.xml
  • eclipseconfigurationorg.eclipse.equinox.simpleconfiguratorbundles.info
  • eclipsefeaturesoracle.eclipse.tools.helios.glassfish_1.7.3.201106220649feature.xml

There are certainly easier way to update a plugin but what did I work on every case.

More info and Jar-File for download is here.

Categories: General Tags: ,

Ruby on Rails – MySQL configuration

In recent days I’ve started working with Rails. I have everything installed within a few minutes and created a Rails-App, exactly as in home page of Rails was written.

Exciting!

I made a small application that makes all the CRUD with Ajax. I’ll write in my next post about this.

But first I want to say about MySQL configuration in Rails. It is really as simple as it was told in home page of Rails but on Windows, I get an error message. I’ve been looking for the solution for a long time.

Here again, how to make MySQL configuration in Rails on Windows and the solution of possible errors;

  1. gem install mysql
  2. in the Gemfile add mysql ( gem ‘mysql’ )
  3. Verify your config/database.yml file (adapter, passwords)
# MySQL version 5.1
#   gem install mysql
#
development:
  adapter: mysql
  database: customer
  host: localhost
  username: root
  password: passwd
  port: 3306
  encoding: utf8

and finished. If you get the following error message, download MySQL client library (libmySQL.dll) and copy it to your Rubybin folder.

Error:

$ rake db:migrate
rake aborted!
Mysql::Error: query: not connected: SHOW TABLES

Tasks: TOP => db:migrate
(See full trace by running task with –trace)

 

Categories: Rails Tags: , , , , ,