Pages

Friday, July 16, 2010

Google Map in Rails

To have google map in an application.First we have to get a key from this link
http://code.google.com/apis/maps/signup.html
Signing up a key for http://yourdomain.com is usually the best practice, as it will work for all sub domains and directories.

Steps to include Google Map in an application

1. Generate an application geomap with latitude:decimal ,longitude:decimal,location
name:string and place description:string using scaffold.

2. We have to show this data in the map.Map we will get from the google server.

3. Download the file at http://tinyurl.com/hfrailsmap .Its a partial file save it as _map.html.erb and place in the app/views/geomaps/ like app/views/geomaps/_map.html.erb

4. We have the update the google_key in the _map.html.erb file with the key we got from google api link.

5. Copy the generated code from the show.html.erb & paste in new file called
show_map.html.erb.place it in app/view/geomaps/show_map.html.erb

6. In the app\controllers\geomaps_controller.rb place the following code

def show_map
@geomap=Geomap.find(params[:id])
end


7. Include the following code in the route.rb located in config folder.
map.connect 'geomaps/map/:id',:action=>'show_map',:controller=>'geomaps'


8. Place a test.xml data file in the public folder.This to check the map with static data.
 <data>
  <description>Vision Tech Solutions Description: Vision Tech Solutions is a Software Product and Outsourced Software Product Development firm, dedicated to provide custom made software services to customer's need of any size within global reach.</description>
  <latitude>10.784745 </latitude>
  <longitude>78.689575 </longitude>
  <title>Vision Tech Solutions</title>
 </data>


9. We have to now include the _map.html.erb partial code in the display page show_map.html.erb
<%=render(:partial=>'map',:local=>{:data=>'test.xml'}) %>

We need to pass a local variable called data containing the path to
the map data /test.xml

10. Check the display of map in http://yourdomain:3000/geomaps/map/1

Thursday, July 15, 2010

Ruby On Rails for Beginners

Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern.
Rails is a collection ruby script. It’s better to have basic idea of ruby language before entering into Rails.
Rails has the following things

1. An Application framework /Action Pack that will help us to
generate data-driven, interactive pages.
2. Rails comes with one build in WebServer -We can run the web
application
3. Database-Rails creates application that are configured to
work with an integrated SQLite3 database
4. Active Record-Rails provides for object-relational mapping
library. This makes the database like a collection of Ruby objects.
5. Rails also provide the collection of tool scripts that helps
to manage the application.

Principle in Rails: Don’t Repeat Yourself
[If we tell Rails something once,its not required to say it again]

Install Ruby on Rails or RoR version2.1 & SQLite3 for database
http://www.rubyonrails.org/down

Getting started with Application

I - Steps to create a new application in Rails
1. At a Command Prompt –type >rails Application name
  Ex: C:\ >rails MyApp

A New Folder names MyApp will be created with basic structure of the
application.
The basic Structure has the following folders &files
App,Config,Db,Doc,Lib,Log,Public,Script, test, tmp, vendor ,Rake files & readme
file

2.In that command prompt change into MyApp folder C:\MyApp>.
Type ruby script/server –To run the web server.

  Ex: C:\MyApp>ruby script/server

3.Check this link http://localhost:3000/ to
confirm whether the webserver running Rails starts its webserver on port 3000 by default.

II -Start developing the Application

CRUD operation
CRUD operation/ Scaffolding –Basic operation of an application
Create,Read,Update & Delete.
Type scaffold command _Will generate the code for doing CRUD
operation in a database and also in the presentation layer .

 Ex: C:\MyApp\>ruby script/generate scaffold employee employee_name:string
address:text

Creates employee.rb file in models & create_employees.rb
file in Db -migrate

[Note: We have to give the db name in singular form like
Employee,Shop..etc., and the table name will be in plural like
employees,Shops..etc.,]

To create the Tables in the database

We have to run the migration script using another rails tool called Rake.This
migration ruby script is generated by the scaffolding.

Type rake db:migrate at the command prompt –Which runs the
migration code& creates the table.[Db files are location the db folder]

  Ex:C:\MyApp\>rake db:migrate

 Run the employees.rb file in Db –migrate & create the table.

Go for link http://localhost:3000/employees In a couple of minutes we
can enter few records & perform the CRUD operations.


In app folder we will have Model, Controller & View folders .

To changes the display of the page

