Thursday, December 19, 2013

Unix/Linux - Shell script to find and replace a text from the list of files

Below is the automated shell script which will find a text and replace it with the given string. It will also keep a backup of existing file. It can also be used for global search and replace string from a text file. Please see the self-explanatory shell script below -

replace.sh

#!/bin/bash

#find string
searchString="text1"

#replace with
replaceWith="text2"

echo "searching "$searchString" ..."
grep -l $searchString * >foundIn.txt
chmod 777 foundIn.txt

echo "replacing "$replaceWith" ..."
count=0
while read x
do
  if [ $x != replace.sh ]
  then
          (cat  $x) >$x"_bkp"
          sed "s/${searchString}/${replaceWith}/g" $x"_bkp" >  $x
          count=$(($count+1))
          echo "Found in... "$x
  fi
done <foundIn.txt

echo $count "occurences have been replaced."

Linux/Unix - Shell script to read a text file

Method 1 - By iterating each line using while loop

#!/bin/bash

#Name of the text file
txtFile=myFile.txt

echo "Reading text file "$txtFile" ..."

while read x
do
echo $x
done <$txtFile


Method 2 - By using cat (concatenate and display files) command

#!/bin/bash

#Name of the text file
txtFile=myFile.txt

echo "Reading text file "$txtFile" ..."

cat $txtFile

Wednesday, December 18, 2013

keytool error: java.io.FileNotFoundException: cacerts (Permission denied)

I got the error when trying to install a certificate into my keystore

Command -
keytool -import -alias aliasName -file fileName.cer -keystore cacerts
keytool -list -keystore cacerts

Solutions

Windows -
This could happen if you are not running the command prompt in administrator mode. Login with the user who has administrator privilege.

For Windows 7 and above - Go to run, type cmd and hit Ctrl+Shift+enter. This will open the command prompt in administrator mode.

For others windows -  Go to start -> all programs -> accessories -> right click command prompt and say run as administrator.

Linux -
First check the write permissions on the keystore. Also if needed login with root user and try the command.

Wednesday, November 13, 2013

How to use scp command without prompting for password

You may need to write a shell script in which you want to copy a file from one server to another. OfCouse you can easily achieve it with SCP command however when you automate the shell script using crontab it will get stuck because of password prompt. To avoid this you want SCP command to work without prompting for password.

Secure Copy (SCP) allows files to be copied to, from, or between different hosts

Let’s assume you want to copy a file from host server (HOST) to destination server (DEST).

1. On HOST server run below command

$ ssh-keygen -t rsa

First it will prompt for "Enter file in which to save the key" just keep it blank by pressing enter. Then it will prompt for passphrase, again keep it blank by pressing enter. It will generate a public key (id_rsa.pub) and a private key (id_rsa) in the folder <your_home_dir>/.ssh

Output -

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/.ssh/id_rsa.
Your public key has been saved in /home/.ssh/id_rsa.pub.
The key fingerprint is:
1a:7b:3b:d7:5c:f0:6d:f1:01:75:0f:b1:71:6a:15:be user@HOST

2. Share the public key (id_rsa.pub) with DEST server

Copy the file id_rsa.pub from HOST to <your_home_dir>/.ssh folder of DEST. You can use scp or ftp anyway you are comfortable with.

3. Copy the contents of id_rsa.pub to <your_home_dir>/.ssh/authorized_keys2 in DEST server

Below command will append the content of id_rsa.pub to authorized_keys2. Note - you may even copy to authorized_keys whichever file exits on <your_home_dir>/.ssh in DEST server

$ cat id_rsa.pub >> authorized_keys2

Now if you use SCP command to transfer a file from HOST to DEST it won’t prompt for password. I hope it helped you.

Java program to play an audio sound

These are the following ways in which you play a sound in Java.

Toolkit - If you just want a beep or quick alert you can use beep() finction of class java.awt.Toolkit. It Emits an audio beep.
AudioClip - The AudioClip interface is a simple abstraction for playing a sound clip.
Clip - The Java Sound API provides functionality for the capture, processing, and playback of sampled audio data & the sequencing and synthesis of MIDI data.
MIDI Sequences - The javax.sound.midi package provides an interfaces and classes for I/O, sequencing, and synthesis of MIDI (Musical Instrument Digital Interface) data.

