Wednesday, August 18, 2010

java.net.BindException: Address already in use: JVM_Bind:8080

This occurs when 8080 port is already used by other application. Check the server.xml in tomcat and change the port as shown below.



this should solve the java.net.BindException: Address already in use: JVM_Bind :80

happy deployment :)

Get table count in MySQL

I was looking for this and got idea from Roland Bouman forum http://forums.mysql.com/read.php?100,48568,48737#msg-48737. Thanks Naveen for (the second query) letting me know this.
1)
select count(*) as number_of_tables from information_schema.tables
where table_schema = 'my_database_schema' and table_type = 'BASE TABLE'
2)
select TABLE_SCHEMA, TABLE_TYPE, ENGINE, count(1)
FROM information_schema.tables GROUP BY TABLE_SCHEMA, TABLE_TYPE, ENGINE;

Wednesday, March 24, 2010

HTML5 Application Framework

SproutCore is an HTML5 application framework for building responsive, desktop-caliber apps in any modern web browser, without plugins.

yea dil mange more >>


yea dil mange demo>>



Thursday, March 18, 2010

ResourceBundle Message Implementation in Spring

Add below in context.xml

beans:bean id="msource" class="org.springframework.context.support.ResourceBundleMessageSource"
beans:property name="basename" value="classpath:mymessages.properties"


-----------------------------------

mymessages.properties
my.user.already.exist={0} already exist!
my.update={0} updated successfully!
my.delete={0} deleted successfully!


---------------------------------------------
Last step just do an autowire in the controller class

@Autowired
@Qualifier("msource")
private MessageSource mymess;

and in the functions use it like below
mymess.getMessage("my.user.already.exist", new Object[] { "Username chandra"}, null)

the Object[] can take multiple params based on the message u want to display
ex:Username {0} cannot be deleted because {1}

--- :)

Saturday, March 13, 2010

How to use base64 to add a basic authentication to an HTTP request.

Use the "Authorization", "basic "+encodedpassword like below.
import org.apache.commons.codec.binary.Base64;

String userpasswd = username+":"+password;
String encodedString = new String(Base64.encodeBase64(userpasswd.getBytes()));
....
and in ur httpconnection object add the below
conn.setRequestProperty("Authorization","Basic "+encodedString);

...

URL url = new URL("https://fyi.com");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Authorization"....


if (conn instanceof HttpsURLConnection)
((HttpsURLConnection) conn).setHostnameVerifier(DNV);
conn.connect();

how to use "Content-Disposition" for file download via http(s)/ftp server

Content-Disposition Header Field
This is an optional field. Never thought this could save my ass.
It has a wonderful param "filename" thru which we can out the content of the file to be downloaded. If you don't use it, the file will download with the servlet name.
Ex: /fyi/myservlet.do
While downloading the file, the dialog prompts to save file with myservlet.do which is really odd & when ur downloading a zip file the name says "save file myservlet.do"

If you dont understand any (:-) thing above see the below code.

response.setHeader("Content-Disposition", "attachment; filename="+ filename);

URL url = new URL("https://fyi/downloadfile/filename.zip");
conn = (HttpsURLConnection) url.openConnection();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = conn.getInputStream();
response.setContentType(conn.getContentType());
response.setContentLength(conn.getContentLength());
response.setHeader("Content-Disposition", "attachment; filename="
+ filename);
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int size = 0;
while ((size = in.read(buf)) >= 0) {
out.write(buf, 0, size);
}
in.close();
out.close();
}

try urself.

to know more about content-disp..

Wednesday, February 17, 2010

Spring - Finding the last user name in controller

HttpSession ss = request.getSession();
ss.getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY)

AuthenticationProcessingFilter is depricated use UsernamePasswordAuthenticationFilter instead

Click here for more details

This will be useful, when u want to redirect to different page from your Authentication Providers using form-login tag in http security.

form-login login-page="/login.do" default-target-url="/something.do" authentication-failure-url="/loginfailure.do"

http://rubyconfindia.org

I'm supporting RubyConf India 2010

Wednesday, February 10, 2010

HashMap Sorting