We can make the changes in the labels by changing the four .html.erb files in
the views folder.

To append a column after creating the Table.
Rails understand the migration Add..To..=>Add particular column
to a particular table.
Ex:If we want to include Phone Number column in employees table.

  C:\MyApp\>ruby script/generate migration
AddPhoneToEmployees phone:string
Rails write the migration code.

After this command we have to give Rake db:migrate to make the
reflection of new column in the table.
Go for link http://localhost:3000/employees to conifrm the addition of
one more column in the table.
We can check the changes whenever we update the code.No need for publish & deploy
operations.

Without Scaffolding
We are in some time need of writing the code by our self for some application.Instead of having the same basic CRUD functions.We might be in need of genearating our own models & controllers

Command to create own model
 ruby script/generate model table name in singular form column name:type

>  rake db:migrate

This command will create magic columns
 Id – Generated Primary Key.
 Created_at and updated_at – record when data is entered or updated

Command to create own controller
ruby script/generate controller
A Controller file will be created in the controller folder.

III- Routes
Route tells Tails where the web pages are located.
Routes are defined in a ruby program in config/routes.rb

By default this two line swill be the routes.rb

  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'

We can specify our own routes.
 Ex:map.connect '/employees/:id',:controller=>'employees',:action=>'show'

The controller by using the finder method in the model sends the employees to the view

employees_controller.rb file

 Class employeesController < ApplicationController
  Def show
    @employee=Employee.find(params[:id])
   end
 end


Rails Layout
Super-template exists in Rails is called Layout. one Single
template that will control how a group of other templates will look.
We have to place the html.erb file in the app/views/layouts.

To Add the style-sheet in the
Style sheet, images & javascripts will resides in the public folder.Which has all the static files.
Include the following code in the head tag of the html template.
   <%=stylesheet_link_tag 'style sheet name(css)'>


Redirect
A redirect tells the browser to go to a different URL for output.
  redirect_to "/---/# {---}"
# -symbol and {} inserts the value of the variable into a string.
Ex: While creating a new sample .We have to redirect to the currently
created sample.

 def create
  @sample = Sample.new(params[:sample])
  @sample.save
  redirect_to "/samples/#{@sample.id}"
 end


Restricting access to a function
Rails will use special kind of web security called HTTP Authenticating .This type of security will pops up a dialog box and asks for a username and password when someone tries to enter a secure area of a website.
In the controller we have to specify the following code to make the filtration before doing security applied functions.

before_filter :function name to be called before executing particular function,;only=>[:security applied operation name]

function name to be called before particular operations

 def functionname
  authenticate_or_request_with_http_basic("The name of the secured area of the website-domain") do |username,password|
    username == "username "&& password =="password"
   end
 end

Ex:

 class SampleController <ApplicationController before_filter   check_logged_in,:only=>[:edit]
  def check_logged_in
    authenticate_or_request_with_http_basic("Samples") do |username,password|
   username == 'admin' && password =="XY2HYS8"
  end
  end
 end

Thursday, July 8, 2010

Execute RUBY program on Command Prompt

Ruby is an object-oriented interpreted scripting language.

Download Ruby -One-Click Installer (old) - ruby186-27_rc2.exe

Know about Ruby by having a look at the below links
http://www.ruby-lang.org/en/about/
http://www.techotopia.com/index.php/What_is_Ruby%3F

Simple steps for executing a tiny ruby program in command prompt.

1. Write a simple program & save the file as “welcome.rb
Code: puts "Welcome ==> RUBY !"

2. Set Ruby on Path as follows :
C:\ruby\prg>set path=%path%;c:\ruby\bin

3.To excute the program give the filename with .rb extension suffix to the word ruby
C:\ruby\prg>ruby welcome.rb

4.Add .rb to the PATHEXT environment variable as follows:
C:\ruby\prg>set PATHEXT=.rb;%PATHEXT%

5.Once the above settings are configured simply run the program by typing the filename at the command prompt (the .rb filename extension is not required):
C:\ruby\prg> welcome

Command Prompt code

Wednesday, July 7, 2010

PostGres Vs MySQL Database

 

PROPERTY

POSTGRES

MYSQL

License

BSD

GPL or Commercial

OS Support

Windows, Unix, Linux,       Mac OS.

Windows, Unix, Linux,       Mac OS, Symbiyan.

Fundamental Futures

ACID, Referential Integrity, Transactions, Unicode, Interface – GUI & SQL