Please see the sample code of each type


Wednesday, November 6, 2013

Example using Java.awt.Robot class

Java.awt.Robot class is used to take the control of mouse and keyboard. In this example we will open a notepad and type a message. Please see the self explanatory code below.

Tuesday, November 5, 2013

Top 5 Popular jQuery Plugins


Author Bio: Danica loves technology and she constantly advises people on the best web hosting platforms for using jQuery as well as a host of other coding libraries. She is an expert at using PHP and hopes to start her own development company in the future.

jQuery is one of the most popular libraries available to webmasters and developers, and a big reason for that is the large number of high quality plugins that are available. These help novice webmasters and developers to create professional looking websites filled with different features, while those with experience can use jQuery to add the finishing touches to what is already an exceptional platform.

That said, one of the worst things for a developer to do online is to overuse plugins, widgets, and various other things that are available in order to enhance the user experience of a website. With that in mind, we have looked at five of the best and most popular jQuery plugins you could use on your website.

Cycle 2

If static images are a big part of your website, then the Cycle 2 jQuery plugin is a great way to take your imagery to the next level and create exciting slideshows on your web pages. What makes this plugin a winner is that it is so easy to use; all you need to do is include the plugin and mark-up to your code, and everything else is done for you. Although this is the perfect plugin for new webmasters or bloggers, it is also loved by those with great knowledge of web development owing to its ability to work within responsive design themes.

FitVids

While many people fret about how having video content on their website will slow down loading times, some struggle to even get video onto their pages at all. Those who want to make video a feature of their site should consider using FitVids, especially if they are embedding video content that is already featured on sites like YouTube.

Even though modern HTML5 coding makes it easy to embed your own videos from your disk or device, it is still worth using a plugin like FitVids so you can be flexible with the video content on your site.

Tuesday, October 29, 2013

Java program to take screen shots of your desktop

This example is used to take screen shots of your desktop and save the file in specific format in your machine. This example uses java.awt.Robot class to capture the screen pixels and returns a BufferedImage. Java.awt.Robot class is used to take the control of mouse and keyboard, see API for more options. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code.

Please see the self explanatory java code below. This example takes screen shot of your desktop after an interval of every 5 second, you can customize it as per your requirement.

Friday, October 25, 2013

The Pros And Cons Of The ZK Framework For Java

By Adam Shrum, IT Manager and analyst at Dynamic CAFM, a Texas based facilities management software provider.

When tackling a new software development project there are many things to consider. First, what is the scope of the project? Second, what language should be used to develop the project. And Finally, what tools will be needed to complete the project efficiently. I manage a team of developers in Pearland, TX and we have had to answer all three of these questions at one time or another. Before we use any tool we always come up with a pros vs. cons analysis to evaluate the tool beforehand. One of the Java tools we use quite frequently is ZK or ZKoss, an Ajax + Mobile enterprise framework that incorporates Spring, JPA, Hibernate, JavaEE, Grails, and Scala. I like to think of ZK as a front end tool that keeps you from having to create a UI from scratch. Like any other front end tool there are pros and cons of using a framework like ZK.

The number one pro of ZK is that it’s Open Source. Because it’s an open source product there is a community of developers that support it via the ZK Forums. It’s important to also note that the documentation for ZK is very good, and there have been few times when we have even needed to go to the forums for help. Another pro is that Big Name Companies use ZK which is always a positive. Companies such as Sony, Deutsche Bank, Sun Microsystems, IBM, Toyota, and Adobe are ZK users and to me one of the biggest red flags of a software tool is that nobody is using it. With ZK you know you’re dealing with a proven product that actually works. ZK has a Rich Modular UI which is made up of many different components you can call out without having to code from scratch. They have thought of almost everything out of the box, but additional components are included with the PE and EE paid versions of the product.
Oh yeah, I forgot to mention that ZK is a Free Product when you use the community edition. Because it’s free there is no upfront cost which is another positive, and there is no cost for a user license as well. If you are working with a legacy system and have decided to utilize ZK in an update to that legacy system you will experience much more control over the system than you had before.