public LinkedHashMap sortHashMap(HashMap uMap) {
List mKey = new ArrayList(uMap.keySet());
List mValues = new ArrayList(uMap.values());
Collections.sort(mValues);
Collections.sort(mKey);

LinkedHashMap sortedMap =
new LinkedHashMap();

Iterator valueIt = mValues.iterator();
while (valueIt.hasNext()) {
Object val = valueIt.next();
Iterator keyIt = mKey.iterator();

while (keyIt.hasNext()) {
Object key = keyIt.next();
String comp1 = uMap.get(key).toString();
String comp2 = val.toString();

if (comp1.equals(comp2)){
uMap.remove(key);
mKey.remove(key);
sortedMap.put((String)key, (String)val);
break;
}
}
}
return sortedMap;
}

Original Post Click here

Tuesday, February 09, 2010

JAVA PreparedStatement with IN clause

JAVA PreparedStatement with IN clause

//two private methods.
private String phbuilder(int length) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < length;) {
b.append("?");
if (++i < length) b.append(",");
}
return b.toString();
}

private void setValues(PreparedStatement ps, Object... values) throws SQLException {
for (int i = 0; i < values.length; i++) {
ps.setObject(i + 1, values[i]);
}
}


Usage

String sql = String.format("SELECT * FROM others_pocket WHERE id IN (%s)", phbuilder(ids.size()));
....
statement = connection.prepareStatement(sql);
setValues(statement, ids.toArray());
resultSet = statement.executeQuery();


For other alternatives pls take a look here

Friday, February 05, 2010

JSP Expression Language (c:if>...)

Implicit Objects

The JSP expression language defines a set of implicit objects:

* pageContext: The context for the JSP page. Provides access to various objects including:
o servletContext: The context for the JSP page's servlet and any web components contained in the same application. See Accessing the Web Context.
o session: The session object for the client. See Maintaining Client State.
o request: The request triggering the execution of the JSP page. See Getting Information from Requests.
o response: The response returned by the JSP page. See Constructing Responses.

In addition, several implicit objects are available that allow easy access to the following objects:

* param: Maps a request parameter name to a single value
* paramValues: Maps a request parameter name to an array of values
* header: Maps a request header name to a single value
* headerValues: Maps a request header name to an array of values
* cookie: Maps a cookie name to a single cookie
* initParam: Maps a context initialization parameter name to a single value

Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.

* pageScope: Maps page-scoped variable names to their values
* requestScope: Maps request-scoped variable names to their values
* sessionScope: Maps session-scoped variable names to their values
* applicationScope: Maps application-scoped variable names to their values

When an expression references one of these objects by name, the appropriate object is returned instead of the corresponding attribute. For example, ${pageContext} returns the PageContext object, even if there is an existing pageContext attribute containing some other value.
Literals

The JSP expression language defines the following literals:

* Boolean: true and false
* Integer: as in Java
* Floating point: as in Java
* String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
* Null: null

Operators

In addition to the . and [] operators discussed in Variables, the JSP expression language provides the following operators:

* Arithmetic: +, - (binary), *, / and div, % and mod, - (unary)
* Logical: and, &&, or, ||, not, !
* Relational: ==, eq, !=, ne, <, lt, >, gt, <=, ge, >=, le. Comparisons can be made against other values, or against boolean, string, integer, or floating point literals.
* Empty: The empty operator is a prefix operation that can be used to determine whether a value is null or empty.
* Conditional: A ? B : C. Evaluate B or C, depending on the result of the evaluation of A.

The precedence of operators highest to lowest, left to right is as follows:

* [] .
* () - Used to change the precedence of operators.
* - (unary) not ! empty
* * / div % mod
* + - (binary)
* < > <= >= lt gt le ge
* == != eq ne
* && and
* || or
* ? :

Reserved Words

The following words are reserved for the JSP expression language and should not be used as identifiers.

and eq gt true instanceof
or ne le false empty
not lt ge null div mod

Note that many of these words are not in the language now, but they may be in the future, so you should avoid using them.
Examples

Table 12-2 contains example EL expressions and the result of evaluating them.
Table 12-2 Example Expressions
EL Expression

Result
${1 > (4/2)}

false
${4.0 >= 3}

true
${100.0 == 100}

true
${(10*10) ne 100}

false
${'a' < 'b'}

true
${'hip' gt 'hit'}

false
${4 > 3}