ACID, Referential Integrity, Transactions, Unicode, Interface – GUI & SQL

Max DB Size

Unlimited

Unlimited

Max Table Size

32 TB

256 TB

Max Row Size

1.6 TB

64 KB

Max Columns per row

250 – 1600 Depending on type

4096

Max BLOB Size

2 GB

4 GB

Max Char Size

1 GB

64 KB

Max Number Size

Unlimited

64 bits

Min Date Value

-4713

1000

Max Date Value

5874897

9999

Max Column Name

63

64

Database Capability

Union, Inner join, Intersect, Except, Inner join, Outer join, Inner Selects, Merge join, Windowing Functions, Common Table Expressions.

Union, Inner join, Outer join, Inner Selects, Merge Joins.

Objects

Data Domain, Cursor, Trigger, Function, Procedure, External Routine.

Cursor, Trigger, Function, Procedure, External Routine.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Facebook API

FaceBook API lets you create and manage your own ads on Facebook programmatically

DownLoad Facebook jar
To work in JAVA Download - facebook-java-api-3.0.2-bin.zip

Inlcuded the jar in the class path and try to access the class in the jar

IDE
Eclipse - Version: 3.4.0


Get the API key & Application Secret

To start your work with Facebook API, You need to get the
API key & Application Key.

You need to get register your applications in this page http://www.facebook.com/developers/apps.php using Facebook account.

Necessary fields to be entered as follows
In Basic - Include the developers name .Who will be involving in developing the application.
In Canvas –Give the callback url of your application


We can start coding the application now.

Create the Twitter object & get the request token by passing the application Consumer key & secret.

To get the user client

FacebookJsonRestClient class is used for getting user client returns the object in JSON format.

FacebookJsonRestClient userClient =getUserClientsession);
public static FacebookJsonRestClient.getUserClient(HttpSession session) {
return (FacebookJsonRestClient)session.getAttribute(FACEBOOK_USER_CLIENT);
}


User session doesn't have a Facebook API client setup yet.

Pass the API key & Application secret to get the valid userclient
And store it in a session.

userClient = new FacebookJsonRestClient(api_key, secret);
session.setAttribute(FACEBOOK_USER_CLIENT, userClient);


Pass the Facebook url with your api key & required permission redirect the call.

You can check the permission available in Facebook .

facebook = new FacebookWebappHelper(req, res, api_key, secret);
nextPage = req.getRequestURI();
nextPage = nextPage.substring(nextPage.indexOf("/", 1) + 1);
//cut out the first /, the context path and the 2nd /
System.out.println(nextPage);
boolean redirectOccurred = facebook.requireLogin(nextPage);
if(redirectOccurred){
res.sendRedirect("http://www.facebook.com/login.php?api_key=dbfc65d0e72f5c103gg0gfgd8c5&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access,sms,email,user_location");
return;
}

After execution of the above code.It request you enter the Facebook username & password.

Get the auth_token

String authToken=request.getParameter("auth_token");

By passing this authToken to the client you can start working on the functionalities like getting friends ,knowing user details etc.,

You can check the functionalities available in the FacebookJsonRestClient in this link
http://developers.facebook.com/docs/reference/rest/

Functions
To know the current user id

Long facebookUserID = userClient.users_getLoggedInUser();

To get friends Id’s

JSONArray arrayObj = (JSONArray)userClient.friends_get();

Get the id’s from Array & store it in a list

List userIds = new ArrayList();
for(int i=0;i try {
userIds.add((arrayObj.getString(i));
} catch (JSONException e) {
e.printStackTrace();
}
}

Set the necessary fields in the ProfileField,that you need from a
User.



EnumSet fields = EnumSet.of ( com.google.code.facebookapi.ProfileField.NAME, com.google.code.facebookapi.ProfileField.PIC, com.google.code.facebookapi.ProfileField.CURRENT_LOCATION, com.google.code.facebookapi.ProfileField.FIRST_NAME, com.google.code.facebookapi.ProfileField.LAST_NAME);

To get the user details
  	                                            

JSONArray userArray = null;
try {
userArray = client.users_getInfo(userIds, fields);
} catch (FacebookException e1) {
e1.printStackTrace();
}
for(int i=0;i< userArray.length();i++){
try {
for (int j = 0; j < userArray.length(); j++) {
JSONObject obj = userArray.getJSONObject(j);
System.out.println("User Id"+obj.getString("uid"));
System.out.println("Pic url "+obj.getString("pic"));
System.out.println("Name"+obj.getString("first_name")
+" "+obj.getString "last_name"));
}
} catch (JSONException e) {
e.printStackTrace();}
}