Saturday, October 19, 2013

Telephone Hacking

Everyone has come to know what phone hacking is after the parents of murdered schoolgirl; MillyDowler had their voicemail hacked into. But, it didn’t end there, it has subsequently been exposed that numerous celebrities have had their telephone hacked into by the British media. One more victim of the telephone hacking outrage has been the Royals. A phone hacker can be defined as somebody who listens to your voicemails without your consensus. However, to become a victim of phone hacking you don’t need to be a celeb.

Your telephone bill can upsurge by thousands of quid if you come to be the victim of telephone hacking. Impostors will hack into your phone system in a process known as phreaking. Phonehacking is least possible to be uncovered during holiday times and evenings, consequently that is when it is almost certainly to happen. You might have become a victim of telephone hacking if your phone bill has unexplainably enlarged dramatically.

Hacking into a telephone system can make the offenders a lot of money. There are websites that are dedicated to this activity; this is where the offenders are learning to do this. So you don’t need to be an internet geek to do this. However, it’s not until the damage has been done that many people realise what’s happened. Just like the anti-virus software for your computer, you need to secure your telephone.

Friday, October 18, 2013

Top Five Suggestions to Grow Twitter Followers Online

In terms of social networking, Twitter’s recent activity and progress is currently as huge as Facebook. Making a Twitter account and posting information is straightforward, since it merely requires a couple of minutes to have things going. Even so, it will necessitate a considerable amount of time for you to begin noticing results. Building an interesting following may be the most difficult part.


This can be still tricky for those already with accounts. For first timers to Twitter, this is a daunting aspect to accomplish. The buzzword “engagement” is normal to all folks, but how do you make that come about? To boost your Twitter presence online, check out Followersboosts.com and adopt these 5 suggestions.

1. Tweet and tweet regularly, but give room for responses 

Depending on how active you are or how active your Twitter profile is, anybody is quite likely to discover you on Twitter as well as become your follower. The more dynamic you are, the larger your chances of someone finding you and vice versa. The Twitter public timeline is where your tweets appear. You increase your probability of appearing there more often by increasing your number of tweets.

Nonetheless, tweeting on a regular basis and of nothing worthy sets you vulnerable to losing followers. By talking too much and about everything, you deny your followers room to respond. You ought to leave room between your topics of dialogue to permit others to communicate. You should therefore attempt to discuss one subject at a time.

Thursday, October 3, 2013

Error occurred during initialization of VM / Could not reserve enough space for object heap

If you are getting below error while running a java program, possible reason could be JVM is running in another bit mode (32 bit OR 64 bit)

Error occurred during initialization of VM
Could not reserve enough space for object heap

Solution - Check out in which bit mode your JVM is running. you can use below command to find out in which bit mode your JVM is running.

java -d32 -version OR java -d64 -version

Find the line that executes the java command and add correct bit mode. For example ' -d64 ' to the java command line. This is a flag that forces the Java virtual machine to run in 64 bit mode.

Saturday, September 21, 2013

Java program to check IP address range

This is a simple java program to check IP address range. Here we provide a IP address to check whether it lies between start and end IP address.

Please see the self explanatory java code below. Just provide the IP address and see the output.


Saturday, September 14, 2013

Is Outdated Java Lurking in Your System?

In January of 2013, Oracle announced plans to reevaluate and strengthen its security protocols. The announcement came after serious vulnerabilities were found in Java 6, coupled with widespread criticism of the company’s rigid patch release schedule.

Throughout the next six months, Oracle did, indeed, take steps to tighten their security, surprising some detractors with their commitment to the issue. Most, if not all, security improvements, however, centeron the latest version of Java, Java 7.

Unfortunately, as a recent report by security firm Bit9 makes clear, many organizations continue to use Java 6, forwhichOracle stopped providing public security updates in April of 2013. Even worse, many endpoint systems run multiple versions of Java, which allows hackers to capitalize on older vulnerabilities.

Java Usage and Version Statistics