true
${1.2E4 + 1.4}

12001.4
${3 div 4}

0.75
${10 mod 4}

2
${empty param.Add}

True if the request parameter named Add is null or an empty string
${pageContext.request.contextPath}

The context path
${sessionScope.cart.numberOfItems}

The value of the numberOfItems property of the session-scoped attribute named cart
${param['mycom.productId']}

The value of the request parameter named mycom.productId
${header["host"]}

The host
${departments[deptName]}

The value of the entry named deptName in the departments map
${requestScope['javax.servlet.
forward.servlet_path']}

The value of the request-scoped attribute named javax.servlet.
forward.servlet_path

Functions

HttpServletRequest Objects

Many time encountered with trying to get servlet context, url, path , port number.
This is for reference.

Window Url:
http://localhost:8080/mycomp/myservlet?something=nothing

- request.getRequestURL().toString()
http://localhost:8080/mycomp/myservlet?something=nothing

- request.getContextPath().toString();
/mycomp

---------url.split(cntxt)[0]---------http://localhost:8080

----request.getProtocol()---------HTTP/1.1

----request.getServletPath()---------/myservlet

----request.getRemoteHost()--------0:0:0:0:0:0:0:1

---------url.split(cntxt)[0]---------http://localhost:8080

Spring Security ACL - Very basic tutorial Introduction

Spring Security ACL - very basic tutorial
Introduction

http://grzegorzborkowski.blogspot.com/2008/10/spring-security-acl-very-basic-tutorial.html

Monday, November 23, 2009

How To Get OpenVPN to Work Under Vista

Ha....
It took me a good amount of time to find out which version of OpenVPN is supported by Windows Vista. Went thru all forums and blogs but no use. My laptop was throwing me challenge each day. Atlast OpenVPN release candidate 22 from version 2.1 on 2009.11.20 fixed my issue.

http://openvpn.net/release/openvpn-2.1_rc22-install.exe

support.real-time.com

Tuesday, July 07, 2009

Skype problem with audio playback

I installed Ubuntu 8.10 & 9.04 version. When ever I make a skype call, I get "problem with audio playback". This problem sucks. I was fetching for same issue in different forums and each one has given different ways to solve it.

Dont be panic. Simple solution is , goto >> skype >> options >> sound devices

Select proper device for "Sound In", "Sound Out" and "Ringing"
Each & every time select and try "make a test sound" or "Make test call".

And keep the checkbox "Allow skype to automatically...." checked.

This should work 100%.

Thursday, June 19, 2008

Cross Site Scripting (XSS)

For now here’s what you need to do. When you see something like this:
<%= @asset.description %>
Make sure you that you consider it a potential for XSS code execution
and simply fix it like so:
<%= h(@asset.description) %>

Tainting or (http://code.google.com/p/xss-shield)
XSS Shield protects your views against cross-site scripting attacks without error-prone manual escaping with h().

Instead of:

<%= h(item.name) %>


<%= link_to "#{h(item.first_name)}'s stuff", :action => :view, :id => item %>



You will be able to write:

<%= item.name %>


<%= link_to "#{item.first_name}'s stuff", :action => :view, :id => item %>



and all your views will be automatically protected. Protection works by tagging strings you trust - which are only those escaped by h(), generated by trusted helpers (like link_to, text_area, will_paginate etc.), or explicitly marked as trusted by you. If untrusted string is to be displayed in a template it is h-escaped first.

XSS Shield supports RHTML and HAML.

To install the plugin run:

./script/plugin install -x http://xss-shield.googlecode.com/svn/trunk/xss-shield/


Referred from google and peepcode

Sunday, May 18, 2008

Print Page functionality

Generate HTML code that includes two stylesheets. One for screen and another one for Print.
or say like below

style .............. /style
style media="print" ........ /style

body{
font-family:serif
}
.new-next, .new-print-btn{
display:none;
}
a:after { content:' [' attr(href) '] '}

The first style is for "Screen" (by default if do not specify one..)

Things to be noted in "Print"

Fonts should be serif (not sans-serif) for printing
Hide images as much as possible
Hide ads
Hide navigational elements
Use a black-on-white colour scheme
Underline links if any
Add the actual URL to your links (see below)
To add the actual URL in the href-part of your link to the name of your link add the following to you print stylesheet:

[css]a:after { content:’ [' attr(href) '] ‘}[/css]

Final thing add "javascript:print()" to the button

input type="button" value="Print" onclick = "javascript:print()"

[Ref: http://ariejan.net/2007/01/19/print-this-page-with-ruby-on-rails/ ]

Thursday, March 27, 2008

Removing Stale Rails Sessions

By default rails does not clear out stale sessions from the session store. To implement this feature I added the following small snippet of code;

class SessionCleaner
def self.remove_stale_sessions
CGI::Session::ActiveRecordStore::Session.
"destroy_all( ['updated_on end
end
And then invoke the remove_stale_sessions method every 10 minutes via;

Reference: http://www.realityforge.org/articles/2006/03/01/removing-stale-rails-sessions

Monday, April 09, 2007

Ruby and Rails blog links

Ruby and Rails blog links

http://www.wayne-robinson.com/ - nice blogs from this guy
http://www.railsenvy.com/2007/2/19/acts-as-ferret-tutorial- About full text indexing
http://del.icio.us/subramani.athikunte - subu

Multiple Values from Scriptaculous' Autocomplete

Multiple Values from Scriptaculous' Autocomplete
in ruby


refered from
http://www.wayne-robinson.com/display/ShowJournal?moduleId=549828&categoryId=40943

This example will auto-populate a state and postcode based on the user's selected suburb

The first step is to create a view for the page containing the autocomplete field and for the autocomplete field itself.

Controller:

def new
# This is the main controller that will
# contain the autocomplete field
@contact = Contact.new
end

def auto_complete_for_suburb
suburb = params[:suburb]
@surburbs = Suburb.find_by_name(suburb,
:order => "name", :limit => 20)
render :partial => "auto_complete_suburb"
end

View for the new action (assume an application.rhtml template has been created, this template must include the Prototype and Script.aculo.us javascript libraries):

<%= form_tag({:action => :create}, {:method => :post}) %>

















Name: <%= text_field(:contact, :name) %>
Suburb: <%= text_field_with_autcomplete(:contact, :suburb,
:select => "value",
:after_update_element =>
"function (ele, value) {
$("contact_state").value =
Ajax.Autocompleter.extract_value(value,
'STATE');
$("contact_postcode").value =
Ajax.Autocompleter.extract_value(value,
'POSTCODE'); }
") %>
State: <%= text_field(:contact, :state, :size => 10) %>
Postcode: <%= text_field(:contact, :postcode,
:size => 10) %>

<%= end_form_tag %>

Before we continue any further, it is worth-while defining the _auto_complete_suburb.rhtml partial.


    <% unless @suburbs.nil? -%>
    <% @suburbs.each do | suburb | -%>

  • <%= h("#{suburb[:name]}, #{suburb[:state]}" +
    "#{suburb[:postcode]}") %>




  • <% end -%>
    <% end -%>

The autocompleter view has three (3) hidden

tags which contain the extra data used by the base Autocompleter Javascript methods as well as the new one (extract_value) that will be defined below.

You may also want to cast your eye over the suburb field definition in the new contact view as this is where most of the action is. There are two options to note:

  • the :value option which specifies the class name of the element which contains the value to place in attribute (the default would be whatever is within the rendered
  • field which, as we will find out below, will contain more than just the selected suburb)
  • the :after_update_element option which specifies a piece of Javascript to execute when the item is selected. You will see that this Javascript executes the Ajax.Autocompleter.extract_value function twice. This function does not exist in Script.aculo.us but is provides an easy way to extract extra values from an autocomplete list.

The Script.aculo.us Autocompleter methods conviently pass the complete contents of the

  • field to the method specified in the :after_update_element option. This allows us to extract any additional values from this data. I have created a simple addition to the Ajax.Autocompleter class below that speeds this extraction:

    Additional method for Ajax.Autocompleter class. This can be declared anywhere after the inital Script.aculo.us script inclusion. For my purposes I put this at the top of my application.js file.

    Ajax.Autocompleter.extract_value =
    function (value, className) {
    var result;

    var elements =
    document.getElementsByClassName(className, value);
    if (elements && elements.length == 1) {
    result = elements[0].innerHTML.unescapeHTML();
    }

    return result;
    };