To update the status of the current user
Check whether the user having the permissions & than try the functions

if (userClient.users_hasAppPermission(Permission.STATUS_UPDATE)){
userClient.users_setStatus("Status-Developing Facebook apps in Java!", false);
}

To Publish the stream for the current user

if(userClient.users_hasAppPermission(Permission.PUBLISH_STREAM)){
userClient.stream_publish("Stream-Publish-Wall written using Facebook API !", null, null, null, null);
}


To post the link to single /Group of user

userClient.links_post(Long.parseLong("Give the UserID"), "www.kyyba.com", "IT Recruitment");

Sunday, July 4, 2010

Twitter API

Twitter4J is a Java library for the Twitter API.
With Twitter4J, We can easily integrate our Java application with the Twitter service.

Step-up Twitter4j API

Get the Consumer key \ API key & Consumer Secret \Secret Key.

To start your work with Twitter4j API, You need to get the
Consumer key \ API key & Consumer Secret \Secret Key.

You need to get register your applications in this page http://twitter.com/apps
using Twitter account.

Download Twitter4j jar
Download - twitter4j-core-2.1.3-SNAPSHOT.jar
Inlcuded the jar in the class path and try to access the class in the jar

We can start coding the application now.
Create the Twitter object & get the request token by passing the application Consumer key & secret.

Code

Twitter twitter = new Twitter();
twitter.setOAuthConsumer("consumer key",”consumer secret” );
RequestToken requestToken = twitter.getOAuthRequestToken();


Get the Access Token & Secret

By using the request token you need to get the access token & token secret.
Code

String token = requestToken.getToken();
String tokenSecret = requestToken.getTokenSecret();


Authorized URL for accessing the Application
Store the requestToken & Authorized URl in a session.

String authUrl = requestToken.getAuthorizationURL();
session.setAttribute("authUrl", authUrl);
session.setAttribute("requestToken", requestToken);


Example Authorized Application URL

https://twitter.com/oauth/authorize?auth_token=LJyavdddrrrreddddy3sfpm8bTHg3H3Bddddm4

Once you click the authorized link it will ask for you twitter username & password.Once user details verfied it redirect to your application.


Functions in Twitter4j

Tweet Message

This function is to tweet a text message in his/her twitter.

Status status = twitter.updateStatus(“Tweet Message .”);


Delete the Tweeted message

We can delete the tweeted message by passing the TweetId

destroyTweet(twitter,tweetId);

User details
This function is used to get the user details.We need to pass the user’s id .

User user = twitter.showUser(twitter.getId());

From the user object we can get the details of the user profile,description …

user.getProfileImageURL();
user.getScreenName();
user.getName();
user.getDescription();
user.getURL();
user.getLocation();
user.getProfileBackgroundColor();
user.getProfileBackgroundImageUrl();


Search Tweet
We can search for tweets by using this method

String searchTweet ="TieCon MidWest"
Query query = new Query("searchTweet");
QueryResult result = twitter.search(query);
System.out.println("hits:" + result.getTotal());
for (Tweet tweet : result.getTweets()) {
System.out.println(tweet.getFromUser() + ":" + tweet.getText());
}

To get the friends tweets & details

/* All the Tweets in the first page will be displayed*/


List statuses = twitter.getFriendsTimeline();
for (Status status : statuses) {
System.out.println(status.getUser().getName() + ":" +
status.getText());
}


/** Four tweets in the first page will be displayed*/

Paging paging = new Paging(1, 4);
List statuses = twitter.getFriendsTimeline(paging);


Sending / Receiving Direct Messages

Twitter sender= new TwitterFactory().getInstance(senderID,senderPassword);
sender.sendDirectMessage(recipientId,message);
Twitter receiver = new TwitterFactory().getInstance(recipientId,recipientPassword);
List messages = receiver.getDirectMessages();
for (DirectMessage message : messages) {
System.out.println("Sender:" + message.getSenderScreenName());
System.out.println("Text:" + message.getText());
}



Method's avaialabe in the Twitter API

http://apiwiki.twitter.com/Twitter-API-Documentation