Bit9 surveyed over 400 organizations, representing a total of over 1 million distinct endpoint systems. The survey discovered Java 6 on over 80 percent of systems. Matters got worse. The most commonly installed version of Java 6 was Java 6 Update 20, which includes a staggering 215 security issues. How far behind is this update? The last version of the software was Java 6 Update 45.

Any system using outdated versions of Java 6 is at risk of serious vulnerabilities. Whether you’re selling 1994 mustang parts or offering online cloud hosting, outdated versions of Java, or indeed any program, represents significant risk of security breaches.

Only 15 percent of endpoint systems surveyed used Java 7, and even then, were rarely up-to-date. Only 3 percent were running Java 7 Update 21, the most recent update at the time of the survey.

Javascript - Password strength meter

Password Strength Algorithm

Password Length:
5 Points: Less than 4 characters
10 Points: 5 to 7 characters
25 Points: 8 or more

Letters:
0 Points: No letters
10 Points: Letters are all lower case
20 Points: Letters are upper case and lower case

Numbers:
0 Points: No numbers
10 Points: 1 number
20 Points: 3 or more numbers

Characters:
0 Points: No characters
10 Points: 1 character
25 Points: More than 1 character

Bonus:
2 Points: Letters and numbers
3 Points: Letters, numbers, and characters
5 Points: Mixed case letters, numbers, and characters

Password Text Range:

>= 90: Very Strong
>= 70: Strong
>= 50: Good
>= 30: Weak
>=  0: Very Weak

Thursday, July 4, 2013

Access restriction: The type BASE64Decoder is not accessible due to restriction on required library C:\Program Files\Java\jdk1.6.0_25\jre\lib\rt.jar

Error :

You may get below compile error in eclipse while using BASE64Decoder or BASE64Encoder.

Access restriction: The type BASE64Decoder is not accessible due to restriction on required library C:\Program Files\Java\jdk1.6.0_25\jre\lib\rt.jar

Using sun.* package should be avoided, Please see the link.

Solution :

Still if you need to access sun.misc.BASE64Encoder, in Eclipse, right click on the project, properties -> Java compiler –> Errors/Warnings –> Enable project specific settings -> Deprecated and restricted API –> Forbidden reference (access rules), change the default "Error" to "Warning". Now, your code should be able to compile, but with some warning messages.



The above solution is not recommended, you should replace sun.misc.BASE64Encoder with other BASE64 class like org.apache.commons.codec.binary.Base64; Apache common codec

Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Exception in thread "main" java.lang.Exception: Error Initializing Context: oracle.jdbc.driver.OracleDriver
at com.hewitt.appinv.sdc.db.LocalContextFactory.createLocalContext(LocalContextFactory.java:28)
at com.hewitt.appinv.sdc.db.TestJNDI.main(TestJNDI.java:14)
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at com.hewitt.appinv.sdc.db.LocalContextFactory.createLocalContext(LocalContextFactory.java:23)
... 1 more

If you see above error, Please add classes12.jar  in your applications classpath. Download it from here. classes12.jar  

Wednesday, July 3, 2013

What You Need to Know About The Recent Java Patches

The latest round of Java patches, which were released in mid-June, call attention to some issues that all Java programmers should be concerned about. Oracle enabled online certificate revocation checking by default in the move, and it dealt with 40 security issues in Java. Of course, it’s hardly unusual for Oracle to issue a large number of patches at once, but it’s critical that programmers understand what the issues were, whether they maintain sites about British history or alcoholrecovery centers.

Who and What Was Impacted

According to Oracle, 34 of the patches in the Java 7 Update 25 (Java 7u25) affected only client developments of Java. Client and server deployments were affected by four other vulnerabilities, while one dealt with the Java installer and another with the Javadoc tool employed to make HTML documentation files.
Here’s an alarming development: The client-only vulnerabilities, which accounted for the aforementioned 34 patches, were extreme. Oracle graded them highly on its vulnerability severity scale. That’s because they might be used to trick users into loading malicious Java applets onto remote servers, a big problem indeed.


javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Error :

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1649)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:893)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1165)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1149)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at com.hewitt.appinv.sdc.URLReader.readURL(URLReader.java:18)
at com.hewitt.appinv.sdc.URLReader.main(URLReader.java:38)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
at sun.security.validator.Validator.validate(Validator.java:218)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1185)
... 13 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
... 19 more


Monday, May 20, 2013

Java - Read excel file with blank cells

If you use normal cellIterator to iterate through excel cells it will skip blank cells. If you need to read blank cells as well you can use below method -

Tuesday, April 23, 2013

The Persuasion of Discussions on Internet Marketing


There are remarkable ideas that you can come across in various internet marketing forums. In whatever kind of forum you join, it is certain that you can have contact with plenty of information that can be useful to start your business. Novice and skilled people in the business usually join in discussions on online marketing with the aim of being taught something new by trading experiences and ideas that they have previously undergone in marketing.


The subject matter of these forums are discussions about SEO, making money, affiliate programs inclusive of others, advertising, search engines and social networks, and all that. The topics in the discussions are for any members who are in the online business and those intending to involve in internet marketing and make them feel part of a important community.

Previous to being part of any internet marketing debates, it will better if you seek out a forum that will be meeting your goals. The platform you choose must be definite to the business you are in to make certain that you maximize the resources. If you are probing through the possible forums, you can also check their FAQs and policies on the online marketing forum. This will assure that you will not breach and be obedient to their group and absolutely disbarred from their site.

Tuesday, April 2, 2013

Celebrities Team Up to Promote Coding



What do Microsoft inventor Bill Gates and music star Will.i.am have in common? They are just two famous people who have teamed up to create a YouTube video that promotes the idea that coding, an activity associated with computer programming, is cool and deserves attention.

Stoking the Desire to Learn

The video is focused on the idea that although many schools don't teach coding as part of regular coursework, students could aim to learn more through extracurricular activities, thus acquiring skills that could contribute to a brighter future. Coding is versatile, because it can be written in several programming languages such as Java and C++, among many others.

Technological opportunities are expanding at a rapid rate and many community colleges offer night classes in coding that cater to busy lifestyles. This means that both a Lancaster workers compensation lawyer and a chef who lives in Chicago are equally able to learn coding after their day job is done, provided the motivation is there. However, the YouTube video focuses more on the belief that coding should be taught in schools, while students are still young. It even calls the skill a “superpower.”

Ignore the Intimidation

The video addresses the common perception that coding is overly complicated. It also points out that as long as people are determined to learn, nothing can stop them.

In the video, NBA star Chris Bosh admits that while he was growing up, people made fun of him because of his interest in technology and coding. However, he was not deterred, and he continued studying the subjects to satisfy his hunger for knowledge. This promotes the idea that if a person feels that they’re not cut out to be a coder, or is getting negative feedback from a friend, that’s not a reason to stop learning something new.

Thursday, March 21, 2013

Hibernate : To handle special characters in HQL


In this article we will see to handle special characters in HQL similar to PreparedStatement in JDBC. It can also used for additional security purpose like to avoid SQL Injection.

For example, I have a below function in my BookDAO class to get detail of a particular book. It accepts bookTitle as a parameter and returns list of books. Here assume bookTitle can contain special characters.

public List findBook(String bookTitle) {
try {
String queryString = "from BsBooks where bookTitle = :bookTitle";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter("bookTitle", bookTitle);
return queryObject.list();
} catch (RuntimeException re) {
throw re;
}
}

Note - the method setParameter(), it is used to set the value for bookTitle, which can contain special characters.

queryObject.setParameter("bookTitle", bookTitle);

The above method will give following error if you try to use it like - queryObject.setParameter(0, bookTitle);

Exception in thread "main" java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
at org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterDescriptor(ParameterMetadata.java:79)
at org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterExpectedType(ParameterMetadata.java:85)
at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:421)
at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:393)


To avoid it you can use it as a '?' placeholder. When you execute the query, you would need to supply the value for it, which would replace the '?' in the query in below function.

public List findBook(String bookTitle) {
try {
String queryString = "from BsBooks where bookTitle = ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, bookTitle);
return queryObject.list();
} catch (RuntimeException re) {
throw re;
}
}


Below are the variations of the method setParameter, to know please see the API.

setParameter(int position, Object val) - Bind a value to a JDBC-style query parameter.

setParameter(int position, Object val, Type type) - Bind a value to a JDBC-style query parameter.

setParameter(String name, Object val) - Bind a value to a named query parameter.

setParameter(String name, Object val, Type type) - Bind a value to a named query parameter.

setParameterList(String name, Collection vals)  - Bind multiple values to a named query parameter.

setParameterList(String name, Collection vals, Type type) - Bind multiple values to a named query parameter.

setParameterList(String name, Object[] vals) - Bind multiple values to a named query parameter.

setParameterList(String name, Object[] vals, Type type) - Bind multiple values to a named query parameter.

setParameters(Object[] values, Type[] types) - Bind values and types to positional parameters.

Java : Function to return type of Object

Below is the java program which shows how to detect type of object in an ArrayList containing different types of Object.


Output :

Mike String
999 Integer
99.0 Double
Thu Mar 21 17:31:29 IST 2013 Date
true Boolean
java.lang.Object@3e25a5 String
null null
 

Tuesday, February 19, 2013

Comfortable Work From Home: Compensated Survey

Do you usually bump into online surveys when you toggle from a website to the next? Ever question yourself why someone would compensate your effort with only completing a mere survey? Perhaps, you might be astounded that successful companies are ready to compensate anyone who shares their thoughts about the company. These companies wish for your opinions on what sort of merchandise you have a preference on, how you consider visiting shops online, and if their assistance is helpful or not, and so on. Your answers are very vital to the companies so they may be familiar with their customer’s opinions about their company so as to make enhancements and end up serving them better.

At this time, you take part here. The paid surveys are just one of the countless ways you can work from home ideas which companies propose online. Any person who has a belief on something can accomplish it without trouble and from your safe and cozy home. The quick transport from different work areas, the irritating time you have to change different uniforms, and the stress of really consuming more time outside than at home are easily prevented by just responding to surveys that pay you as your part-time work. Completing those added recommendations would not be needed for you to access a second occupation. They only necessitate your sincere view and they can easily reimburse you for just that.

Monday, February 18, 2013

Spring bean syntax




1. Import resources

Below is the syntax to import resources from various files. It is helpful when you want to bifurcated beans and database configuration in separate files and merger everything into single servlet. Here you can provide absolute or relative path of the source file.

<beans>
<import resource="file1.xml" />
<import resource="../file2.xml" />
</beans>

2. Spring MVC Dispatcher Servlet, syntax to load XMLs using init param

You can use it in web.xml file to XMLs using init param. You can load various XMLs like  beans and database configuration etc.

<web-app>
    <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>            
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/test/*.xml
            </param-value>        
        </init-param>        
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>/test/*.do</url-pattern>
    </servlet-mapping>
</web-app>

3. Url Handler Mapping syntax

Below is the example for Mapping URLs with respective beans, this is useful when you want to keep all URLs mapping together at one place.

<beans>

    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
        <props>
            <prop key="/sfc.do">simpleFormController</prop>
            <prop key="/mac.do">multiActionController</prop>
        </props>
        </property>
    </bean>


    <bean id="simpleFormController" class="com.javaxp.FormController" autowire="byName">
        <property name="commandName" value="formBean"></property>
        <property name="commandClass" value="com.javaxp.FormBean"></property>
        <property name="formView" value="form"></property>
        <property name="successView" value="submit"></property>        
    </bean>

    <bean id="multiActionController" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="action" />
<property name="defaultMethodName" value="defaultPage" />
    </bean>

</beans>

PHP example - Google Recaptcha validation using jquery (AJAX)

In earlier post we have seen JSP example, how to validate Recaptcha using jquery,  Now we will see how to achieve the same in PHP.

To know more about Google recaptcha, click here.

To run php example add recaptcha-php-1.11 in your application. Please see the self explanatory PHP code below.

test.php

JSP example - Google Recaptcha validation using jquery (AJAX)


Below is the example for Google Recaptcha validation using jquery(AJAX).

What is reCAPTCHA?

reCAPTCHA is a free CAPTCHA service that protects your site against spam, malicious registrations and other forms of attacks where computers try to disguise themselves as a human; a CAPTCHA is a Completely Automated Public Turing test to tell Computers and Human Apart. reCAPTCHA comes in the form of a widget that you can easily add to your blog, forum, registration form, etc.

To know more about Google recaptcha, please see below links
http://www.google.com/recaptcha
https://developers.google.com/recaptcha/

Please see self explanatory JSP code below. To run below example add recaptcha4j-0.0.7.jar file in your applications classpath.

test.jsp

Monday, February 11, 2013

java.lang.Exception: Socket bind failed: [730048] Only one usage of each socket address (protocol/network address/port) is normally permitted.

In earlier post, we have seen how to rid of - java.net.BindException: Address already in use: JVM_Bind :8080. Today i saw another similar error, please see the error below.


java.lang.Exception: Socket bind failed: [730048] Only one usage of each socket address (protocol/network address/port) is normally permitted.  
    at org.apache.tomcat.util.net.AprEndpoint.init(AprEndpoint.java:649)
    at org.apache.tomcat.util.net.AprEndpoint.start(AprEndpoint.java:766)
    at org.apache.coyote.http11.Http11AprProtocol.start(Http11AprProtocol.java:137)
    at org.apache.catalina.connector.Connector.start(Connector.java:1122)
    at org.apache.catalina.core.StandardService.start(StandardService.java:540)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Feb 11, 2013 8:13:42 PM org.apache.catalina.core.StandardService start
SEVERE: Failed to start connector [Connector[HTTP/1.1-8080]]
LifecycleException:  service.getName(): "Catalina";  Protocol handler start failed: java.lang.Exception: Socket bind failed: [730048] Only one usage of each socket address (protocol/network address/port) is normally permitted.  
    at org.apache.catalina.connector.Connector.start(Connector.java:1129)
    at org.apache.catalina.core.StandardService.start(StandardService.java:540)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Feb 11, 2013 8:13:42 PM org.apache.coyote.ajp.AjpAprProtocol start
SEVERE: Error starting endpoint

Wednesday, February 6, 2013

Oracle Moves Past 2012 Woes


Oracle had a bumpy ride in 2012. The company lost an important patent lawsuit centered on Google's Android platform, which must have hurt. In the last half of the year, a series of unpatched security flaws were discovered, leading to many industry experts recommending users remove Java from their browsers entirely.

Oracle wasn't exactly proactive with its response to the security flaws, which allowed malware to escape the Java "sandbox." Instead, the company stuck to its questionable policy of releasing patches on a restrictive and immutable schedule. To many, it looked like the company was closing the remote blinds on the office windows and hoping the problem would go away.

Still Number One

In spite of these setbacks, Java remains the shining star in Oracle's portfolio. Java maintains its position as the most used coding language in the Pypl Popularity Language Index.

The outlook for Java developers is also promising. For the second year in a row, technology professional website Dice ranked Java and J2EE developers as the most sought-after professionals in the industry.

Bye-Bye Java 6, Hello 7

Okay, Java 7 has actually been out for some time now, but plenty of enterprises and consumers are still happy with Java 6. That's going to change in February 2013, when the last public patch for Java 6 comes out. After that, you're on your own as far as Java 6 security goes.

The first patch for Java 7 is due out during the summer of 2013, so you have plenty of time to roll over from Java 6 to the new version. Just don’t leave it too late; running an obsolete version of Java is an invitation for security breaches.


Java Closes One Door, Opens another


The last public security patch for Java 6 comes out February 19, 2013, marking an important turning point for Oracle. Java 6 was developed by Sun Microsystems, which Oracle bought out for a purported $7.4 billion in 2011. Java 7, in contrast, is the first edition of Java released by Oracle. With Java 6 retired, Oracle cuts the program’s last ties to its parent company.

To be totally fair, Java 6 enjoyed a longer life than previous editions. The final public patch was originally scheduled for July 2012, and then bumped back to November 2012. Despite these two reprieves, it looks like the end is finally in sight.

Life after Retirement  

The final security patch serves as a warning to consumers and businesses. Oracle continues to provide security patches to enterprises with support plans after a final public patch, but for those of us without support plans, it's time to consider switching to Java 7.

Sure, in theory you could continue to use Java 6, but without the safety net of security updates you're asking for trouble. Old and retired programs attract hackers and malware like hyenas circling an injured antelope. Both sets of scavengers know their preys' defenses are down.

If you’re looking to update to Java 7, do so before June 18, 2013. The date marks the first major patch for the new system. (Don't get me started on Oracle's ironclad update schedule; in my mind, patches should be released when they're needed, rather than on a fixed timetable. Emergency response teams and drug rehab centers offer protection and help when it's most needed. To my mind, security patches are the virtual equivalent).


Wednesday, January 23, 2013

Element (center) is obsolete. Its use is discouraged in HTML5 documents


In latest version of HTML (HTML 5.0), CENTER tag is deprecated. So instead of using Tag <center>..</center>, you can use text-align:center. 'text-align' property doesn't actually aligns the division, it aligns the text content within the division.

Inline -

<div style="text-align:center">your content...</div>

Css -

.center {
  text-align:center
}

<div class="center">your content...</div>

SAXException - Failed to resolve: arg0=-//GetAhead Limited//DTD Direct Web Remoting *.0//EN

In my previous article I have shown you a simple hello world DWR example however while trying to implement it in an application I faced below exception.


SEVERE: DwrServlet.init() failed
org.xml.sax.SAXException: Failed to resolve: arg0=-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN arg1=http://directwebremoting.org/schema/dwr30.dtd
at org.directwebremoting.impl.DTDEntityResolver.resolveEntity(DTDEntityResolver.java:59)
at com.sun.org.apache.xerces.internal.util.EntityResolverWrapper.resolveEntity(EntityResolverWrapper.java:107)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.resolveEntityAsPerStax(XMLEntityManager.java:1018)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1190)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1089)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1002)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
at org.directwebremoting.impl.DwrXmlConfigurator.setInputStream(DwrXmlConfigurator.java:132)
at org.directwebremoting.impl.DwrXmlConfigurator.setServletResourceName(DwrXmlConfigurator.java:87)
at org.directwebremoting.impl.ContainerUtil.configureFromDefaultDwrXml(ContainerUtil.java:263)
at org.directwebremoting.impl.ContainerUtil.configureContainerFully(ContainerUtil.java:421)
at org.directwebremoting.servlet.DwrServlet.init(DwrServlet.java:79)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:791)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:127)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:619)
Jan 16, 2013 2:05:46 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet dwr-invoker
org.xml.sax.SAXException: Failed to resolve: arg0=-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN arg1=http://directwebremoting.org/schema/dwr30.dtd
at org.directwebremoting.impl.DTDEntityResolver.resolveEntity(DTDEntityResolver.java:59)
at com.sun.org.apache.xerces.internal.util.EntityResolverWrapper.resolveEntity(EntityResolverWrapper.java:107)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.resolveEntityAsPerStax(XMLEntityManager.java:1018)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1190)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1089)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1002)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
at org.directwebremoting.impl.DwrXmlConfigurator.setInputStream(DwrXmlConfigurator.java:132)
at org.directwebremoting.impl.DwrXmlConfigurator.setServletResourceName(DwrXmlConfigurator.java:87)
at org.directwebremoting.impl.ContainerUtil.configureFromDefaultDwrXml(ContainerUtil.java:263)
at org.directwebremoting.impl.ContainerUtil.configureContainerFully(ContainerUtil.java:421)
at org.directwebremoting.servlet.DwrServlet.init(DwrServlet.java:79)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:791)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:127)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:174)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:874)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689)
at java.lang.Thread.run(Thread.java:619)
Jan 16, 2013 2:09:33 AM org.apache.catalina.startup.HostConfig checkResources


JavaScript - onscroll function not working


Today I faced a weird issue, when I add below DOCTYPE in HTML or JSP file onscroll function stops working

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Also I saw that, document.body.scrollTop is always coming as 0 and document.body.scrollHeight & document.body.clientHeight are always same no matter where my scroll bar is.

I didn't get much time to do research on it however to resolve this I modified DOCTYPE as shown below. If you need quick fix please add below DOCTYPE in your HTML or JSP file.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

If I find more info on it, I will update the post.